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
<repo_name>martinslabber/smosl<file_sep>/logparser/smosl2file.py #!/usr/bin/env python from __future__ import print_function import sys import argparse from util import parse_msg parser = argparse.ArgumentParser(description='Parse log lines from STDIN.') parser.add_argument('-o', '--file', dest='filename', action='store', help='Filename to store metric to.') parser.add_argument('-r', '--fileflush', dest='flush', action='store', help='Save to disk after this many metric has been ' 'recieved.') args = parser.parse_args() flush_rate = args.flush try: flush_rate = int(flush_rate) except (ValueError, TypeError): flush_rate = 100 if flush_rate < 0 or flush_rate > 10000: flush_rate = 100 filename = args.filename if not filename: print('Please supply a filename with --file or see --help for more.') sys.exit(1) with open(filename, 'a') as fh: counter = 0 while 1: # Endless loop and read STDIN try: line = sys.stdin.readline() except KeyboardInterrupt: break if not line: break for n in parse_msg(line): fh.write(','.join(n) + '\n') counter += 1 if counter >= flush_rate: counter = 0 fh.flush() # <file_sep>/enter_python_ve.sh # # Call this script as a bash include. # . ./enter_python_ve.py # Note the dot space dot slash virtualenv ve . ./ve/bin/activate pip install -q nose <file_sep>/python-client/README.rst System Monitoring Over Syslog - Client Module ============================================= A python client to format `Metrics`_ and send it to syslog. This is useful for sending custom metrics to smosl. For system metrics see the smosl collectd example. Smosl uses syslog as the transport for the metrics. You are using syslog already, right? So we ship the metrics via the same channel. Often in production syslog is already setup to ship logs to centralised log storage or processing nodes. Installation ------------ Use pip to install from pypi. :: sudo pip install smosl Use pip to install from source. (Run this command from where code was checked out to.):: pip install -U . usage ----- The module can be used from within an application to record metrics. eg. :: import smosl metric = smosl.SmoslMetric() # Send one metric. metric.send_one('connections', 10) # Send several metrics. stats = {'connections': 11, 'errors': 3, 'loggedin_users': 9} metric.send(**stats) smosl_send ---------- This utility can be used from the command line or from shell scripts. It is used to send metric the SMOSL way. This script can also be used in a PIPE and accepts values via STDIN. PIPE Example ^^^^^^^^^^^^ Adding the *-i* argument to *smosl_send* tells it to listen to STDIN for metric values. If the metric name is given each line shoudl only contain the value. If metric name is not given the metric name must be send with each value. Eg. :: MemTotal=1017796000 MemFree=837588000 Buffers=17512000 This example sends the meminfo of a Linux system to smosl. :: cat /proc/meminfo | sed -e " s/://" | awk '{ V=$2; if ($3 == "kB") V=V*1000; print $1"="V}' | smosl_send -t number -i This example sends the *sysctl* to SMOSL works on Linux and Mac. :: sysctl -a | sed -e " s/:/=/g" | ./smosl_send -i -t number --path sysctl Metrics ------- A key value pair that represent measurement or monitored status. eg. fanspeed at 78 Further ------- At https://github.com/martinslabber/smosl there are further examples of using SMOSL with collectd to get overall view of a system. <file_sep>/python-client/smosl_send #!/usr/bin/env python from __future__ import print_function import sys import argparse import smosl def arg_parse(): """ Not implemented but something like this can be added. -h, --host=STRING host to send to -p, --port=INT port to use -t, --tcp use tcp not udp. -d, --device=STRING use device other than /dev/log - Cannot use with -p or -h """ parser = argparse.ArgumentParser() parser.add_argument('-n', '--name', dest='metric_name', action='store', help='Name of the metric.') parser.add_argument('-v', '--value', dest='metric_value', action='store', help='Value of the metric.') parser.add_argument('-t', '--type', dest='metric_type', action='store', choices=['text', 'number', 'boolean'], help='Type of the metric.') parser.add_argument('-i', '--stdin', dest='use_stdin', action='store_true', help='Metric data is received on standard in.') parser.add_argument('-s', '--path', dest='path', action='store', help='Path of metric. eg. if path is meminfo and ' 'metric if free the metric will be recorded ' 'as meminfo:freemem') parser.add_argument('-q', '--quiet', dest='quiet', action='store_true', help='Suppress the message. ' 'No Error messages will be printed.') return vars(parser.parse_args()) def send(service, metric_name, metric_value, metric_type=None): """Send one metric to syslog. Parameters ---------- service: Smosl Object A Smosl object to use. metric_name: str Name of the metric metric_value: str Value of metric metric_type: str Type of metric """ custom_none = '++This is not possible to send++' if metric_type == 'boolean': try: if metric_value is None: value = None else: value = bool(metric_value) except ValueError as e: print('Exception:', e) value = custom_none elif metric_type == 'number': try: value = float(metric_value) except ValueError as e: print('Exception:', e) value = custom_none else: if metric_value: value = str(metric_value) else: print('{0} value did not work: "{1}"'.format(metric_name, metric_value)) value = custom_none if value is not custom_none: service.send_one(metric_name, value) def stdin_func_factory(settings): """Return the function to use for string parsing in STDIN mode. Parameters ---------- settings: dict Dictionary with the settings. Returns ------- func The function to use for line parsing. """ if settings.get('metric_name'): # Each line is treated as a metric value. def parse_line(service, line): send(service, settings.get('metric_name'), line, settings.get('metric_type')) else: # Each line is treated as metric name and metric value # separated by a '=' def parse_line(service, line): segments = line.split('=', 1) if len(segments) > 1: send(service, segments[0].strip(), segments[1].strip()) return parse_line if __name__ == "__main__": settings = arg_parse() metric = smosl.SmoslMetric(path=settings.get('path')) if settings.get('metric_name') and settings.get('metric_value'): send(metric, settings.get('metric_name'), settings.get('metric_value'), settings.get('metric_type')) if settings.get('use_stdin'): stdin_func = stdin_func_factory(settings) counter = 0 while 1: try: line = sys.stdin.readline() except KeyboardInterrupt: break if line: stdin_func(metric, line.strip()) else: break # <file_sep>/logparser/smosl2redis.py #!/usr/bin/env python import sys import redis from util import parse_msg def save(db, metric_host, metric_key, metric_time, metric_value): db.hset(metric_host + ':' + metric_key, metric_time, metric_value) db = redis.Redis(db=9) while 1: try: line = sys.stdin.readline() except KeyboardInterrupt: break if not line: break for n in parse_msg(line): save(db, *n) <file_sep>/logparser/README.rst A bunch of utility script that read STDIN and save the metric. The scripts work best with a syslog daemon. .. note:: These scripts have only been tested with rsyslog v7. Installation ============== #. Copy the appropriate log handler from this directory to */usr/local/bin* :: sudo cp smosl2file.py /usr/local/bin/. #. Setup rsyslog. (copy example file *100-smosl.config* to */etc/rsyslog.d* and edit) smosl2file ========== This script reads STDIN and save each metric as a new line in the specified file. Destination filename must be given with the -o or --file argument. Reference ========= `SMOSL <https://pypi.python.org/pypi/smosl>`_ <file_sep>/syslog/smosl2file.py #!/usr/bin/python import re import sys import shlex import time import datetime def convert_enddate_to_seconds(ts): """Takes ISO 8601 format(string) and converts into epoch time.""" dt = datetime.datetime.strptime(ts[:-7], '%Y-%m-%dT%H:%M:%S.%f') + \ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:])) * int(ts[-6:-5] + '1') seconds = time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0 return seconds def parse_msg(inmsg): metrics = shlex.split(unicode(inmsg)) if metrics: try: mtime = convert_enddate_to_seconds(metrics[0]) # TODO(MS): Convert to timestamp UTC. host = re.sub('[^a-z0-9_.]+', '', metrics[1].lower()) for metric in metrics[3:]: if '=' in metric: key, value = metric.split('=', 1) key = re.sub('[^a-z0-9_:]+', '', key.lower()) yield (host + ':' + key, mtime, value) else: print 'ERROR', metric, inmsg except ValueError: return def save(fh, metric_key, metric_time, metric_value): fh.write(",".join(map(str, [metric_time, metric_key, metric_value])) + '\n') fh = open('/tmp/metric_data.csv', 'a') fh.write('# Started\n') fh.flush() counter = 0 while 1: try: line = sys.stdin.readline() except KeyboardInterrupt: break if not line: break for n in parse_msg(line): save(fh, *n) counter += 1 if counter > 1: counter = 0 fh.flush() fh.close() # <file_sep>/python-client/setup.py # SMOSL Setup.py from setuptools import setup, find_packages setup(name='smosl', version='0.1', description='System Monitoring Over SysLog', author='martinslabber', url='https://github.com/martinslabber/smosl', classifiers=["Development Status :: 4 - Beta", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python"], platforms=["OS Independent"], scripts=["smosl_send"], packages=find_packages()) <file_sep>/python-client/tox.ini [tox] envlist = py26,py27,py34 [testenv] deps=nose commands=nosetests <file_sep>/logparser/util.py import re import time import shlex import datetime def convert_enddate_to_seconds(ts): """Takes ISO 8601 format(string) and converts into epoch time.""" dt = datetime.datetime.strptime(ts[:-7], '%Y-%m-%dT%H:%M:%S.%f') + \ datetime.timedelta(hours=int(ts[-5:-3]), minutes=int(ts[-2:])) * int(ts[-6:-5] + '1') seconds = time.mktime(dt.timetuple()) + dt.microsecond / 1000000.0 return seconds def parse_msg(inmsg): metrics = shlex.split(unicode(inmsg)) if metrics: mtime = convert_enddate_to_seconds(metrics[0]) host = re.sub('[^a-z0-9_.]+', '', metrics[1].lower()) for metric in metrics[3:]: if '=' in metric: key, value = metric.split('=', 1) key = re.sub('[^a-z0-9_:]+', '', key.lower()) yield (host, key, mtime, value) else: print('ERROR', metric, inmsg) # <file_sep>/python-client/smosl/__init__.py import sys import zlib import logging import logging.handlers class SmoslMetric(object): def __init__(self, server=None, port=None, path=None): self._path = [] self._address = '/dev/log' self._change_detection = {} self._log_level = logging.INFO if sys.platform == "darwin": self._address = "/var/run/syslog" self._log_level = logging.WARN if server: self._address = (server, port or 514) self._logger = logging.getLogger('smosl') self._setup_logger() if isinstance(path, str): path = path.split(':') if path: self.path = [n for n in path if n] def _setup_logger(self): """Configure the python logger.""" self._logger.setLevel(logging.INFO) ## Attach Syslog as a handler syslog_handler = logging.handlers.SysLogHandler(address=self._address) syslog_handler.setLevel(self._log_level) syslog_handler.setFormatter(logging.Formatter('metric: %(message)s')) self._logger.addHandler(syslog_handler) def _send(self, msg): """Send the message to syslog.""" self._logger.log(self._log_level, '@smosl ' + msg) @property def path(self): """The key hierarchy path for this class.""" return self._path @path.setter def path(self, value): if not value: self._path = [] elif isinstance(value, list): self._path = value else: self._path = str(value).split(":") def attache_console(self, format=None): """attach the console to Log messages.""" console_handler = logging.StreamHandler() console_handler.setLevel(logging.INFO) console_handler.setFormatter( logging.Formatter('%(levelname)s:%(filename)s:%(lineno)d -- ' '%(message)s')) self._logger.addHandler(console_handler) def send_one(self, metric_name, metric_value): """Send one metric value.""" return self.send(**{metric_name: metric_value}) def send(self, **kwargs): """Send to syslog.""" msg = [] for kwkey, value in kwargs.items(): key = ":".join(self._path + [kwkey]) if value is None: msg.append('{0}=N'.format(key)) elif isinstance(value, str): msg.append('{0}="{1}"'.format(key, str(value))) elif isinstance(value, bool): msg.append('{0}={1}'.format(key, str(value)[0])) elif isinstance(value, (int, float)): msg.append('{0}={1}'.format(key, value)) else: raise ValueError('Cannot interprete {0} of type {1}'. format(value, type(value))) self._send(' '.join(msg)) def send_on_change(self, **kwargs): """Keep track of metrics and values. Send if there was a change.""" send_update = {} for kwkey, value in kwargs.items(): akey = zlib.adler32(str(kwkey).encode('UTF-8')) aval = zlib.adler32(str(value).encode('UTF-8')) if self._change_detection.get(akey) != aval: self._change_detection[akey] = aval send_update[kwkey] = value if send_update: self.send(**send_update) def flush_on_change(self): """Flush/Clear the on chnage detection storage.""" self._change_detection = {} <file_sep>/python-client/tests/test_smosl.py from smosl import SmoslMetric class TestSMOSL(object): def setup(self): # Monkey patch the _send method to get the message that will be send # via syslog. self.smosl = SmoslMetric() self.test_result = '' def _send(b): self.test_result = b self.smosl._send = _send def test_01_send_one(self): self.smosl.send_one('one', 1) assert self.test_result == 'one=1' self.smosl.send_one('one', 'just one') assert self.test_result == 'one="just one"' self.smosl.send_one('one', True) assert self.test_result == 'one=T' self.smosl.send_one('one', None) assert self.test_result == 'one=N' def test_02_send(self): self.smosl.send(**{'one': 1}) assert self.test_result == 'one=1' self.smosl.send(one=1) assert self.test_result == 'one=1' def test_03_send_on_change(self): self.smosl.send_on_change(**{'one': 1}) assert self.test_result == 'one=1' self.smosl.send_on_change(one=1) assert self.test_result == 'one=1' self.smosl.send_on_change(one=2) assert self.test_result == 'one=2' self.test_result = '-' self.smosl.send_on_change(one=2) assert self.test_result == '-' self.smosl.send_on_change(one=2) assert self.test_result == '-' self.smosl.send_on_change(one=3) assert self.test_result == 'one=3' <file_sep>/collectd/smosl_collectd.py ######## # # Use this file with collectd. # """ # Copy this file to: /usr/local/.../smosl_collectd sudo pip install collectd sudo pip install smosl # Add the following to Collectd Config LoadPlugin python <Plugin python> ModulePath "/usr/local/.../smosl_collectd" LogTraces true # Interactive true Import "smosl_collectd" </Plugin> """ import smosl import collectd metric = smosl.SmoslMetric(path='collectd') metric.send_on_change(**{"startup": 'nod'}) def write(vl, data=None): name_segments = [] for item in [vl.plugin, getattr(vl, 'plugin_instance', None), vl.type, getattr(vl, 'type_instance', None)]: if item: item = str(item).lower().replace('-', '_') if item not in name_segments: name_segments.append(item) name = ":".join(name_segments) if name == 'load': send_data = {name + ':1': vl.values[0], name + ':5': vl.values[1], name + ':15': vl.values[2]} else: send_data = {name: vl.values[0]} metric.send_on_change(**send_data) collectd.register_write(write) <file_sep>/README.rst System Monitoring Over SysLog (SMOSL) ======================================= ALPHA.! At the moment this is some old code pulled out of the closet and dumped here in the hope it will get structure. * Monitoring metrics are send through in the message part or a syslog message. * Metrics are space separated from one another * Key is separated from value with '=' (equals) no spaces eg. :: app1:database:open_connections=5 app1:database:last_error="out of memory" The JSON equivalent would be. :: {app1: {database: {open_connections: 5, last_error: "out of memory"}}} Installation ------------- :: cp smosl.py /usr/local/bin/smosl.py cp 100-smosl.conf /etc/rsyslog.d/. sudo service ryslog restart Keys ---- The key contain a hierarchy, sections in the hierarchy are separated from one another with the ':' character. The key and all it sections are case insensitive and should only consist out of 'a' to 'z', '0' to '9' and the '_' character. When key is processed the key will be converted to lower case, any character not in the above listed set will be dropped. Value Types ----------- SMOSL has only 3 data types, it is up to the client to force values into one of the following types: Text, Number and Boolean. Text ^^^^ * Value part must be surrounded by '"' (double quotes). * Length of string is only limited by syslog implementation. Example: :: metric:name="The string value." The JSON equivalent would be. :: {metric: {hour: "The string value."}} Number ^^^^^^ * All numbers are converted to a floating point number. * If conversion failed value is discarded. Example: :: metric:hour=24 The JSON equivalent would be. :: {metric: {hour: 24}} Boolean (True, False, Null, None) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * T, F or N Could work nice for boolean and null. * The lack of a value (a '=' followed by a space) should be treated as a Null. :: metric:seg1:seg2=T The JSON equivalent would be. :: {metric: {seg1: {seg2: true}}}
e19b00a579679e8626e985b3b6aeff878d73bcaf
[ "INI", "Python", "reStructuredText", "Shell" ]
14
Python
martinslabber/smosl
ff59f2ff2cf09e5fd515bba9442eb7e1dd373fa9
b16addf7f830da0eb86953686f6aa7c6ed554900
refs/heads/master
<file_sep>define( [ 'jquery', 'uiComponent', 'Magento_Checkout/js/model/payment/renderer-list' ], function ($, Component, rendererList) { 'use strict'; var defaultComponent = 'Payssion_Payment/js/view/payment/method-renderer/default'; var methods = [ {type: 'payssion_payment_alipay_cn', component: defaultComponent}, {type: 'payssion_payment_atmva_id', component: defaultComponent}, {type: 'payssion_payment_bitcoin', component: defaultComponent}, {type: 'payssion_payment_boleto_br', component: defaultComponent}, {type: 'payssion_payment_cashu', component: defaultComponent}, {type: 'payssion_payment_enets_sg', component: defaultComponent}, {type: 'payssion_payment_eps_at', component: defaultComponent}, {type: 'payssion_payment_fpx_my', component: defaultComponent}, {type: 'payssion_payment_giropay_de', component: defaultComponent}, {type: 'payssion_payment_ideal_nl', component: defaultComponent}, {type: 'payssion_payment_maybank2u_my', component: defaultComponent}, {type: 'payssion_payment_onecard', component: defaultComponent}, {type: 'payssion_payment_p24_pl', component: defaultComponent}, {type: 'payssion_payment_paysbuy_th', component: defaultComponent}, {type: 'payssion_payment_poli_au', component: defaultComponent}, {type: 'payssion_payment_poli_nz', component: defaultComponent}, {type: 'payssion_payment_qiwi', component: defaultComponent}, {type: 'payssion_payment_sberbank_ru', component: defaultComponent}, {type: 'payssion_payment_singpost_sg', component: defaultComponent}, {type: 'payssion_payment_sofort', component: defaultComponent}, {type: 'payssion_payment_webmoney', component: defaultComponent}, {type: 'payssion_payment_yamoney', component: defaultComponent} ]; $.each(methods, function (k, method) { rendererList.push(method); }); return Component.extend({}); } );
a29cb1350e043c8d430015051779e820356271b5
[ "JavaScript" ]
1
JavaScript
patrickouc/plugin_magento2
8b2b87597d485bd0c0e967f72dc2e41ca411c04c
0fcd512ce8de9d1a2aadb6573ab90dfcbf0f439a
refs/heads/main
<repo_name>Arteuss/Learning-Simulator<file_sep>/Assets/Scripts/ProjectUI/UiView.cs using System; using System.Collections.Generic; using DG.Tweening; using TMPro; using UnityEngine; using UnityEngine.UI; namespace ProjectUI { public class UiView : MonoBehaviour { #region Variables [SerializeField] private List<Button> _startButtons; [SerializeField] private GameObject _startPanel; [SerializeField] private GameObject _taskPanel; [SerializeField] private GameObject _endPanel; [SerializeField] private GameObject _resultPanel; [SerializeField] private TextMeshProUGUI _taskText; [SerializeField] private TextMeshProUGUI _endTitleText; [SerializeField] private Button _continueButton; [SerializeField] private Button _restartButton; [SerializeField] private TextMeshProUGUI _mistakesText; [SerializeField] private TextMeshProUGUI _learningTimeText; private CanvasGroup _cgStartPanel; private CanvasGroup _cgTaskPanel; private CanvasGroup _cgEndPanel; private const string EndTitleWrong = "Вы допустили ошибку!"; private const string EndTitleComplete = "Обучение пройдено!"; private const string Mistakes = "Kоличество ошибок - "; private const string LearningTime = "Время обучения - "; #endregion public Action<int> onSelect; public Action onRestart; private void Start() { _cgStartPanel = _startPanel.GetComponent<CanvasGroup>(); _cgTaskPanel = _taskPanel.GetComponent<CanvasGroup>(); _cgEndPanel = _endPanel.GetComponent<CanvasGroup>(); for (int i = 0; i < _startButtons.Count; i++) { var num = i; var button = _startButtons[i]; button.onClick.AddListener( () => OnButtonClick(num)); } _continueButton.onClick.AddListener(OnContinueClick); _restartButton.onClick.AddListener(OnRestartClick); HidePanel(_cgTaskPanel); HidePanel(_cgEndPanel); ShowPanel(_cgStartPanel); } public void UpdateUi(DataForUi data) { _taskText.text = data.Message; if (!data.IsShowPopup) return; if (data.IsFinish) ShowEndPanel(data.Mistakes, data.LearningTime); else ShowWrongPanel(); } private void OnButtonClick(int num) { onSelect(num); HidePanel(_cgStartPanel); ShowPanel(_cgTaskPanel); } private void OnRestartClick() { HidePanel(_cgEndPanel); HidePanel(_cgTaskPanel); ShowPanel(_cgStartPanel); onRestart.Invoke(); } private void OnContinueClick() { HidePanel(_cgEndPanel); } private void HidePanel(CanvasGroup panel) { DOTween.To(()=> panel.alpha, x=> panel.alpha = x, 0, 0.5f); panel.blocksRaycasts = false; } private void ShowPanel(CanvasGroup panel) { DOTween.To(()=> panel.alpha, x=> panel.alpha = x, 1, 0.5f); panel.blocksRaycasts = true; } private void ShowEndPanel(int mistakeCount, TimeSpan timer) { _endTitleText.text = EndTitleComplete; _continueButton.gameObject.SetActive(false); _resultPanel.SetActive(true); _mistakesText.text = $"{Mistakes}{mistakeCount}"; _learningTimeText.text = $"{LearningTime} {timer.Minutes} м. {timer.Seconds} с."; ShowPanel(_cgEndPanel); HidePanel(_cgTaskPanel); } private void ShowWrongPanel() { _endTitleText.text = EndTitleWrong; _continueButton.gameObject.SetActive(true); _resultPanel.SetActive(false); ShowPanel(_cgEndPanel); } } }<file_sep>/Assets/Scripts/Configs/SimulatorScenarioConfig.cs using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "SimulatorCreator/SimulatorScenario", fileName = "SimulatorScenario")] public class SimulatorScenarioConfig : ScriptableObject { [SerializeField] private GameObject _devicePrefab; [SerializeField] private List<ElementConfig> _elementConfigs = new List<ElementConfig>(); public GameObject DevicePrefab => _devicePrefab; public List<ElementConfig> ElementConfigs => _elementConfigs; }<file_sep>/Assets/Scripts/ISimulatorModel.cs using System; public interface ISimulatorModel { /// <summary> /// Обработка выбора устройства /// </summary> /// <param name="num">id устройства</param> void OnSelectDevice(int num); /// <summary> /// Рестарт устройств на сцене /// </summary> void Restart(); /// <summary> /// Событие обновления ui /// </summary> event Action<DataForUi> UpdateUi; // event Action<string, bool, bool> UpdateUi; }<file_sep>/Assets/Scripts/DeviceSpawner.cs using System.Collections.Generic; using UnityEngine; public class DeviceSpawner : IDeviceSpawner { private readonly DevicesConfigs _devicesConfigs; private List<Device> _simulatorViews = new List<Device>(); private List<SimulatorScenarioConfig> _simulatorScenarioConfig = new List<SimulatorScenarioConfig>(); private List<GameObject> _devices = new List<GameObject>(); public DeviceSpawner(DevicesConfigs devicesConfigs) { _devicesConfigs = devicesConfigs; foreach (var scenarioConfig in _devicesConfigs.ScenarioConfigs) { _simulatorScenarioConfig.Add(scenarioConfig); if (scenarioConfig.DevicePrefab) Spawn(scenarioConfig.DevicePrefab); } HideAll(); } private void Spawn(GameObject devicePrefab) { var device = GameObject.Instantiate(devicePrefab); var simulatorView = device.GetComponent<Device>(); if(simulatorView) _simulatorViews.Add(simulatorView); _devices.Add(device); } public void ShowDevice(int numDevice, out SimulatorScenarioConfig simulatorScenarioConfig, out Device device) { var deviceGO = _devices[numDevice]; deviceGO.transform.position = Vector3.zero; device = deviceGO.GetComponent<Device>(); simulatorScenarioConfig = _simulatorScenarioConfig[numDevice]; } public void HideAll() { foreach (var device in _devices) { device.transform.position = Vector3.one * 100f; } } }<file_sep>/Assets/Scripts/Configs/ElementConfig.cs using System; using System.Collections.Generic; using UnityEngine; [Serializable] [CreateAssetMenu(menuName = "SimulatorCreator/ElementConfig", fileName = "ElementConfig")] public class ElementConfig : ScriptableObject { public List<SimulatorElement> Element; public string TaskText; }<file_sep>/Assets/Scripts/SimulatorElement.cs using UnityEngine; public class SimulatorElement : MonoBehaviour { private Device _simulator; private bool _isEnable; [SerializeField] private AnimationClip _onClip; [SerializeField] private AnimationClip _offClip; [SerializeField] private string _elementId; public string ElementId => _elementId; private Animation AnimationE { get; set; } private void Start() { _isEnable = true; _simulator = GetComponentInParent<Device>(); AnimationE = GetComponent<Animation>(); } public void OnClickElement() { _simulator.SetElement(this); } public void PlayAnimation() { AnimationE.Play(_isEnable ? _offClip.name : _onClip.name); _isEnable = !_isEnable; } public void ResetElement() { AnimationE.Play(_onClip.name); _isEnable = true; } } <file_sep>/Assets/Scripts/SystemInstaller.cs using ProjectUI; using UnityEngine; using Zenject; public class SystemInstaller : MonoInstaller { [SerializeField] private DevicesConfigs _devicesConfigs; public override void InstallBindings() { Container.Bind<UiView>().FromComponentInHierarchy().AsSingle(); Container.BindInstance(_devicesConfigs).AsSingle(); Container.QueueForInject(_devicesConfigs); Container.BindInterfacesAndSelfTo<UiController>().AsSingle().NonLazy(); Container.BindInterfacesAndSelfTo<DeviceSpawner>().AsSingle().NonLazy(); Container.BindInterfacesAndSelfTo<SimulatorModel>().AsSingle().NonLazy(); } }<file_sep>/Assets/Scripts/Device.cs using System; using System.Collections.Generic; using System.Linq; using UnityEngine; public class Device : MonoBehaviour { public event Action<SimulatorElement> OnClickElement; private List<SimulatorElement> _elements = new List<SimulatorElement>(); private void Awake() { _elements = GetComponentsInChildren<SimulatorElement>().ToList(); } public void SetElement(SimulatorElement element) { OnClickElement.Invoke(element); } public void ResetElements() { foreach (var simulatorElement in _elements) { simulatorElement.ResetElement(); } } }<file_sep>/Assets/Scripts/DataForUi.cs using System; using UnityEngine; public struct DataForUi { public string Message; public bool IsShowPopup; public bool IsFinish; public int Mistakes; public TimeSpan LearningTime; public DataForUi( string message, bool isShowPopup, bool isFinish, int mistakes, TimeSpan learningTime ) { Message = message; IsShowPopup = isShowPopup; IsFinish = isFinish; Mistakes = mistakes; LearningTime = learningTime; } }<file_sep>/Assets/Scripts/IDeviceSpawner.cs public interface IDeviceSpawner { /// <summary> /// Показать выбранное устройство /// </summary> /// <param name="numDevice">id устройство</param> /// <param name="simulatorScenarioConfig">Конфиг сценария обучения</param> /// <param name="device">Устройство</param> void ShowDevice(int numDevice, out SimulatorScenarioConfig simulatorScenarioConfig, out Device device); /// <summary> /// Скрыть все устройства /// </summary> void HideAll(); }<file_sep>/Assets/Scripts/InputManager.cs using System; using UnityEngine; public class InputManager : MonoBehaviour { private Ray _ray; private Camera _camera; private void Start() { _camera = Camera.main; } private void Update() { if (Input.GetMouseButtonDown(0)) { _ray = _camera.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(_ray, out var hitInfo)) { var element = hitInfo.transform.GetComponentInParent<SimulatorElement>(); if (element != null) { element.OnClickElement(); } } } } }<file_sep>/Assets/Scripts/Configs/SimulatorScenarioConfigInspector.cs using UnityEditor; using UnityEditorInternal; using UnityEngine; namespace Configs { [CustomEditor(typeof(SimulatorScenarioConfig))] public class SimulatorScenarioConfigInspector : Editor { /// <summary> /// Список элементов в сценарии /// </summary> private ReorderableList _elementsList; /// <summary> /// Высота линии /// </summary> private float _lineHeight; private void OnEnable() { if(target == null) return; _lineHeight = EditorGUIUtility.singleLineHeight; _elementsList = new ReorderableList(serializedObject, serializedObject.FindProperty("_elementConfigs"),true,false,true,true); _elementsList.drawElementCallback = (rect, index, active, focused) => { var element = _elementsList.serializedProperty.GetArrayElementAtIndex(index); var offset = 30; if (element != null) { EditorGUI.LabelField(new Rect(rect.x, rect.y, offset, rect.height), $"#{index}"); EditorGUI.PropertyField(new Rect(rect.x + offset, rect.y, rect.width - offset, rect.height), element, GUIContent.none); } }; _elementsList.elementHeightCallback = index => _lineHeight; } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUI.PropertyField(new Rect(15, 10, 400, _lineHeight), serializedObject.FindProperty("_devicePrefab"), GUIContent.none); EditorGUILayout.Space(30); GUILayout.Label("Elements:"); _elementsList.DoLayoutList(); serializedObject.ApplyModifiedProperties(); } } }<file_sep>/Assets/Scripts/SimulatorModel.cs using System; using System.Collections.Generic; using System.Linq; public class SimulatorModel : ISimulatorModel { private Queue<EntryAction> _actions; private IDeviceSpawner _spawner; private SimulatorScenarioConfig _simulatorScenarioConfig; public event Action<DataForUi> UpdateUi; private Device _device; private int _mistakes; private TimeSpan _learningTimer; private DateTime _startTime; private DateTime _endTime; public SimulatorModel( IDeviceSpawner spawner) { _spawner = spawner; } public void OnSelectDevice(int num) { _startTime = DateTime.Now; _spawner.ShowDevice(num, out var simulatorScenarioConfig, out var device); _device = device; _device.OnClickElement -= OnClickElement; _device.OnClickElement += OnClickElement; _actions = new Queue<EntryAction>(simulatorScenarioConfig.ElementConfigs.Count); foreach (var elementConfig in simulatorScenarioConfig.ElementConfigs) { var action = new EntryAction(elementConfig.Element, elementConfig.TaskText); action.ElementsId[""] = true; _actions.Enqueue(action); } UpdateUi.Invoke(GetData(false, false)); } private string GetTextMessage() { var textMessage = ""; if(_actions.Count > 0) textMessage = _actions.Peek().TaskText; return textMessage; } public void Restart() { _actions.Clear(); _device.ResetElements(); _spawner.HideAll(); _mistakes = 0; } private void OnClickElement(SimulatorElement element) { if(_actions.Count < 1) return; var currentElement = _actions.Peek(); if (currentElement.ElementsId.ContainsKey(element.ElementId)) { if (!currentElement.ElementsId[element.ElementId]) { currentElement.ElementsId[element.ElementId] = true; element.PlayAnimation(); var allComplete = currentElement.ElementsId.All(elements => elements.Value); //Все части текущего задания завершены, удаляем его из очереди if (allComplete) { _actions.Dequeue(); if (_actions.Count < 1) { _endTime = DateTime.Now; _learningTimer = _endTime - _startTime; UpdateUi.Invoke(GetData(true, true)); } else { //Пишем сообщение про следующее задание UpdateUi.Invoke(GetData(false, false)); } } } } else { _mistakes++; //Пишем сообщение, что кликнули не то UpdateUi.Invoke(GetData(true, false)); } } private DataForUi GetData(bool isShowPopup, bool isFinish) { return new DataForUi(GetTextMessage(), isShowPopup, isFinish, _mistakes, _learningTimer); } }<file_sep>/Assets/Scripts/Configs/DevicesConfigs.cs using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "SimulatorCreator/DevicesConfigs", fileName = "DevicesConfigs")] public class DevicesConfigs : ScriptableObject { [SerializeField] private List<SimulatorScenarioConfig> _scenarioConfigs; public List<SimulatorScenarioConfig> ScenarioConfigs => _scenarioConfigs; }<file_sep>/Assets/Scripts/EntryAction.cs using System.Collections.Generic; public class EntryAction { public Dictionary<string, bool> ElementsId { get;} public string TaskText { get; } public EntryAction(List<SimulatorElement> elements, string taskText) { ElementsId = new Dictionary<string, bool>(); foreach (var element in elements) { ElementsId[element.ElementId] = false; } TaskText = taskText; } }<file_sep>/Assets/Scripts/ProjectUI/UiController.cs  using System; namespace ProjectUI { public class UiController: IDisposable { private ISimulatorModel _simulatorModel; private UiView _uiView; public UiController(ISimulatorModel simulatorModel, UiView uiView) { _simulatorModel = simulatorModel; _uiView = uiView; _uiView.onSelect = _simulatorModel.OnSelectDevice; _uiView.onRestart = _simulatorModel.Restart; _simulatorModel.UpdateUi += _uiView.UpdateUi; } public void Dispose() { _simulatorModel.UpdateUi -= _uiView.UpdateUi; } } }
254c21c7bf8e1b9b86d5f602b448111b2e1fe3ee
[ "C#" ]
16
C#
Arteuss/Learning-Simulator
41426eb32b88a17b971f7216da92d5f3a0a3a1fa
928b43cc720ce72206c14ac6436a5c2e4e648474
refs/heads/master
<repo_name>emmavanninen/react-router<file_sep>/front-react-router/src/components/User.js import React, { Component } from "react"; import Axios from "axios"; export default class User extends Component { state = { user: {}, isLoading: true, isError: false, errMsg: "" }; async componentDidMount() { try { let success = await Axios.get( `http://localhost:3001/users/get-user-by-id/${this.props.match.params.id}` ); let dataArr = success.data; this.setState({ user: dataArr[0], isLoading: false }); } catch (e) { this.setState({ isError: true, errMsg: e.response.data, isLoading: false }); // ! getting error status msg, use .response console.log(e.response); } } render() { // console.log(`!!!!`, this.props.match); // console.log(`?????`, this.props.location); return ( <div> {this.state.isLoading ? ( <h2>...loading</h2> ) : this.state.isError ? ( <h2>{this.state.errMsg}</h2> ) : ( <> <h2>name: {this.state.user.name}</h2> <h2>ID: {this.state.user.id}</h2> </> )} {/* //! props.match matches with the slug */} {/* <h2>User: {this.props.match.params.id}</h2> */} {/* <h2>Name: {this.props.location.state.name}</h2> */} </div> ); } } <file_sep>/front-react-router/src/App.js import React, { Component } from "react"; //! as Poop to rename import { BrowserRouter as Router, Route, Switch, Link } from "react-router-dom"; import Home from "./components/Home"; import Users from "./components/Users"; import User from "./components/User"; import AboutMe from "./components/AboutMe"; export default class App extends Component { render() { return ( //! Old version of BrowserRouter: HashBrowser <Router> <div> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/users">Users</Link> </li> <li> <Link to="/about-me">About me</Link> </li> </ul> </div> {/* //! with Switch statement only one thing is true */} <Switch> {/* //! exact to prevent showing everything with '/'' */} <Route path="/" exact component={Home} /> <Route path="/users" exact component={Users} /> //! ':id' is a slug or dynamic <Route path="/users/:id" exact component={User} /> <Route path="/about-me" exact component={AboutMe} /> {/* //! If nothing else, show Not Found */} <Route exact path="" render={() => <h1>Not Found</h1>} /> </Switch> </Router> ); } } <file_sep>/front-react-router/src/components/Users.js import React, { Component } from "react"; import { Link } from "react-router-dom"; import axios from "axios"; export default class Users extends Component { //! state is temporary data state = { users: [] }; async componentDidMount() { try { let success = await axios.get( "http://localhost:3001/users/get-all-users" ); let dataArray = success.data; this.setState({ users: dataArray }); // console.log(success); } catch (e) { console.log(e); } } render() { //! Object destructuring const { users } = this.state; return ( <div> <ul> {users.map((user, index) => { return ( <li key={user.id}> <Link to={`/users/${user.id}`}> user:ID {user.id} username: {user.name} </Link> {/* //! 'to' is Link property <Link to={{ pathname: `/users/${user.id}`, state: { name: user.name } }} > user:ID {user.id} username: {user.name} </Link> */} </li> ); })} </ul> </div> ); } } <file_sep>/back-react-router/react-router/routes/users.js var express = require("express"); var router = express.Router(); let users = [ { id: 1, name: "poop", age: "1 month" }, { id: 2, name: "Hamster", age: "999" }, { id: 3, name: "Toivo", age: "almost 4 yo" } ]; /* GET users listing. */ router.get("/", function(req, res, next) { res.send("poop"); }); router.get("/get-all-users", function(req, res) { res.json(users); }); router.get("/get-user-by-id/:id", function(req, res) { let userID = req.params.id; let foundUser = users.filter(user => user.id == userID); if (foundUser.length) { res.json(foundUser); } else { //! error status goes directly to catch block on axios res.status(404).send("User Not Found"); } }); module.exports = router;
08d3e40550e61e1609c19b8ec218da2f472b5dc3
[ "JavaScript" ]
4
JavaScript
emmavanninen/react-router
762767a11e70524a45328bb1e9e2eaad56cc08f9
33217d35bc160db7c5c45a222888861231ee386c
refs/heads/master
<repo_name>edithr2852/student-diary-project<file_sep>/README.md # Pseudo Diaries :page_facing_up: Project #2 Node/Express/MongoDB Full-stack CRUD Application ____________________________________________________________________________________________________________________________________________________________________ ## Application Overview #### Pseudo Diaries is an online diary for the SEIR-308 cohort. Here, students will be able to enter daily diaries about their day to day experience in this course. ## ERD ![erd](https://github.com/edithr2852/student-diary-project/blob/master/student-diary-project/Screen%20Shot%202021-04-15%20at%201.05.16%20AM.png) ## Wireframe ![wireframe](https://github.com/edithr2852/student-diary-project/blob/master/student-diary-project/Screen%20Shot%202021-04-15%20at%201.05.35%20AM.png) ## Finished Product ![App Preview2](https://github.com/edithr2852/student-diary-project/blob/master/student-diary-project/Screen%20Shot%202021-04-15%20at%201.06.17%20AM.png) ![GApp Preview](https://github.com/edithr2852/student-diary-project/blob/master/student-diary-project/Screen%20Shot%202021-04-15%20at%201.07.04%20AM.png) ## Technologies Used #### - Javascript #### - HTML #### - CSS #### - Boostrap #### - Express #### - Node.js #### - MongoDB #### - Mongoose ## [Pseudo Diaries](https://pseudo-diary-project.herokuapp.com/students) ## Next steps #### 1. We would like to make the page look better through Bootstrap and/or CSS #### 2. We would like to add an additional feature where students can comment on other student's diary entries for suggestions, support, etc.. #### 3. We want to restructure code so that we can make the application look like our wireframe. <file_sep>/student-diary-project/controllers/students.js const Student = require('../models/students'); const student = require('../models/students'); const diary = require('../models/students'); const Diary = require('../models/diaries'); function index(req, res) { Student.find({}, function(err, students) { res.render('students/index', {students}) }) } function show(req, res) { Student.findById(req.params.id, function(err, student){ res.render('students/show', {student, diary}) }) } function newStudent(req, res) { res.render('students/new', { name: "<NAME>"}); } function create(req, res){ Student.create(req.body); res.redirect('/students'); } function deleteOne(req, res){ Student.findByIdAndRemove(req.params.id, function(err, student) { res.redirect('/students'); }) } function update(req, res){ Student.findByIdAndUpdate(req.params.id, req.body, function(err, student) { res.redirect(`/students/${student.id}`) }) } module.exports = { index, show, new: newStudent, create, delete: deleteOne, update, }<file_sep>/student-diary-project/models/students.js const mongoose = require('mongoose'); const Schema = mongoose.Schema; const diarySchema = new Schema ({ date: {type: Date, required: true}, mood: {type: String, required: true}, diaryEntry: {type: String, required: true}, }); const studentSchema = new Schema( { name: String, location: String, preCodingExp: Boolean, diaries: [diarySchema] }, ); module.exports = mongoose.model('Student', studentSchema) <file_sep>/student-diary-project/controllers/diaries.js const Diary = require('../models/diaries'); const students = require('../models/students'); const Student = require('../models/students'); module.exports = { create, } function create(req, res) { Student.findById(req.params.id, function(err, student) { student.diaries.push(req.body); student.save(function(err) { res.redirect(`/students/${student._id}`); }); }); }<file_sep>/student-diary-project/routes/diaries.js var express = require('express'); var router = express.Router(); const diariesCtrl = require('../controllers/diaries'); router.post('/students/:id/diaries', diariesCtrl.create); module.exports = router; <file_sep>/student-diary-project/routes/students.js var express = require('express'); var router = express.Router(); const studentsCtrl = require('../controllers/students') router.get('/', studentsCtrl.index); router.get('/new', studentsCtrl.new); router.get('/:id', studentsCtrl.show); router.post('/', studentsCtrl.create); router.delete('/:id', studentsCtrl.delete); router.put('/:id', studentsCtrl.update); module.exports = router;
6d58956054af7b5b4f6f5fc1d20b680b5211137b
[ "Markdown", "JavaScript" ]
6
Markdown
edithr2852/student-diary-project
ff6ceaeeb6e890d76f974d20a46ddfecc7f3c963
3d4d8dee8aae1aa07f0e45175825e1e4411cb1d9
refs/heads/main
<repo_name>JuliaJindow/project-superhero-3<file_sep>/main.js var canvas = new fabric.Canvas("myCanvas"); var blockWidth = 30; var blockHeight = 30; var playerX = 10; var playerY = 10; var playerObject = ""; var blockObject = ""; function playerUpdate() { fabric.Image.fromURL("player.png", function(Img){ playerObject = Img; playerObject.scaleToWidth(150); playerObject.scaleToHeight(140); playerObject.set({ top:playerY, left:playerX }); canvas.add(playerObject); }); } function newImg(getImg) { fabric.Image.fromURL(getImg, function(Img){ blockObject = Img; blockObject.scaleToWidth(blockWidth); blockObject.scaleToHeight(blockHeight); blockObject.set({ top:playerY, left:playerX }); canvas.add(blockObject); }); } window.addEventListener("keydown", my_keydown); function my_keydown(e) { var keyPressed = e.keyCode; console.log(keyPressed); if (e.shiftKey == true && keyPressed == "80") { console.log("p & shift pressed together"); blockWidth = blockWidth + 10; blockHeight = blockHeight + 10; document.getElementById("currentWidth").innerHTML = blockWidth; document.getElementById("currentHeight").innerHTML = blockHeight; } if (e.shiftKey == true && keyPressed == "77") { console.log("m & shift pressed together"); blockWidth = blockWidth - 10; blockHeight = blockHeight - 10; document.getElementById("currentWidth").innerHTML = blockWidth; document.getElementById("currentHeight").innerHTML = blockHeight; } if (keyPressed == '70'){ newImg('ironman_face.png'); console.log("f"); } if (keyPressed == '66'){ newImg('spiderman_body.png'); console.log("b"); } if (keyPressed == '76'){ newImg('hulk_legs.png'); console.log("l"); } if (keyPressed == '82'){ newImg('thor_right_hand.png'); console.log("r"); } if (keyPressed == '72'){ newImg("captain_america_left_hand.png"); console.log("h"); } if (keyPressed == '38'){ up(); console.log("up"); } if (keyPressed == '40'){ down(); console.log("down"); } if (keyPressed == '37'){ left(); console.log("left"); } if (keyPressed == '39'){ right(); console.log("right"); } } function up() { if (playerY >= 50){ playerY = playerY - blockHeight; console.log("Block's height is " + blockHeight); console.log("When up arrow is pressed, x = " + playerX + "y = " + playerY); canvas.remove(playerObject); playerUpdate(); } } function down() { if (playerY <= 550){ playerY = playerY + blockHeight; console.log("Block's height is " + blockHeight); console.log("When down arrow is pressed, x = " + playerX + "y = " + playerY); canvas.remove(playerObject); playerUpdate(); } } function left() { if (playerX >= 50){ playerX = playerX - blockWidth; console.log("Block's width is " + blockWidth); console.log("When left arrow is pressed, x = " + playerX + "y = " + playerY); canvas.remove(playerObject); playerUpdate(); } } function right() { if (playerX <= 850){ playerX = playerX + blockWidth; console.log("Block's width is " + blockWidth); console.log("When right arrow is pressed, x = " + playerX + "y = " + playerY); canvas.remove(playerObject); playerUpdate(); } }
3ec78425be6d8b25612044bdd924b905af82fdfd
[ "JavaScript" ]
1
JavaScript
JuliaJindow/project-superhero-3
ca02189993f1ad018198937d2c054793d58aaa60
a1891897156a06f7ee48b0b7314b72db6d9d8dd6
refs/heads/master
<file_sep>package com.example.tddd80_projekt; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText; import com.android.volley.RequestQueue; import com.android.volley.toolbox.Volley; import com.google.android.material.snackbar.Snackbar; /** * A simple {@link Fragment} subclass. */ public class LoginFragment extends Fragment { private int maxUsernameLength; private int maxPasswordLength; private EditText usernameOrEmail; private EditText password; private RequestQueue mQueue; private MainActivity mainActivity; public LoginFragment() { // Required empty public constructor } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mQueue = Volley.newRequestQueue(mainActivity); } @Override public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_login, container, false); final String usernameOrEmailText; final String passwordText; Button loginBtn = view.findViewById(R.id.login_btn); usernameOrEmailText = view.findViewById(R.id.edit_text_username_or_email).toString(); passwordText = view.findViewById(R.id.edit_text_password).toString(); loginBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Snackbar snackbar = Snackbar.make(container, usernameOrEmailText + passwordText, Snackbar.LENGTH_LONG); snackbar.show(); } }); return view; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if(context instanceof MainActivity){ mainActivity = (MainActivity) context; } } } <file_sep>rootProject.name='TDDD80_Projekt' include ':app' <file_sep>package com.example.lab3; import android.content.Context; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class DetailFragment extends Fragment { private Context mainAct; private RequestQueue mQueue; private Group group = null; private TextView textView; public DetailFragment() { // Required empty public constructor } static DetailFragment newInstance(String groupName) { Bundle args = new Bundle(); DetailFragment fragment = new DetailFragment(); args.putString("groupName", groupName); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mQueue = Volley.newRequestQueue(mainAct); if (getArguments() != null){ group = new Group(getArguments().getString("groupName"), new ArrayList<Member>()); } else{ group = new Group(" Press group to show memebers", new ArrayList<Member>()); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_detail, container, false); textView = view.findViewById(R.id.text_view_members); if (getArguments() != null) { jsonParse(group.getGroupName()); } return view; } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); if(context instanceof MainActivity){ mainAct = (MainActivity) context; } else{ throw new RuntimeException(context.toString() + " error in DetailFragment!"); } } @Override public void onDetach() { super.onDetach(); mainAct = null; } private void jsonParse(String groupName) { final Gson gson = new Gson(); String url = "https://tddd80server.herokuapp.com/medlemmar/" + groupName; final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { JSONArray jsonArray = response.getJSONArray("medlemmar"); for (int i = 0; i <jsonArray.length() ; i++) { Member member = gson.fromJson(jsonArray.get(i).toString(), Member.class); group.addMember(member); } textView.setText(group.getGroupName()); for (Member m:group.getMembers()) { textView.append("\n\n"+ "Namn: "+m.getName()+"\nEpost: " + m.getEmail() + "\nSvarade: " + m.getAnswered()); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); mQueue.add(request); } public void updateGroup(String groupName) { textView.setText(""); group.setGroupName(groupName); group.resetMemebers(); jsonParse(groupName); } } <file_sep>package com.example.tddd80_projekt; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentTransaction; import android.annotation.SuppressLint; import android.content.pm.ActivityInfo; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @SuppressLint("SourceLockedOrientationActivity") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); createLoginScreen(ft); } /** * Login screen which is the first fragment that user sees * @param ft FragmentTransaction */ private void createLoginScreen( FragmentTransaction ft){ //Request to server (username, password lenght) LoginFragment loginFragment = new LoginFragment(); ft.replace(R.id.container, loginFragment).addToBackStack(null).commit(); } } <file_sep>rootProject.name='Lab2igen' include ':app'
84f30cc022ddf5971cb89385429fd4d1142a0afd
[ "Java", "Gradle" ]
5
Java
berryPiee/AndroidLabbar
f6ceb16085b2de1b77989257680d3afe679daf43
1500c375f7cd30ab9701587784f1880207036ad8
refs/heads/master
<file_sep># -*- coding: UTF-8 -*- import unittest from picture_category import pic_exif class TestPicExif(unittest.TestCase): def setUp(self): self.picFile = 'F:\\DCIM\\100ANDRO\\DSC_0004.JPG' def tearDown(self): self.picFile = None def testGetExif(self): self.assertIsNotNone(pic_exif.get_exif(self.picFile), 'test success') if __name__=='__main__': # unittest.main() suite = unittest.TestSuite() suite.addTest(TestPicExif("testGetExif")) # 执行测试 runner = unittest.TextTestRunner() runner.run(suite)<file_sep>from PIL import Image from PIL.ExifTags import TAGS from PIL.ExifTags import GPSTAGS import time import os import re def get_exif(pic_file): # i = Image.open('F:\\DCIM\\100ANDRO\\DSC_0004.JPG') # i = Image.open('F:\\photos\\iphone 2016.5.22\\101APPLE\\IMG_3007.JPG') try: img = Image.open(pic_file) if hasattr(img, '_getexif'): info = img._getexif() if info is not None: return {TAGS.get(tag): value for tag, value in info.items()} else: return None else: return None except IOError: print('IOERROR:', pic_file) def get_pic_propery(pic_file, exif): pic_info = {} # GPS gps = exif['GPSInfo'] if 'GPSInfo' in exif.keys() else None if gps is not None: gps_dic = {GPSTAGS.get(gpstag): value for gpstag, value in gps.items()} lat = gps_dic['GPSLatitude'] latitude_d = (lat[0][0] * 1.0) / lat[0][1] + ((lat[1][0] * 1.0) / lat[1][1]) / 60.0 + ((lat[2][0] * 1.0) / lat[2][1]) / 3600.0 longi = gps_dic['GPSLongitude'] longitude_d = (longi[0][0] * 1.0) / longi[0][1] \ + ((longi[1][0] * 1.0) / longi[1][1]) / 60.0 \ + ((longi[2][0] * 1.0) / longi[2][1]) / 3600.0 pic_info['latitude'] = latitude_d pic_info['lonitude'] = longitude_d # make make = exif['Make'] if 'Make' in exif.keys() else 'unknown' pic_info['make'] = make # model model = exif['Model'] if 'Model' in exif.keys() else "unknown_model" # only keep effective characters as filename model = re.sub('[^a-zA-Z0-9]', '', model) pic_info['model'] = model # Picture Create Time create_time = exif['DateTimeOriginal'] if 'DateTimeOriginal' in exif.keys() else "1970:01:01 23:59:59" # if exif don't have time info, then use file modify time. if re.match('^[0-9]{4}:[0-9]{1,2}:[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$', create_time): create_time_t = time.strptime(create_time, '%Y:%m:%d %H:%M:%S') else: create_time_t = time.localtime(os.path.getmtime(picFile)) pic_info['createTime'] = create_time_t # LensModel lens_model = exif['LensModel'] if 'LensModel' in exif.keys() else 'unknown' pic_info['lensModel'] = lens_model # ExifImageWidth width = exif['ExifImageWidth'] if 'ExifImageWidth' in exif.keys() else '0' pic_info['width'] = width # ExifImageHeight height = exif['ExifImageHeight'] if 'ExifImageHeight' in exif.keys() else '0' pic_info['height'] = height pic_info['raw'] = exif return pic_info picFile = 'F:\\photos\\iphone 2016.5.22\\101APPLE\\IMG_3007.JPG' exif = get_exif(picFile) get_pic_propery(picFile, exif) # gps = exif['GPSInfo'] # # for gpstag, value in gps.items(): # print(GPSTAGS.get(gpstag)) # print(value) <file_sep>from setuptools import setup, find_packages setup( name="PictureCategory", version="0.0.1", description="category photos by date", author="<NAME>", url="", license="LGPL", packages=find_packages(), install_requires=['Pillow'], # scripts=["picture_category/*.py"], entry_points={ 'console_scripts': [ 'pic_category = picture_category.main:main'] } ) <file_sep># -*- coding: UTF-8 -*- import os import shutil from picture_category import pic_exif import time import re import logging def scan_dir_get_pic(pic_dir): """ get all pictures, file size should be larger than 300KB, :param pic_dir: :return: category_pic, un_category_pic """ category_pic = [] # store photos which full fill requirements un_category_pic = [] # store small pictures which not photo generated by camera and smart phone for root, dirs, files in os.walk(pic_dir, True, None, False): for f in files: if os.path.isfile(os.path.join(root, f)): ext = os.path.splitext(f)[1].lower() file_size = os.path.getsize(os.path.join(root, f)) if ext in ('.jpg', '.jpeg', '.bmp') and file_size > 307200: category_pic.append(os.path.join(root, f)) # print(os.path.join(root,f)) else: un_category_pic.append(os.path.join(root, f)) logging.info('total picture counts(原始图片总张数): %d' % (len(category_pic) + len(un_category_pic))) logging.info(' to be categorized picture counts(待分类照片总张数) : %d' % len(category_pic)) logging.info('un_categorized picture(no exif; not pic ext; file size too small) ' 'counts(不能分类照片总张数) : %d' % len(un_category_pic)) return category_pic, un_category_pic def cp_categorized_file(src_path, dest_dir): """ input a photo file path, and rename picture to a new name (create_time_model),then copy it to dest_dir :param src_path: :param dest_dir: :return: """ file_name_raw = os.path.basename(src_path) ext = os.path.splitext(file_name_raw)[1].lower() _datetime_re = re.compile('^[0-9]{4}:[0-9]{1,2}:[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}$') pic_info = pic_exif.get_exif(src_path) if pic_info is not None: # if exif don't have time info, then use file modify time. if 'DateTimeOriginal' in pic_info.keys(): create_time_str = pic_info['DateTimeOriginal'] else: create_time_str = "1970:01:01 23:59:59" if _datetime_re.match(create_time_str): create_time = time.strptime(create_time_str, '%Y:%m:%d %H:%M:%S') else: create_time = time.localtime(os.path.getmtime(src_path)) # create_time_file are used as part of final file name create_time_file = time.strftime('%Y_%m_%d_%H_%M_%S', create_time) model = pic_info['Model'] if 'Model' in pic_info.keys() else "unknown_model" # only keep effective characters as filename model = re.sub('[^a-zA-Z0-9]', '', model) file_name = create_time_file + '_' + model + ext # dest folder is monthly folder dest_folder = time.strftime('%Y_%m', create_time) # if dest folder don't exists, create dir if not os.path.exists(dest_dir + os.path.sep + dest_folder): os.makedirs(dest_dir + os.path.sep + dest_folder) dest_path = dest_dir + os.path.sep + dest_folder + os.path.sep + file_name if os.path.exists(src_path) and not os.path.exists(dest_path): logging.debug('cp %s %s' % (src_path, dest_path)) shutil.copy(src_path, dest_path) else: # photo don't have exif info, copy to un_categorized folder logging.info('%s dont have exif info(无照片信息)' % src_path) dest_folder = 'un_categorized' if not os.path.exists(dest_dir + os.path.sep + dest_folder): os.makedirs(dest_dir + os.path.sep + dest_folder) dest_path = dest_dir + os.path.sep + dest_folder + os.path.sep + file_name_raw if os.path.exists(src_path) and not os.path.exists(dest_path): logging.debug('cp %s %s' % (src_path, dest_path)) shutil.copy(src_path, dest_path) def cp_un_categorized_file(src_path, dest_dir): file_name_raw = os.path.basename(src_path) dest_folder = 'un_categorized' if not os.path.exists(dest_dir + os.path.sep + dest_folder): os.makedirs(dest_dir + os.path.sep + dest_folder) dest_path = dest_dir + os.path.sep + dest_folder + os.path.sep + file_name_raw if os.path.exists(src_path) and not os.path.exists(dest_path): logging.debug('cp %s %s' % (src_path, dest_path)) shutil.copy(src_path, dest_path) def category(input_dir, dest_dir): ''' category photos :param input_dir: :param dest_dir: :return: ''' category_pic, un_category_pic = scan_dir_get_pic(input_dir) for pic in category_pic: cp_categorized_file(pic, dest_dir) for pic in un_category_pic: cp_un_categorized_file(pic, dest_dir) <file_sep># -*- coding: UTF-8 -*- import unittest from picture_category import category class TestAll(unittest.TestCase): def setUp(self): self.inputDir = 'F:\\photos\\2016.1 vivo' self.destDir = 'D:\\test' def tearDown(self): self.inputDir = None self.destDir = None def testScanDir(self): categoryPicList, unCategoryPicList = category.scanDirGetPic(self.inputDir) self.assertEqual(len(categoryPicList),6,'category picture list ') self.assertEqual(len(unCategoryPicList), 5, 'uncategory picture list ') def testCategory(self): self.assertIsNone(category.category(self.inputDir, self.destDir), 'process done') if __name__=='__main__': # unittest.main() suite = unittest.TestSuite() suite.addTest(TestAll("testScanDir")) suite.addTest(TestAll("testCategory")) # 执行测试 runner = unittest.TextTestRunner() runner.run(suite)<file_sep># -*- coding: UTF-8 -*- from __future__ import absolute_import import logging import argparse from picture_category import category def main(): parser = argparse.ArgumentParser(description="Picture Category Program") parser.add_argument('input', type=str, help="input directory which raw pictures store") parser.add_argument('output', type=str, help="ouput directory store processed pictures") args = parser.parse_args() # dir = 'F:\\DCIM' # dir = 'F:' logging.basicConfig(level=logging.INFO , format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s' , datefmt='%Y %b %d %H:%M:%S' # ,filename='myapp.log' # ,filemode='w' ) input_dir = args.input dest_dir = args.output # dir = 'F:\\photos\\2016.1 vivo' # dir = 'F:\\王娜\\照片\\本科照片\\照片\\大学的照片\\照片\\联通实习留念\\王娜' # destDir = 'D:\\Photo_Category' category.category(input_dir, dest_dir) logging.info('process done') if __name__ == "__main__": main() <file_sep># 介绍 电脑中经常会备份有手机或相机等不同日期的照片,而且文件夹之间有很多重复的,时间久了会很杂乱无章。 此小程序可以将照片按照月份分类,去掉重复的。整理后的文件名是从照片EXIF中读取的创建日期与拍摄设备型号。 #安装 python setup.py install #使用方法 两个输入参数: 照片所在目录; 处理后存储目录 pic_category "F:\photos\2016.1 vivo" "D:\test" <file_sep>from picture_category import main main()
c5ea674190223578e90cdd0b680e1737dee7f843
[ "Markdown", "Python" ]
8
Python
xidongsheng/photo_category
8a70dabaeab3f005116bd5dc0542aaccd16a4183
b86a2a5d990a80a800ca4c109d1f49d714c72bd4
refs/heads/master
<repo_name>BoshiLee/Core_Data<file_sep>/Udemy_Course/CoreData_Demo_L8_Core_Data_Stack/Grocery List/Data_Model/Grocery+CoreDataClass.swift // // Grocery+CoreDataClass.swift // Grocery List // // Created by <NAME> on 2017/2/21. // Copyright © 2017年 devhubs. All rights reserved. // import Foundation import CoreData public class Grocery: NSManagedObject { } <file_sep>/Udemy_Course/CoreData_Demo_L6_Creating ManagedObject Subclass_1/Grocery List/GroceryTableViewController.swift // // GroceryTableViewController.swift // Grocery List // // Created by <NAME> on 8/30/16. // Copyright © 2016 devhubs. All rights reserved. // import UIKit import CoreData class GroceryTableViewController: UITableViewController { // 存放資料的型態必須要是 [NSManagedObject] var groceries = [Grocery]() var managerObjectContext: NSManagedObjectContext? override func viewDidLoad() { super.viewDidLoad() guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return } managerObjectContext = appDelegate.persistentContainer.viewContext loadData() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func loadData() { // 實例化請求該 entity //let request: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: "Grocery") // 透過 subclass 直接實例化請求 let request: NSFetchRequest<Grocery> = Grocery.fetchRequest() do { // fetch 請求存入 result let results = try managerObjectContext?.fetch(request) // 將 result 存入 NSManagedobject 陣列裡 groceries = results! tableView.reloadData() } catch { fatalError("Error in retriving Grocery item") } } @IBAction func addAction(_ sender: UIBarButtonItem) { let alertController = UIAlertController(title: "Grocery Item", message: "What's to buy now?", preferredStyle: UIAlertControllerStyle.alert) alertController.addTextField { (textField: UITextField) in } let addAction = UIAlertAction(title: "ADD", style: UIAlertActionStyle.default) { [weak self] (action: UIAlertAction) in // let textField = alertController.textFields?.first // //self?.groceries.append(textField!.text!) // // let enetity = NSEntityDescription.entity(forEntityName: "Grocery", in: (self?.managerObjectContext)!)! // // let grocery = NSManagedObject(entity: enetity, insertInto: self?.managerObjectContext) // grocery.setValue(textField!.text, forKey: "item") guard let itemString = alertController.textFields?.first?.text, itemString != "" else { return } let grocery = Grocery(context: (self?.managerObjectContext)!) grocery.item = itemString do{ try self?.managerObjectContext?.save() } catch { fatalError("Error to save data") } self?.loadData() } let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default, handler: nil) alertController.addAction(addAction) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return self.groceries.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "groceryCell", for: indexPath) // 將 managedobject 放入每一個 cell 裡 let grocery = self.groceries[indexPath.row] cell.textLabel?.text = grocery.item return cell } }
bf7cd2f7e660738b578520ad390a8691d51fa959
[ "Swift" ]
2
Swift
BoshiLee/Core_Data
e2aafff913fb4fd14c19f2ddae6a2b4bc0ccd1e2
6fea9bd7d5370f01cd75386ef147370a80a02969
refs/heads/master
<file_sep><?php declare(strict_types=1); namespace Orba\RandomCat\Api\Data; interface RandomCatImageInterface { const API_URL = 'http://randomcatapi.orbalab.com/'; const REQUEST_METHOD = 'api_key'; public function getRandomCatImage(): string; } <file_sep><?php declare(strict_types=1); namespace Orba\RandomCat\Logger; use Magento\Framework\Logger\Handler\Base; class Handler extends Base { /** * Logging level * * @var int */ protected $loggerType = Logger::ERROR; /** * File name * * @var string */ protected $fileName = '/var/log/orba.txt'; } <file_sep><?php namespace Orba\RandomCat\Logger; class Logger extends \Monolog\Logger { } <file_sep>Orba Recruitment Magento 2 Backend Task ======================================= Overview -------- The purpose of this repository is to check skills of candidates applying to Orba for a position of Magento 2 Backend Developer. If you are here, you probably want to work with us :-). In the repository you will find an almost empty Magento 2 module called Orba_RandomCat. Your task will be to fill in this module with code to achieve the following feature: Change all product photos in catalog listing (and only there) to random cat photos using **Random Cat API**. ### Random Cat API It's a simple JSON API with only one endpoint: http://randomcatapi.orbalab.com/ It is protected by API key. To be authorized you must pass `api_key` GET parameter to the endpoint. The key that you may use is `<KEY>`. As a response for request to this API you will get simple JSON object with just one attribute called "url", eg. `{"url": "http://supercats.com/randomkitty123.jpg"}`. The API is heavily loaded, so from time to time (approximately 25% of all requests) it will not respond with HTTP status 200. Collection of cats photos used by the API is a little bit outdated, so from time to time (approximately 30% of successfull requests) it will return URL pointing to a 404 page. ### Mockup ![Mockup](mockup.png "Mockup") Recruitment task description ---------------------------- 1. Clone this repository to your local Magento 2.4.x installation. 2. Build Orba_RandomCat module. 3. When you're done, create a Pull Request with your changes. Assumptions and watchouts ------------------------- 1. Frontend should always show correct image. In case of any problems with API, internal `view/frontend/web/images/404.jpg` photo must be shown. 2. Don't worry about cache. It's OK that images are random only on the first page load. 3. Log all failed API responses and invalid images to a text log file. 4. Treat API credentials as non-public. 5. Write unit tests to get more points. 6. Make your code SOLID to get even more points.<file_sep><?php declare(strict_types=1); namespace Orba\RandomCat\Plugin; use Magento\Catalog\Block\Product\Image; use Magento\Catalog\Block\Product\ImageFactory; use Magento\Framework\App\Request\Http; use Magento\Framework\App\State; use Orba\RandomCat\Api\Data\RandomCatImageInterface; class RandomImage { /** * @var RandomCatImageInterface */ private $randomCatImage; /** * @var Http */ private $request; /** * @param RandomCatImageInterface $randomCatImage * @param Http $request */ public function __construct( RandomCatImageInterface $randomCatImage, Http $request ) { $this->randomCatImage = $randomCatImage; $this->request = $request; } /** * @param ImageFactory $imageFactory * @param Image $image * @return Image */ public function afterCreate( ImageFactory $imageFactory, Image $image ): Image { if ($this->request->getFullActionName() == 'catalog_category_view') { $image->setData('image_url', $this->randomCatImage->getRandomCatImage()); } return $image; } } <file_sep><?php declare(strict_types=1); namespace Orba\RandomCat\Model; use Magento\Framework\HTTP\Client\Curl; use Magento\Framework\Serialize\SerializerInterface; use Magento\Framework\View\Asset\Repository; use Orba\RandomCat\Api\Data\RandomCatImageInterface; use Orba\RandomCat\Logger\Logger; class RandomCatImage implements RandomCatImageInterface { /** * @var Curl */ private $curlClient; /** * @var SerializerInterface */ private $serializer; /** * @var Repository */ private $assertRepe; /** * @var Logger */ private $logger; /** * @param Curl $curl * @param SerializerInterface $serializer * @param Repository $assetRepo * @param Logger $logger */ public function __construct( Curl $curl, SerializerInterface $serializer, Repository $assetRepo, Logger $logger ) { $this->curlClient = $curl; $this->serializer = $serializer; $this->assertRepe = $assetRepo; $this->logger = $logger; } /** * Get random image * * @return string */ public function getRandomCatImage(): string { return $this->getImageFromApi(); } /** * Getting a valid path to a random picture or picture * that must be set if the picture from API is not valid or is missing * * @return string */ public function getImageFromApi(): string { $this->curlClient->get($this->getApiUrl()); return $this->getValidImage(); } /** * Returns a request to get a random image from the API * * @return string */ private function getApiUrl(): string { return self::API_URL . '?' . self::REQUEST_METHOD . '=' . '5up3rc0nf1d3n714llp455w0rdf0rc47s'; } /** * Checking the existence of a file on the server. * If there is no file for the received url, return the file 404. * * @return string */ public function getValidImage(): string { if ($this->curlClient->getStatus() !== 200) { $this->logger->error('Image not found'); return $this->assertRepe->getUrl("Orba_RandomCat::images/404.jpg"); } else { $imageUrl = $this->serializer->unserialize($this->curlClient->getBody())['url']; $this->curlClient->get($imageUrl); if ($this->curlClient->getStatus() === 200) { return (string) $imageUrl; } else { $this->logger->error('Image is non valid'); return $this->assertRepe->getUrl("Orba_RandomCat::images/404.jpg"); } } } }
49bb4da6ffc2aef80b5596a0cf48b2c728f41adb
[ "Markdown", "PHP" ]
6
PHP
andrey-vladimirovich/test_work
d9733834ab022fe7b8ec73ba4f2132401920f9b0
e7f07124b6b9de2da759e9f7ee13d03b9a2a7f77
refs/heads/master
<file_sep>sap.ui.define([ "sap/ui/core/Control" ], function(Control){ Control.extend("oft.fiori.nov.customControls.Heading",{ metadata:{ properties:{ "magic":"", "mario":"", "border":"" }, functions:{ }, events:{ } }, init: function(){ this.setBorder("1px solid black"); }, renderer:function(oRm,oControl){ //oRm.write("<h1>Spiderman is here </h1>"); //oRm.write("<h1 style='color:" + oControl.getMario()+"'>" + oControl.getMagic() + "</h1>"); //we will breakdown the code in renderer api oRm.write("<h1"); oRm.addStyle("color",oControl.getMario()); oRm.addStyle("border",oControl.getBorder()); oRm.writeStyles(); oRm.write(">" + oControl.getMagic() + "</h1>"); } }); });
7f17efa1187abf9a8a142f3a8b6f935d8cbd6de6
[ "JavaScript" ]
1
JavaScript
msreddyui5/CustomControl
5b0fc883411222fd92026bacd5ebf6b649461e8b
3a372f498ed30bac33b5ecc9e0643ae3c78adf9a
refs/heads/master
<repo_name>aatxe/chipster<file_sep>/src/screen.c #include <SDL/SDL.h> #include <stdlib.h> #include "screen.h" SDL_Surface* screen; screen_type m_type; key_state keys[0x11]; uint32_t last_updated; const uint16_t scale = 0x4; // Display Scale const uint32_t tick_length = 1000 / 60; // milliseconds per tick int init() { return (SDL_Init(SDL_INIT_VIDEO) < 0) ? 0 : 1; } void setup(screen_type type) { SDL_Color Colors[2] = {{0, 0, 0, 255}, {255, 255, 255, 255}}; // 0, 251, 52 for green. screen = SDL_SetVideoMode(64 * scale * type, 32 * scale * type, 8, SDL_SWSURFACE); SDL_SetColors(screen, Colors, 0, 2); m_type = type; } void update_keys() { SDL_Event e; while (SDL_PollEvent(&e)) { key_state key_value = KEY_UP; switch (e.type) { case SDL_QUIT: exit(0); break; case SDL_KEYDOWN: key_value = KEY_DOWN; case SDL_KEYUP: switch (e.key.keysym.sym) { case SDLK_1: keys[0x1] = key_value; break; case SDLK_2: keys[0x2] = key_value; break; case SDLK_3: keys[0x3] = key_value; break; case SDLK_4: keys[0xC] = key_value; break; case SDLK_q: keys[0x4] = key_value; break; case SDLK_w: keys[0x5] = key_value; break; case SDLK_e: keys[0x6] = key_value; break; case SDLK_r: keys[0xD] = key_value; break; case SDLK_a: keys[0x7] = key_value; break; case SDLK_s: keys[0x8] = key_value; break; case SDLK_d: keys[0x9] = key_value; break; case SDLK_f: keys[0xE] = key_value; break; case SDLK_z: keys[0xA] = key_value; break; case SDLK_x: keys[0x0] = key_value; break; case SDLK_c: keys[0xB] = key_value; break; case SDLK_v: keys[0xF] = key_value; break; default: break; } } } } key_state get_key(uint8_t k) { check(k < 0x10, "Invalid key: %x\n", k); return keys[k]; error: return KEY_UP; } void update_screen(uint8_t *fb) { uint16_t y, x; SDL_Rect b; b.x = 0, b.y = 0, b.w = scale, b.h = scale; for (y = 0; y < 32 * m_type; ++y) { b.y = y * scale; for (x = 0; x < 64 * m_type; ++x) { b.x = x * scale; SDL_FillRect(screen, &b, fb[y * (64 * m_type) + x]); } } SDL_Flip(screen); } void update(uint8_t *fb) { update_keys(); update_screen(fb); check(SDL_GetError(), "Something went wrong: %s", SDL_GetError()); error: return; } void sync() { uint32_t diff = SDL_GetTicks() - last_updated; if (diff < tick_length) SDL_Delay(tick_length - diff); last_updated = SDL_GetTicks(); } <file_sep>/src/chipster.c #include <SDL/SDL.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include "interpreter.h" #include "screen.h" void chipster_st() { forever { if (is_awaiting_keystroke()) { update_keys(); uint8_t i; for (i = 0; i < 0x10; i++) if (get_key(i)) send_key(i); } else { if (!get_dt()) interpret(); update_timers(); update(framebuf); sync(); } } } int interpreter_thread() { forever { if (is_awaiting_keystroke()) { update_keys(); uint8_t i; for (i = 0; i < 0x10; i++) if (get_key(i)) send_key(i); } else if (!get_dt()) { interpret(); } } return 0; } int main_thread() { forever { update_timers(); update(framebuf); sync(); } return 0; } void chipster_mt() { SDL_Thread *main, *interpreter; main = SDL_CreateThread(main_thread, NULL); check(main, "Failed to create main thread: %s\n", SDL_GetError()); interpreter = SDL_CreateThread(interpreter_thread, NULL); check(interpreter, "Failed to create interpreter thread: %s\n", SDL_GetError()); SDL_WaitThread(main, NULL); SDL_WaitThread(interpreter, NULL); error: exit(1); } int main(int argc, char *argv[]) { int rom_index = 1, mt = 0; if (!strcmp(argv[1], "--test")) return 0; // just a simple test to see if installed. if (!strcmp(argv[1], "-mt")) { debug("chipster is running in multithreaded mode."); rom_index++; mt = 1; } check_user(argc >= rom_index + 1, "%s: you must supply a ROM argument!\n", argv[0]); check_user(access(argv[rom_index], R_OK) != -1, "%s: could not find ROM: %s\n", argv[0], argv[rom_index]); if (!init() || !load(argv[rom_index])) goto error; if (mt) chipster_mt(); else chipster_st(); return 0; error: return 1; }<file_sep>/README.md # chipster # chipster is an urban, indie emulator for the [CHIP-8](https://en.wikipedia.org/wiki/CHIP-8) system. It wears old clothes from the thrift shop that is [SDL](http://www.libsdl.org/). chipster was designed by hipsters, for hipsters. Take on the retro gaming and get crackin' as an indie game developer for the retro CHIP-8 interpreter! You'll be the envy of all your hipster friends! ### What? ### chipster is a fast emulator for the [CHIP-8](https://en.wikipedia.org/wiki/CHIP-8) system using [SDL](http://www.libsdl.org/). It was made for the purpose of learning more about emulation. Quite frankly, there's a million of them and this one is nothing special. Try it out, take it for a spin, or just move along. I won't blame you. ### Screenshot ### ![chipster - VBRIX](https://dl.dropboxusercontent.com/u/8097711/chipster.png) ## Acknowledgements ## * [Cowgod's CHIP-8 Reference](http://devernay.free.fr/hacks/chip8/C8TECH10.HTM) for its immense usefulness. * [<NAME>](https://github.com/kvanberendonck) for his help and general _berendonckulousness_. * [<NAME>](https://github.com/retep998) for his help and support. * Others from #vana on [FyreChat](http://www.fyrechat.net/) for their continued support and tidbits of help. ## License ## chipster is completely open source and licensed under the MIT License. The full license text can be found in LICENSE.md for your convenience.<file_sep>/src/interpreter.h #ifndef __interpreter_h__ #define __interpreter_h__ #include <stdint.h> #include "minuet/minuet.h" // Compatability for non-clang compilers #ifndef __has_feature #define __has_feature(x) 0 #endif // Base Address for Program Space #define BASE_ADDR 0x200 extern uint8_t *framebuf; // Frame Buffer typedef struct { uint8_t interpreter[BASE_ADDR]; // Interpreter Space uint8_t rom[0xFFF - BASE_ADDR]; // Program Space } Memory; typedef uint8_t await_key_register; int load(char *path); void interpret(); int get_dt(); void update_timers(); int is_awaiting_keystroke(); void send_key(uint8_t key); #endif <file_sep>/src/screen.h #ifndef __screen_h__ #define __screen_h__ #include <stdint.h> #include "minuet/minuet.h" typedef enum { SCREEN_LOW = 1, SCREEN_HIGH } screen_type; typedef enum { KEY_UP, KEY_DOWN } key_state; int init(); void setup(screen_type type); void update_keys(); void update(uint8_t *fb); key_state get_key(uint8_t k); void sync(); #endif <file_sep>/src/interpreter.c #include <stdlib.h> #include <stdio.h> #include <time.h> #include "interpreter.h" #include "screen.h" uint16_t *pc; // Program Counter Memory mem; // System memory uint8_t si; // Stack Index uint16_t *stack[0x10]; // Stack uint8_t *I; // Memory-Access Register uint8_t V[0x10]; // Registers uint8_t dt, st; // Timers (Delay and Sound) uint8_t *framebuf; // Frame Buffer uint16_t bufsize; // size of the framebuffer screen_type m_type; // Screen Type await_key_register await_reg; // Awaiting Key Register, 0x10 if none. #if __has_feature(c_static_assert) _Static_assert(sizeof(mem) == 0xFFF) #endif // System Font Sprites const uint8_t font[0x50] = { 0xF0, 0x90, 0x90, 0x90, 0xF0, 0x20, 0x60, 0x20, 0x20, 0x70, 0xF0, 0x10, 0xF0, 0x80, 0xF0, 0xF0, 0x10, 0xF0, 0x10, 0xF0, 0x90, 0x90, 0xF0, 0x10, 0x10, 0xF0, 0x80, 0xF0, 0x10, 0xF0, 0xF0, 0x80, 0xF0, 0x90, 0xF0, 0xF0, 0x10, 0x20, 0x40, 0x40, 0xF0, 0x90, 0xF0, 0x90, 0xF0, 0xF0, 0x90, 0xF0, 0x10, 0xF0, 0xF0, 0x90, 0xF0, 0x90, 0x90, 0xE0, 0x90, 0xE0, 0x90, 0xE0, 0xF0, 0x80, 0x80, 0x80, 0xF0, 0xE0, 0x90, 0x90, 0x90, 0xE0, 0xF0, 0x80, 0xF0, 0x80, 0xF0, 0xF0, 0x80, 0xF0, 0x80, 0x80 }; int load(char *path) { FILE* rom; uint8_t * p; // Loads fonts into interpreter space. uint8_t* d = mem.interpreter; for (; d < mem.interpreter + 0x50; d++) *d = font[d - mem.interpreter]; // Loads specified ROM into program space. rom = fopen(path, "rb"); check(rom != NULL, "Failed to load ROM: %s\n", path); p = mem.rom; while(fread(p++, sizeof(uint8_t), 1, rom)); fclose(rom); // Allocates frame buffer for rendering. framebuf = (uint8_t*) calloc(1, sizeof(uint8_t) * 64 * 32); check_mem(framebuf); bufsize = sizeof(uint8_t) * 64 * 32; // Other initialization stuffs. m_type = SCREEN_LOW; setup(m_type); await_reg = 0x10; pc = (uint16_t*) mem.rom; srand(time(NULL)); return 1; error: fclose(rom); free(framebuf); return 0; } void regen_frame_buffer(screen_type type) { free(framebuf); framebuf = malloc(sizeof(uint8_t) * 64 * 32 * type * type); check_mem(framebuf); bufsize = sizeof(uint8_t) * 64 * 32 * type * type; error: log_err("Failed to regenerate frame buffer."); exit(1); } void interpret() { // Data stuffs for interpretation. uint16_t instr; uint16_t nnn; uint8_t kk; uint8_t n1, n2, n3, n4; // States used within certain instruction interpretations. uint8_t x, y, nx, ny; uint8_t* i; uint16_t k; instr = *pc >> 8 | *pc << 8; pc++; // increment pc here because of jumps and stuff // performs a simple security check to make sure program instructions are in-bounds check(pc >= (uint16_t*) mem.rom && pc <= (uint16_t*) ((uint8_t*) &mem + 4096), "Instruction out of program bounds: %x (%x)", instr, (int) pc); // nnn is the last 12-bits of the instruction nnn = instr & 0xFFF; // kk is the last 8-bits of the instruction kk = instr & 0xFF; // nX are individual nibbles (4-bit segments) of the instruction n1 = instr >> 12; n2 = (instr >> 8) & 0xF; n3 = (instr >> 4) & 0xF; n4 = instr & 0xF; i = I; debug("%X%X%X%X", n1, n2, n3, n4); switch (n1) { case 0x0: switch (n2) { case 0x0: switch (n3) { case 0xE: switch (n4) { case 0x0: // CLS for (k = 0; k < bufsize; k++) framebuf[k] = 0; break; case 0xE: // RET pc = stack[--si]; break; default: debug("Unknown instruction: %X\n", instr); } break; case 0xF: switch (n4) { case 0xD: // EXIT exit(0); case 0xE: // LOW m_type = SCREEN_LOW; regen_frame_buffer(SCREEN_LOW); setup(SCREEN_LOW); break; case 0xF: // HIGH m_type = SCREEN_HIGH; regen_frame_buffer(SCREEN_HIGH); setup(SCREEN_HIGH); break; default: debug("Unknown instruction: %X\n", instr); } break; default: debug("Unknown instruction: %X\n", instr); } break; default: // SYS addr - purposefully ignored. break; } break; case 0x1: // JP addr pc = (uint16_t*) ((uint8_t*) &mem + nnn); break; case 0x2: // CALL addr stack[si++] = pc; pc = (uint16_t*) ((uint8_t*) &mem + nnn); break; case 0x3: // SE Vx, byte if (V[n2] == kk) pc++; break; case 0x4: // SNE Vx, byte if (V[n2] != kk) pc++; break; case 0x5: // SE Vx, Vy if (V[n2] == V[n3]) pc++; break; case 0x6: // LD Vx, byte V[n2] = kk; break; case 0x7: // ADD Vx, byte V[n2] += kk; break; case 0x8: switch (n4) { case 0x0: // LD Vx, Vy V[n2] = V[n3]; break; case 0x1: // OR Vx, Vy V[n2] |= V[n3]; break; case 0x2: // AND Vx, Vy V[n2] &= V[n3]; break; case 0x3: // XOR Vx, Vy V[n2] ^= V[n3]; break; case 0x4: // ADD Vx, Vy V[0xF] = (V[n2] + V[n3] > 0xFFF) ? 0x1 : 0x0; V[n2] = (V[n2] + V[n3]) & 0xFFF; break; case 0x5: // SUB Vx, Vy V[0xF] = (V[n2] > V[n3]) ? 0x1 : 0x0; V[n2] -= V[n3]; break; case 0x6: // SHR Vx {, Vy} V[0xF] = V[n2] & 0x1; V[n2] >>= 1; break; case 0x7: // SUBN Vx, Vy V[0xF] = (V[n3] > V[n2]) ? 0x1 : 0x0; V[n2] = V[n3] - V[n2]; break; case 0xE: // SHL Vx {, Vy} V[0xF] = V[n2] >> 7; V[n2] <<= 1; break; default: debug("Unknown instruction: %X\n", instr); } break; case 0x9: // SNE Vx, Vy if (V[n2] != V[n3]) pc++; break; case 0xA: // LD I, addr I = (uint8_t*) &mem + nnn; break; case 0xB: // JP V0, addr pc = (uint16_t*) ((uint8_t*) &mem + nnn + V[0]); break; case 0xC: // RND Vx, byte V[n2] = (rand() % 0x100) & kk; break; case 0xD: // DRW Vx, Vy, nibble for (y = V[n3], ny = 0; ny < n4; ++ny, y = (y + 1) % (32 * m_type)) { for (x = V[n2], nx = 8; nx; --nx, x = (x + 1) % (64 * m_type)) { framebuf[y * (64 * m_type) + x] ^= (I[ny] >> (nx - 1)) & 1; } } break; case 0xE: switch (kk) { case 0x9E: // SKP Vx if (get_key(V[n2])) pc++; break; case 0xA1: // SKNP Vx if (!get_key(V[n2])) pc++; break; default: debug("Unknown instruction: %X\n", instr); } break; case 0xF: switch (kk) { case 0x07: // LD Vx, DT V[n2] = dt; break; case 0x0A: // LD Vx, K await_reg = n2; break; case 0x15: // LD DT, Vx dt = V[n2]; break; case 0x18: // LD ST, Vx st = V[n2]; break; case 0x1E: // ADD I, Vx I += V[n2]; break; case 0x29: // LD F, Vx I = (uint8_t*) &mem + (V[n2] * 5); break; case 0x33: // LD B, Vx I[0] = V[n2] / 100; I[1] = (V[n2] % 100) / 10; I[2] = V[n2] % 10; break; case 0x55: // LD [I], Vx for (; i < I + n2; i++) *i = V[i - I]; break; case 0x65: // LD [Vx], I for (; i < I + n2; i++) V[i - I] = *i; break; default: debug("Unknown instruction: %X\n", instr); } break; default: debug("Unknown instruction: %X\n", instr); } error: return; } int get_dt() { return dt; } void update_timers() { if (dt > 0) dt--; if (st > 0) st--; } int is_awaiting_keystroke() { return (await_reg < 0x10) ? 1 : 0; } void send_key(uint8_t key) { check_debug(await_reg < 0x10, "Received key whilst not awaiting a keypress.\n"); V[await_reg] = key; await_reg = 0x10; error: return; } <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(chipster) # Find SDL find_package(SDL REQUIRED) set(CMAKE_C_FLAGS "-Wall -Werror -Wextra") set(CMAKE_C_FLAGS_DEBUG "-O0 -Wall -Werror -Wextra -ggdb") set(CMAKE_C_FLAGS_RELEASE "-O2 -Wall -Werror -Wextra -DNDEBUG") aux_source_directory(./src CHIPSTER_SOURCES) add_executable(chipster ${CHIPSTER_SOURCES}) target_link_libraries(chipster ${SDL_LIBRARY}) install(TARGETS chipster DESTINATION bin)
8855c8edb38ab31c201320b449a53d992225d191
[ "Markdown", "C", "CMake" ]
7
C
aatxe/chipster
4ba37307fb4d1d4bc8de2202bbc36a126da63b1c
0a340c0d1783cbcaf9d89642e540c401740bfe7b
refs/heads/master
<file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef MYPROJECT_mesh001_generated_h #error "mesh001.generated.h already included, missing '#pragma once' in mesh001.h" #endif #define MYPROJECT_mesh001_generated_h #define MyProjectA_Source_MyProject_mesh001_h_12_RPC_WRAPPERS #define MyProjectA_Source_MyProject_mesh001_h_12_RPC_WRAPPERS_NO_PURE_DECLS #define MyProjectA_Source_MyProject_mesh001_h_12_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAmesh001(); \ friend struct Z_Construct_UClass_Amesh001_Statics; \ public: \ DECLARE_CLASS(Amesh001, AActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(Amesh001) #define MyProjectA_Source_MyProject_mesh001_h_12_INCLASS \ private: \ static void StaticRegisterNativesAmesh001(); \ friend struct Z_Construct_UClass_Amesh001_Statics; \ public: \ DECLARE_CLASS(Amesh001, AActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(Amesh001) #define MyProjectA_Source_MyProject_mesh001_h_12_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API Amesh001(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(Amesh001) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, Amesh001); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(Amesh001); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API Amesh001(Amesh001&&); \ NO_API Amesh001(const Amesh001&); \ public: #define MyProjectA_Source_MyProject_mesh001_h_12_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API Amesh001(Amesh001&&); \ NO_API Amesh001(const Amesh001&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, Amesh001); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(Amesh001); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(Amesh001) #define MyProjectA_Source_MyProject_mesh001_h_12_PRIVATE_PROPERTY_OFFSET #define MyProjectA_Source_MyProject_mesh001_h_9_PROLOG #define MyProjectA_Source_MyProject_mesh001_h_12_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_mesh001_h_12_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_mesh001_h_12_RPC_WRAPPERS \ MyProjectA_Source_MyProject_mesh001_h_12_INCLASS \ MyProjectA_Source_MyProject_mesh001_h_12_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MyProjectA_Source_MyProject_mesh001_h_12_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_mesh001_h_12_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_mesh001_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_mesh001_h_12_INCLASS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_mesh001_h_12_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MyProjectA_Source_MyProject_mesh001_h PRAGMA_ENABLE_DEPRECATION_WARNINGS <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef MYPROJECT_myActorMesh_generated_h #error "myActorMesh.generated.h already included, missing '#pragma once' in myActorMesh.h" #endif #define MYPROJECT_myActorMesh_generated_h #define MyProjectA_Source_MyProject_myActorMesh_h_15_RPC_WRAPPERS \ \ DECLARE_FUNCTION(execOnRep_IsActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_IsActive(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execsetActive) \ { \ P_GET_UBOOL(Z_Param_inState); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->setActive(Z_Param_inState); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execisActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->isActive(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_myActorMesh_h_15_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execOnRep_IsActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_IsActive(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execsetActive) \ { \ P_GET_UBOOL(Z_Param_inState); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->setActive(Z_Param_inState); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execisActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->isActive(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_myActorMesh_h_15_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAmyActorMesh(); \ friend struct Z_Construct_UClass_AmyActorMesh_Statics; \ public: \ DECLARE_CLASS(AmyActorMesh, AStaticMeshActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(AmyActorMesh) #define MyProjectA_Source_MyProject_myActorMesh_h_15_INCLASS \ private: \ static void StaticRegisterNativesAmyActorMesh(); \ friend struct Z_Construct_UClass_AmyActorMesh_Statics; \ public: \ DECLARE_CLASS(AmyActorMesh, AStaticMeshActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(AmyActorMesh) #define MyProjectA_Source_MyProject_myActorMesh_h_15_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API AmyActorMesh(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AmyActorMesh) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AmyActorMesh); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AmyActorMesh); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AmyActorMesh(AmyActorMesh&&); \ NO_API AmyActorMesh(const AmyActorMesh&); \ public: #define MyProjectA_Source_MyProject_myActorMesh_h_15_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AmyActorMesh(AmyActorMesh&&); \ NO_API AmyActorMesh(const AmyActorMesh&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AmyActorMesh); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AmyActorMesh); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(AmyActorMesh) #define MyProjectA_Source_MyProject_myActorMesh_h_15_PRIVATE_PROPERTY_OFFSET \ FORCEINLINE static uint32 __PPO__bIsActive() { return STRUCT_OFFSET(AmyActorMesh, bIsActive); } #define MyProjectA_Source_MyProject_myActorMesh_h_12_PROLOG #define MyProjectA_Source_MyProject_myActorMesh_h_15_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_myActorMesh_h_15_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_myActorMesh_h_15_RPC_WRAPPERS \ MyProjectA_Source_MyProject_myActorMesh_h_15_INCLASS \ MyProjectA_Source_MyProject_myActorMesh_h_15_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MyProjectA_Source_MyProject_myActorMesh_h_15_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_myActorMesh_h_15_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_myActorMesh_h_15_RPC_WRAPPERS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_myActorMesh_h_15_INCLASS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_myActorMesh_h_15_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MyProjectA_Source_MyProject_myActorMesh_h PRAGMA_ENABLE_DEPRECATION_WARNINGS <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "MyProject/tankPlayer.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodetankPlayer() {} // Cross Module References MYPROJECT_API UClass* Z_Construct_UClass_AtankPlayer_NoRegister(); MYPROJECT_API UClass* Z_Construct_UClass_AtankPlayer(); ENGINE_API UClass* Z_Construct_UClass_APawn(); UPackage* Z_Construct_UPackage__Script_MyProject(); ENGINE_API UClass* Z_Construct_UClass_UCameraComponent_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_UStaticMeshComponent_NoRegister(); // End Cross Module References void AtankPlayer::StaticRegisterNativesAtankPlayer() { } UClass* Z_Construct_UClass_AtankPlayer_NoRegister() { return AtankPlayer::StaticClass(); } struct Z_Construct_UClass_AtankPlayer_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_Camera_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_Camera; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_VisableComponent_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_VisableComponent; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_AtankPlayer_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_APawn, (UObject* (*)())Z_Construct_UPackage__Script_MyProject, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AtankPlayer_Statics::Class_MetaDataParams[] = { { "HideCategories", "Navigation" }, { "IncludePath", "tankPlayer.h" }, { "ModuleRelativePath", "tankPlayer.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AtankPlayer_Statics::NewProp_Camera_MetaData[] = { { "Category", "tankPlayer" }, { "EditInline", "true" }, { "ModuleRelativePath", "tankPlayer.h" }, { "ToolTip", "UPROPERTY(EditAnywhere)\n UCapsuleComponent* CapsuleComponent;" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AtankPlayer_Statics::NewProp_Camera = { UE4CodeGen_Private::EPropertyClass::Object, "Camera", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000080009, 1, nullptr, STRUCT_OFFSET(AtankPlayer, Camera), Z_Construct_UClass_UCameraComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AtankPlayer_Statics::NewProp_Camera_MetaData, ARRAY_COUNT(Z_Construct_UClass_AtankPlayer_Statics::NewProp_Camera_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AtankPlayer_Statics::NewProp_VisableComponent_MetaData[] = { { "Category", "tankPlayer" }, { "EditInline", "true" }, { "ModuleRelativePath", "tankPlayer.h" }, { "ToolTip", "component to be visible" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AtankPlayer_Statics::NewProp_VisableComponent = { UE4CodeGen_Private::EPropertyClass::Object, "VisableComponent", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000080009, 1, nullptr, STRUCT_OFFSET(AtankPlayer, VisableComponent), Z_Construct_UClass_UStaticMeshComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AtankPlayer_Statics::NewProp_VisableComponent_MetaData, ARRAY_COUNT(Z_Construct_UClass_AtankPlayer_Statics::NewProp_VisableComponent_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AtankPlayer_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AtankPlayer_Statics::NewProp_Camera, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AtankPlayer_Statics::NewProp_VisableComponent, }; const FCppClassTypeInfoStatic Z_Construct_UClass_AtankPlayer_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<AtankPlayer>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AtankPlayer_Statics::ClassParams = { &AtankPlayer::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x009000A0u, nullptr, 0, Z_Construct_UClass_AtankPlayer_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_AtankPlayer_Statics::PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_AtankPlayer_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_AtankPlayer_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_AtankPlayer() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AtankPlayer_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AtankPlayer, 2927726503); static FCompiledInDefer Z_CompiledInDefer_UClass_AtankPlayer(Z_Construct_UClass_AtankPlayer, &AtankPlayer::StaticClass, TEXT("/Script/MyProject"), TEXT("AtankPlayer"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AtankPlayer); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "MyProject/myActorMesh.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodemyActorMesh() {} // Cross Module References MYPROJECT_API UClass* Z_Construct_UClass_AmyActorMesh_NoRegister(); MYPROJECT_API UClass* Z_Construct_UClass_AmyActorMesh(); ENGINE_API UClass* Z_Construct_UClass_AStaticMeshActor(); UPackage* Z_Construct_UPackage__Script_MyProject(); MYPROJECT_API UFunction* Z_Construct_UFunction_AmyActorMesh_isActive(); MYPROJECT_API UFunction* Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive(); MYPROJECT_API UFunction* Z_Construct_UFunction_AmyActorMesh_setActive(); // End Cross Module References void AmyActorMesh::StaticRegisterNativesAmyActorMesh() { UClass* Class = AmyActorMesh::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "isActive", &AmyActorMesh::execisActive }, { "OnRep_IsActive", &AmyActorMesh::execOnRep_IsActive }, { "setActive", &AmyActorMesh::execsetActive }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_AmyActorMesh_isActive_Statics { struct myActorMesh_eventisActive_Parms { bool ReturnValue; }; static void NewProp_ReturnValue_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_AmyActorMesh_isActive_Statics::NewProp_ReturnValue_SetBit(void* Obj) { ((myActorMesh_eventisActive_Parms*)Obj)->ReturnValue = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_AmyActorMesh_isActive_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Bool, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(myActorMesh_eventisActive_Parms), &Z_Construct_UFunction_AmyActorMesh_isActive_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AmyActorMesh_isActive_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AmyActorMesh_isActive_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AmyActorMesh_isActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "myActorMesh.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AmyActorMesh_isActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AmyActorMesh, "isActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(myActorMesh_eventisActive_Parms), Z_Construct_UFunction_AmyActorMesh_isActive_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AmyActorMesh_isActive_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AmyActorMesh_isActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AmyActorMesh_isActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AmyActorMesh_isActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AmyActorMesh_isActive_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "myActorMesh.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AmyActorMesh, "OnRep_IsActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AmyActorMesh_setActive_Statics { struct myActorMesh_eventsetActive_Parms { bool inState; }; static void NewProp_inState_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_inState; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_AmyActorMesh_setActive_Statics::NewProp_inState_SetBit(void* Obj) { ((myActorMesh_eventsetActive_Parms*)Obj)->inState = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_AmyActorMesh_setActive_Statics::NewProp_inState = { UE4CodeGen_Private::EPropertyClass::Bool, "inState", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(myActorMesh_eventsetActive_Parms), &Z_Construct_UFunction_AmyActorMesh_setActive_Statics::NewProp_inState_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AmyActorMesh_setActive_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AmyActorMesh_setActive_Statics::NewProp_inState, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AmyActorMesh_setActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "myActorMesh.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AmyActorMesh_setActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AmyActorMesh, "setActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(myActorMesh_eventsetActive_Parms), Z_Construct_UFunction_AmyActorMesh_setActive_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AmyActorMesh_setActive_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AmyActorMesh_setActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AmyActorMesh_setActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AmyActorMesh_setActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AmyActorMesh_setActive_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_AmyActorMesh_NoRegister() { return AmyActorMesh::StaticClass(); } struct Z_Construct_UClass_AmyActorMesh_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bIsActive_MetaData[]; #endif static void NewProp_bIsActive_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsActive; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_AmyActorMesh_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AStaticMeshActor, (UObject* (*)())Z_Construct_UPackage__Script_MyProject, }; const FClassFunctionLinkInfo Z_Construct_UClass_AmyActorMesh_Statics::FuncInfo[] = { { &Z_Construct_UFunction_AmyActorMesh_isActive, "isActive" }, // 1428542466 { &Z_Construct_UFunction_AmyActorMesh_OnRep_IsActive, "OnRep_IsActive" }, // 3972750567 { &Z_Construct_UFunction_AmyActorMesh_setActive, "setActive" }, // 870011770 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AmyActorMesh_Statics::Class_MetaDataParams[] = { { "HideCategories", "Input" }, { "IncludePath", "myActorMesh.h" }, { "ModuleRelativePath", "myActorMesh.h" }, { "ShowCategories", "Input|MouseInput Input|TouchInput" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AmyActorMesh_Statics::NewProp_bIsActive_MetaData[] = { { "ModuleRelativePath", "myActorMesh.h" }, }; #endif void Z_Construct_UClass_AmyActorMesh_Statics::NewProp_bIsActive_SetBit(void* Obj) { ((AmyActorMesh*)Obj)->bIsActive = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_AmyActorMesh_Statics::NewProp_bIsActive = { UE4CodeGen_Private::EPropertyClass::Bool, "bIsActive", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000020, 1, "OnRep_IsActive", sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(AmyActorMesh), &Z_Construct_UClass_AmyActorMesh_Statics::NewProp_bIsActive_SetBit, METADATA_PARAMS(Z_Construct_UClass_AmyActorMesh_Statics::NewProp_bIsActive_MetaData, ARRAY_COUNT(Z_Construct_UClass_AmyActorMesh_Statics::NewProp_bIsActive_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AmyActorMesh_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AmyActorMesh_Statics::NewProp_bIsActive, }; const FCppClassTypeInfoStatic Z_Construct_UClass_AmyActorMesh_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<AmyActorMesh>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AmyActorMesh_Statics::ClassParams = { &AmyActorMesh::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x009000A0u, FuncInfo, ARRAY_COUNT(FuncInfo), Z_Construct_UClass_AmyActorMesh_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_AmyActorMesh_Statics::PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_AmyActorMesh_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_AmyActorMesh_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_AmyActorMesh() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AmyActorMesh_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AmyActorMesh, 238566882); static FCompiledInDefer Z_CompiledInDefer_UClass_AmyActorMesh(Z_Construct_UClass_AmyActorMesh, &AmyActorMesh::StaticClass, TEXT("/Script/MyProject"), TEXT("AmyActorMesh"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AmyActorMesh); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef MYPROJECT_tankPlayer_generated_h #error "tankPlayer.generated.h already included, missing '#pragma once' in tankPlayer.h" #endif #define MYPROJECT_tankPlayer_generated_h #define MyProjectA_Source_MyProject_tankPlayer_h_14_RPC_WRAPPERS #define MyProjectA_Source_MyProject_tankPlayer_h_14_RPC_WRAPPERS_NO_PURE_DECLS #define MyProjectA_Source_MyProject_tankPlayer_h_14_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAtankPlayer(); \ friend struct Z_Construct_UClass_AtankPlayer_Statics; \ public: \ DECLARE_CLASS(AtankPlayer, APawn, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(AtankPlayer) #define MyProjectA_Source_MyProject_tankPlayer_h_14_INCLASS \ private: \ static void StaticRegisterNativesAtankPlayer(); \ friend struct Z_Construct_UClass_AtankPlayer_Statics; \ public: \ DECLARE_CLASS(AtankPlayer, APawn, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(AtankPlayer) #define MyProjectA_Source_MyProject_tankPlayer_h_14_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API AtankPlayer(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AtankPlayer) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AtankPlayer); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AtankPlayer); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AtankPlayer(AtankPlayer&&); \ NO_API AtankPlayer(const AtankPlayer&); \ public: #define MyProjectA_Source_MyProject_tankPlayer_h_14_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AtankPlayer(AtankPlayer&&); \ NO_API AtankPlayer(const AtankPlayer&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AtankPlayer); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AtankPlayer); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(AtankPlayer) #define MyProjectA_Source_MyProject_tankPlayer_h_14_PRIVATE_PROPERTY_OFFSET #define MyProjectA_Source_MyProject_tankPlayer_h_11_PROLOG #define MyProjectA_Source_MyProject_tankPlayer_h_14_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_tankPlayer_h_14_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_tankPlayer_h_14_RPC_WRAPPERS \ MyProjectA_Source_MyProject_tankPlayer_h_14_INCLASS \ MyProjectA_Source_MyProject_tankPlayer_h_14_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MyProjectA_Source_MyProject_tankPlayer_h_14_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_tankPlayer_h_14_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_tankPlayer_h_14_RPC_WRAPPERS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_tankPlayer_h_14_INCLASS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_tankPlayer_h_14_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MyProjectA_Source_MyProject_tankPlayer_h PRAGMA_ENABLE_DEPRECATION_WARNINGS <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef MYPROJECT_MyProjectGameMode_generated_h #error "MyProjectGameMode.generated.h already included, missing '#pragma once' in MyProjectGameMode.h" #endif #define MYPROJECT_MyProjectGameMode_generated_h #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_RPC_WRAPPERS \ virtual void HasWinner_Implementation(); \ virtual void AllLoser_Implementation(); \ \ DECLARE_FUNCTION(execHasWinner) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->HasWinner_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAllLoser) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AllLoser_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetWinner) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->GetWinner(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execSetWinner) \ { \ P_GET_PROPERTY(UStrProperty,Z_Param_inName); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->SetWinner(Z_Param_inName); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(exectimeDecrease) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->timeDecrease(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ virtual void HasWinner_Implementation(); \ virtual void AllLoser_Implementation(); \ \ DECLARE_FUNCTION(execHasWinner) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->HasWinner_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAllLoser) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AllLoser_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetWinner) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->GetWinner(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execSetWinner) \ { \ P_GET_PROPERTY(UStrProperty,Z_Param_inName); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->SetWinner(Z_Param_inName); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(exectimeDecrease) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->timeDecrease(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_EVENT_PARMS #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_CALLBACK_WRAPPERS #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAMyProjectGameMode(); \ friend struct Z_Construct_UClass_AMyProjectGameMode_Statics; \ public: \ DECLARE_CLASS(AMyProjectGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), CASTCLASS_None, TEXT("/Script/MyProject"), MYPROJECT_API) \ DECLARE_SERIALIZER(AMyProjectGameMode) #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_INCLASS \ private: \ static void StaticRegisterNativesAMyProjectGameMode(); \ friend struct Z_Construct_UClass_AMyProjectGameMode_Statics; \ public: \ DECLARE_CLASS(AMyProjectGameMode, AGameModeBase, COMPILED_IN_FLAGS(0 | CLASS_Transient), CASTCLASS_None, TEXT("/Script/MyProject"), MYPROJECT_API) \ DECLARE_SERIALIZER(AMyProjectGameMode) #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ MYPROJECT_API AMyProjectGameMode(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AMyProjectGameMode) \ DECLARE_VTABLE_PTR_HELPER_CTOR(MYPROJECT_API, AMyProjectGameMode); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AMyProjectGameMode); \ private: \ /** Private move- and copy-constructors, should never be used */ \ MYPROJECT_API AMyProjectGameMode(AMyProjectGameMode&&); \ MYPROJECT_API AMyProjectGameMode(const AMyProjectGameMode&); \ public: #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ MYPROJECT_API AMyProjectGameMode(AMyProjectGameMode&&); \ MYPROJECT_API AMyProjectGameMode(const AMyProjectGameMode&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(MYPROJECT_API, AMyProjectGameMode); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AMyProjectGameMode); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(AMyProjectGameMode) #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_PRIVATE_PROPERTY_OFFSET #define MyProjectA_Source_MyProject_MyProjectGameMode_h_9_PROLOG \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_EVENT_PARMS #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_RPC_WRAPPERS \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_CALLBACK_WRAPPERS \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_INCLASS \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MyProjectA_Source_MyProject_MyProjectGameMode_h_12_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_CALLBACK_WRAPPERS \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_INCLASS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_MyProjectGameMode_h_12_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MyProjectA_Source_MyProject_MyProjectGameMode_h PRAGMA_ENABLE_DEPRECATION_WARNINGS <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef MYPROJECT_Pickup_generated_h #error "Pickup.generated.h already included, missing '#pragma once' in Pickup.h" #endif #define MYPROJECT_Pickup_generated_h #define MyProjectA_Source_MyProject_Pickup_h_13_RPC_WRAPPERS \ \ DECLARE_FUNCTION(execcheckIsPlayerHit) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->checkIsPlayerHit(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_pickupDisplayText) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_pickupDisplayText(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_HitCountA) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_HitCountA(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_HitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_HitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_IsActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_IsActive(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execaddHitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->addHitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execgetHitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->getHitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execsetActive) \ { \ P_GET_UBOOL(Z_Param_inState); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->setActive(Z_Param_inState); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execisActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->isActive(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_Pickup_h_13_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execcheckIsPlayerHit) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->checkIsPlayerHit(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_pickupDisplayText) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_pickupDisplayText(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_HitCountA) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_HitCountA(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_HitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_HitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_IsActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_IsActive(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execaddHitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->addHitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execgetHitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->getHitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execsetActive) \ { \ P_GET_UBOOL(Z_Param_inState); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->setActive(Z_Param_inState); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execisActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->isActive(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_Pickup_h_13_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAPickup(); \ friend struct Z_Construct_UClass_APickup_Statics; \ public: \ DECLARE_CLASS(APickup, AStaticMeshActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(APickup) #define MyProjectA_Source_MyProject_Pickup_h_13_INCLASS \ private: \ static void StaticRegisterNativesAPickup(); \ friend struct Z_Construct_UClass_APickup_Statics; \ public: \ DECLARE_CLASS(APickup, AStaticMeshActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(APickup) #define MyProjectA_Source_MyProject_Pickup_h_13_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API APickup(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(APickup) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, APickup); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(APickup); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API APickup(APickup&&); \ NO_API APickup(const APickup&); \ public: #define MyProjectA_Source_MyProject_Pickup_h_13_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API APickup(APickup&&); \ NO_API APickup(const APickup&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, APickup); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(APickup); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(APickup) #define MyProjectA_Source_MyProject_Pickup_h_13_PRIVATE_PROPERTY_OFFSET \ FORCEINLINE static uint32 __PPO__pickupName() { return STRUCT_OFFSET(APickup, pickupName); } \ FORCEINLINE static uint32 __PPO__pickupDisplayText() { return STRUCT_OFFSET(APickup, pickupDisplayText); } \ FORCEINLINE static uint32 __PPO__HitCount() { return STRUCT_OFFSET(APickup, HitCount); } \ FORCEINLINE static uint32 __PPO__HitCountA() { return STRUCT_OFFSET(APickup, HitCountA); } \ FORCEINLINE static uint32 __PPO__name() { return STRUCT_OFFSET(APickup, name); } \ FORCEINLINE static uint32 __PPO__bIsActive() { return STRUCT_OFFSET(APickup, bIsActive); } #define MyProjectA_Source_MyProject_Pickup_h_10_PROLOG #define MyProjectA_Source_MyProject_Pickup_h_13_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_Pickup_h_13_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_Pickup_h_13_RPC_WRAPPERS \ MyProjectA_Source_MyProject_Pickup_h_13_INCLASS \ MyProjectA_Source_MyProject_Pickup_h_13_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MyProjectA_Source_MyProject_Pickup_h_13_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_Pickup_h_13_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_Pickup_h_13_RPC_WRAPPERS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_Pickup_h_13_INCLASS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_Pickup_h_13_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MyProjectA_Source_MyProject_Pickup_h PRAGMA_ENABLE_DEPRECATION_WARNINGS <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "MyProject/BreakableWall.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeBreakableWall() {} // Cross Module References MYPROJECT_API UClass* Z_Construct_UClass_ABreakableWall_NoRegister(); MYPROJECT_API UClass* Z_Construct_UClass_ABreakableWall(); ENGINE_API UClass* Z_Construct_UClass_AStaticMeshActor(); UPackage* Z_Construct_UPackage__Script_MyProject(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_addHitCount(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_GetHP(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_GetName(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_GetText(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_isActive(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_onHit(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_onHitBP(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_IsActive(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_topHP(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_wHP(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_wText(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_setActive(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_UpdateWallRender(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_WallBreak(); MYPROJECT_API UFunction* Z_Construct_UFunction_ABreakableWall_WallBreakBP(); // End Cross Module References static FName NAME_ABreakableWall_onHitBP = FName(TEXT("onHitBP")); void ABreakableWall::onHitBP() { ProcessEvent(FindFunctionChecked(NAME_ABreakableWall_onHitBP),NULL); } static FName NAME_ABreakableWall_UpdateWallRender = FName(TEXT("UpdateWallRender")); void ABreakableWall::UpdateWallRender() { ProcessEvent(FindFunctionChecked(NAME_ABreakableWall_UpdateWallRender),NULL); } static FName NAME_ABreakableWall_UpdateWallRenderBP = FName(TEXT("UpdateWallRenderBP")); void ABreakableWall::UpdateWallRenderBP() { ProcessEvent(FindFunctionChecked(NAME_ABreakableWall_UpdateWallRenderBP),NULL); } static FName NAME_ABreakableWall_WallBreak = FName(TEXT("WallBreak")); void ABreakableWall::WallBreak() { ProcessEvent(FindFunctionChecked(NAME_ABreakableWall_WallBreak),NULL); } static FName NAME_ABreakableWall_WallBreakBP = FName(TEXT("WallBreakBP")); void ABreakableWall::WallBreakBP() { ProcessEvent(FindFunctionChecked(NAME_ABreakableWall_WallBreakBP),NULL); } void ABreakableWall::StaticRegisterNativesABreakableWall() { UClass* Class = ABreakableWall::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "addHitCount", &ABreakableWall::execaddHitCount }, { "GetHP", &ABreakableWall::execGetHP }, { "GetName", &ABreakableWall::execGetName }, { "GetText", &ABreakableWall::execGetText }, { "isActive", &ABreakableWall::execisActive }, { "onHit", &ABreakableWall::execonHit }, { "OnRep_IsActive", &ABreakableWall::execOnRep_IsActive }, { "OnRep_topHP", &ABreakableWall::execOnRep_topHP }, { "OnRep_wHP", &ABreakableWall::execOnRep_wHP }, { "OnRep_wText", &ABreakableWall::execOnRep_wText }, { "setActive", &ABreakableWall::execsetActive }, { "UpdateWallRender", &ABreakableWall::execUpdateWallRender }, { "WallBreak", &ABreakableWall::execWallBreak }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_ABreakableWall_addHitCount_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_addHitCount_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_addHitCount_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "addHitCount", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_addHitCount_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_addHitCount_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_addHitCount() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_addHitCount_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_GetHP_Statics { struct BreakableWall_eventGetHP_Parms { float ReturnValue; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_ABreakableWall_GetHP_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Float, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(BreakableWall_eventGetHP_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ABreakableWall_GetHP_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ABreakableWall_GetHP_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_GetHP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_GetHP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "GetHP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(BreakableWall_eventGetHP_Parms), Z_Construct_UFunction_ABreakableWall_GetHP_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_GetHP_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_GetHP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_GetHP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_GetHP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_GetHP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_GetName_Statics { struct BreakableWall_eventGetName_Parms { FString ReturnValue; }; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_ABreakableWall_GetName_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Str, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(BreakableWall_eventGetName_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ABreakableWall_GetName_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ABreakableWall_GetName_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_GetName_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, { "ToolTip", "mutator and assessors" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_GetName_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "GetName", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(BreakableWall_eventGetName_Parms), Z_Construct_UFunction_ABreakableWall_GetName_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_GetName_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_GetName_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_GetName_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_GetName() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_GetName_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_GetText_Statics { struct BreakableWall_eventGetText_Parms { FString ReturnValue; }; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_ABreakableWall_GetText_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Str, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(BreakableWall_eventGetText_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ABreakableWall_GetText_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ABreakableWall_GetText_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_GetText_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_GetText_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "GetText", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(BreakableWall_eventGetText_Parms), Z_Construct_UFunction_ABreakableWall_GetText_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_GetText_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_GetText_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_GetText_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_GetText() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_GetText_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_isActive_Statics { struct BreakableWall_eventisActive_Parms { bool ReturnValue; }; static void NewProp_ReturnValue_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_ABreakableWall_isActive_Statics::NewProp_ReturnValue_SetBit(void* Obj) { ((BreakableWall_eventisActive_Parms*)Obj)->ReturnValue = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_ABreakableWall_isActive_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Bool, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(BreakableWall_eventisActive_Parms), &Z_Construct_UFunction_ABreakableWall_isActive_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ABreakableWall_isActive_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ABreakableWall_isActive_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_isActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_isActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "isActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(BreakableWall_eventisActive_Parms), Z_Construct_UFunction_ABreakableWall_isActive_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_isActive_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_isActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_isActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_isActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_isActive_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_onHit_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_onHit_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_onHit_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "onHit", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_onHit_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_onHit_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_onHit() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_onHit_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_onHitBP_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_onHitBP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_onHitBP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "onHitBP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x08020800, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_onHitBP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_onHitBP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_onHitBP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_onHitBP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_OnRep_IsActive_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_OnRep_IsActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_OnRep_IsActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "OnRep_IsActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_OnRep_IsActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_OnRep_IsActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_IsActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_OnRep_IsActive_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_OnRep_topHP_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_OnRep_topHP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_OnRep_topHP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "OnRep_topHP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_OnRep_topHP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_OnRep_topHP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_topHP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_OnRep_topHP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_OnRep_wHP_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_OnRep_wHP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_OnRep_wHP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "OnRep_wHP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_OnRep_wHP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_OnRep_wHP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_wHP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_OnRep_wHP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_OnRep_wText_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_OnRep_wText_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_OnRep_wText_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "OnRep_wText", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_OnRep_wText_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_OnRep_wText_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_OnRep_wText() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_OnRep_wText_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_setActive_Statics { struct BreakableWall_eventsetActive_Parms { bool inState; }; static void NewProp_inState_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_inState; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_ABreakableWall_setActive_Statics::NewProp_inState_SetBit(void* Obj) { ((BreakableWall_eventsetActive_Parms*)Obj)->inState = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_ABreakableWall_setActive_Statics::NewProp_inState = { UE4CodeGen_Private::EPropertyClass::Bool, "inState", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(BreakableWall_eventsetActive_Parms), &Z_Construct_UFunction_ABreakableWall_setActive_Statics::NewProp_inState_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_ABreakableWall_setActive_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_ABreakableWall_setActive_Statics::NewProp_inState, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_setActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_setActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "setActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(BreakableWall_eventsetActive_Parms), Z_Construct_UFunction_ABreakableWall_setActive_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_setActive_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_setActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_setActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_setActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_setActive_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_UpdateWallRender_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_UpdateWallRender_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_UpdateWallRender_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "UpdateWallRender", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04024CC0, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_UpdateWallRender_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_UpdateWallRender_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_UpdateWallRender() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_UpdateWallRender_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "UpdateWallRenderBP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x08020800, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_WallBreak_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_WallBreak_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_WallBreak_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "WallBreak", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04024CC0, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_WallBreak_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_WallBreak_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_WallBreak() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_WallBreak_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_ABreakableWall_WallBreakBP_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_ABreakableWall_WallBreakBP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_ABreakableWall_WallBreakBP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_ABreakableWall, "WallBreakBP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x08020800, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_ABreakableWall_WallBreakBP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_ABreakableWall_WallBreakBP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_ABreakableWall_WallBreakBP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_ABreakableWall_WallBreakBP_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_ABreakableWall_NoRegister() { return ABreakableWall::StaticClass(); } struct Z_Construct_UClass_ABreakableWall_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bIsActive_MetaData[]; #endif static void NewProp_bIsActive_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsActive; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_wText_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_wText; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_wName_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_wName; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_topHP_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_topHP; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_wHP_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_wHP; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_ABreakableWall_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AStaticMeshActor, (UObject* (*)())Z_Construct_UPackage__Script_MyProject, }; const FClassFunctionLinkInfo Z_Construct_UClass_ABreakableWall_Statics::FuncInfo[] = { { &Z_Construct_UFunction_ABreakableWall_addHitCount, "addHitCount" }, // 2457664385 { &Z_Construct_UFunction_ABreakableWall_GetHP, "GetHP" }, // 118450162 { &Z_Construct_UFunction_ABreakableWall_GetName, "GetName" }, // 3442979011 { &Z_Construct_UFunction_ABreakableWall_GetText, "GetText" }, // 2613210442 { &Z_Construct_UFunction_ABreakableWall_isActive, "isActive" }, // 3124656815 { &Z_Construct_UFunction_ABreakableWall_onHit, "onHit" }, // 3006323160 { &Z_Construct_UFunction_ABreakableWall_onHitBP, "onHitBP" }, // 800662368 { &Z_Construct_UFunction_ABreakableWall_OnRep_IsActive, "OnRep_IsActive" }, // 1926351265 { &Z_Construct_UFunction_ABreakableWall_OnRep_topHP, "OnRep_topHP" }, // 2066182992 { &Z_Construct_UFunction_ABreakableWall_OnRep_wHP, "OnRep_wHP" }, // 2666262721 { &Z_Construct_UFunction_ABreakableWall_OnRep_wText, "OnRep_wText" }, // 2415350064 { &Z_Construct_UFunction_ABreakableWall_setActive, "setActive" }, // 2348119559 { &Z_Construct_UFunction_ABreakableWall_UpdateWallRender, "UpdateWallRender" }, // 1373700508 { &Z_Construct_UFunction_ABreakableWall_UpdateWallRenderBP, "UpdateWallRenderBP" }, // 3921674942 { &Z_Construct_UFunction_ABreakableWall_WallBreak, "WallBreak" }, // 326674323 { &Z_Construct_UFunction_ABreakableWall_WallBreakBP, "WallBreakBP" }, // 1906502638 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABreakableWall_Statics::Class_MetaDataParams[] = { { "HideCategories", "Input" }, { "IncludePath", "BreakableWall.h" }, { "ModuleRelativePath", "BreakableWall.h" }, { "ShowCategories", "Input|MouseInput Input|TouchInput" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABreakableWall_Statics::NewProp_bIsActive_MetaData[] = { { "ModuleRelativePath", "BreakableWall.h" }, }; #endif void Z_Construct_UClass_ABreakableWall_Statics::NewProp_bIsActive_SetBit(void* Obj) { ((ABreakableWall*)Obj)->bIsActive = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_ABreakableWall_Statics::NewProp_bIsActive = { UE4CodeGen_Private::EPropertyClass::Bool, "bIsActive", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000020, 1, "OnRep_IsActive", sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(ABreakableWall), &Z_Construct_UClass_ABreakableWall_Statics::NewProp_bIsActive_SetBit, METADATA_PARAMS(Z_Construct_UClass_ABreakableWall_Statics::NewProp_bIsActive_MetaData, ARRAY_COUNT(Z_Construct_UClass_ABreakableWall_Statics::NewProp_bIsActive_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABreakableWall_Statics::NewProp_wText_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_ABreakableWall_Statics::NewProp_wText = { UE4CodeGen_Private::EPropertyClass::Str, "wText", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000025, 1, "OnRep_wText", STRUCT_OFFSET(ABreakableWall, wText), METADATA_PARAMS(Z_Construct_UClass_ABreakableWall_Statics::NewProp_wText_MetaData, ARRAY_COUNT(Z_Construct_UClass_ABreakableWall_Statics::NewProp_wText_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABreakableWall_Statics::NewProp_wName_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_ABreakableWall_Statics::NewProp_wName = { UE4CodeGen_Private::EPropertyClass::Str, "wName", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000005, 1, nullptr, STRUCT_OFFSET(ABreakableWall, wName), METADATA_PARAMS(Z_Construct_UClass_ABreakableWall_Statics::NewProp_wName_MetaData, ARRAY_COUNT(Z_Construct_UClass_ABreakableWall_Statics::NewProp_wName_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABreakableWall_Statics::NewProp_topHP_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ABreakableWall_Statics::NewProp_topHP = { UE4CodeGen_Private::EPropertyClass::Float, "topHP", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000025, 1, "OnRep_topHP", STRUCT_OFFSET(ABreakableWall, topHP), METADATA_PARAMS(Z_Construct_UClass_ABreakableWall_Statics::NewProp_topHP_MetaData, ARRAY_COUNT(Z_Construct_UClass_ABreakableWall_Statics::NewProp_topHP_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_ABreakableWall_Statics::NewProp_wHP_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "BreakableWall.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_ABreakableWall_Statics::NewProp_wHP = { UE4CodeGen_Private::EPropertyClass::Float, "wHP", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000025, 1, "OnRep_wHP", STRUCT_OFFSET(ABreakableWall, wHP), METADATA_PARAMS(Z_Construct_UClass_ABreakableWall_Statics::NewProp_wHP_MetaData, ARRAY_COUNT(Z_Construct_UClass_ABreakableWall_Statics::NewProp_wHP_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_ABreakableWall_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABreakableWall_Statics::NewProp_bIsActive, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABreakableWall_Statics::NewProp_wText, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABreakableWall_Statics::NewProp_wName, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABreakableWall_Statics::NewProp_topHP, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_ABreakableWall_Statics::NewProp_wHP, }; const FCppClassTypeInfoStatic Z_Construct_UClass_ABreakableWall_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<ABreakableWall>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_ABreakableWall_Statics::ClassParams = { &ABreakableWall::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x009000A0u, FuncInfo, ARRAY_COUNT(FuncInfo), Z_Construct_UClass_ABreakableWall_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_ABreakableWall_Statics::PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_ABreakableWall_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_ABreakableWall_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_ABreakableWall() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_ABreakableWall_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(ABreakableWall, 47414391); static FCompiledInDefer Z_CompiledInDefer_UClass_ABreakableWall(Z_Construct_UClass_ABreakableWall, &ABreakableWall::StaticClass, TEXT("/Script/MyProject"), TEXT("ABreakableWall"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(ABreakableWall); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Engine/StaticMeshActor.h" #include "BreakableWall.generated.h" UCLASS() class MYPROJECT_API ABreakableWall : public AStaticMeshActor { GENERATED_BODY() public: // Sets default values for this actor's properties ABreakableWall(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; //networking stuff void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>&OutLifetimeProps) const override; UFUNCTION(BlueprintPure) bool isActive(); UFUNCTION(BlueprintCallable) void setActive(bool inState); //mutator and assessors UFUNCTION(BlueprintPure) FString GetName() { return wName; }; UFUNCTION(BlueprintPure) FString GetText() { return wText; }; UFUNCTION(BlueprintPure) float GetHP() { return wHP; } UFUNCTION(BlueprintCallable) void onHit(); UFUNCTION(BlueprintImplementableEvent) void onHitBP(); UFUNCTION(BlueprintCallable, NetMulticast, reliable) void UpdateWallRender(); UFUNCTION(BlueprintImplementableEvent) void UpdateWallRenderBP(); UFUNCTION(BlueprintCallable, NetMulticast, reliable) void WallBreak(); UFUNCTION(BlueprintImplementableEvent) void WallBreakBP(); UFUNCTION(BlueprintCallable) void addHitCount() { if (Role == ROLE_Authority) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "server"); wHP++; wName = FString::SanitizeFloat(wHP); //UpdateWallRender(); } else { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, "client"); } } protected: UPROPERTY(EditAnyWhere,Category="Parameters", ReplicatedUsing = OnRep_wHP, BlueprintReadWrite) float wHP = 100.f; UPROPERTY(EditAnyWhere, Category = "Parameters", ReplicatedUsing = OnRep_topHP, BlueprintReadWrite) float topHP = 0.f; UPROPERTY(EditAnyWhere, Category = "Parameters", BlueprintReadWrite) FString wName = "wall"; UPROPERTY(EditAnyWhere, Category = "Parameters", ReplicatedUsing = OnRep_wText, BlueprintReadWrite) FString wText = "push it to break"; UPROPERTY(ReplicatedUsing = OnRep_IsActive) bool bIsActive; UFUNCTION() virtual void OnRep_IsActive(); UFUNCTION() virtual void OnRep_wHP(); UFUNCTION() virtual void OnRep_topHP(); UFUNCTION() virtual void OnRep_wText(); //multicast=>func. //doRep RPC=> var. }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "BreakableWall.h" #include "MyProject.h" #include "Net/UnrealNetwork.h" // Sets default values ABreakableWall::ABreakableWall() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. //PrimaryActorTick.bCanEverTick = true; bReplicates = true; //moveable and physics enabled bReplicateMovement = true;//replicate the movement } // Called when the game starts or when spawned void ABreakableWall::BeginPlay() { Super::BeginPlay(); topHP = 100.f; } // Called every frame void ABreakableWall::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void ABreakableWall::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); //DOREPLIFETIME(ABreakableWall, COND_SimulatedOnly); DOREPLIFETIME(ABreakableWall, bIsActive); DOREPLIFETIME(ABreakableWall, wHP); DOREPLIFETIME(ABreakableWall, topHP); DOREPLIFETIME(ABreakableWall, wText); } bool ABreakableWall::isActive() { return bIsActive; } void ABreakableWall::setActive(bool inState) { if (Role == ROLE_Authority) { bIsActive = inState; } } void ABreakableWall::UpdateWallRender_Implementation() { UpdateWallRenderBP(); } void ABreakableWall::WallBreak_Implementation() { WallBreakBP(); } void ABreakableWall::onHit() { onHitBP(); } void ABreakableWall::OnRep_IsActive() { //bla bla bla code } void ABreakableWall::OnRep_wHP() { } void ABreakableWall::OnRep_topHP() { } void ABreakableWall::OnRep_wText() { } <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "BreakableWall.h" #include "Pickup.h" #include "MyProjectCharacter.generated.h" UCLASS(config=Game) class AMyProjectCharacter : public ACharacter { GENERATED_BODY() /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; public: AMyProjectCharacter(); //do when begin play void BeginPlay(); /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseLookUpRate; virtual void Tick(float DeltaSeconds); protected: /** Resets HMD orientation in VR. */ void OnResetVR(); /** Called for forwards/backward input */ void MoveForward(float Value); /** Called for side to side input */ void MoveRight(float Value); /** * Called via input to turn at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void TurnAtRate(float Rate); /** * Called via input to turn look up/down at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void LookUpAtRate(float Rate); /** Handler for when a touch input begins. */ void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location); /** Handler for when a touch input stops. */ void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location); protected: // APawn interface virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; // End of APawn interface public: /** Returns CameraBoom subobject **/ FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject **/ FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } UFUNCTION(BlueprintPure) FString myRole(); //*************************************************************************************************** //** Trace functions - used to detect items we are looking at in the world //** Adapted from code found on the unreal wiki https://wiki.unrealengine.com/Trace_Functions //*************************************************************************************************** bool Trace( UWorld* World, TArray<AActor*>& ActorsToIgnore, const FVector& Start, const FVector& End, FHitResult& HitOut, ECollisionChannel CollisionChannel, bool ReturnPhysMat ); void CallMyTrace(); void ProcessTraceHit(FHitResult& HitOut); void ClearPickupInfo(); //functional variables ABreakableWall* CurrentWall = nullptr; APickup* CurrentPickup = nullptr; UPROPERTY(BlueprintReadOnly) FString PickupName; UPROPERTY(BlueprintReadOnly) FString PickupDisplayText; bool PickupFound; //accessor and mutator UFUNCTION(BlueprintPure) float GetSpeed() { return pSpeed; } UFUNCTION(BlueprintCallable) void AddSpeed(float inSpeed) { pSpeed *= inSpeed; } UFUNCTION(BlueprintCallable) void AddStaminaJoy(float inStamina, float inJoy); UFUNCTION(BlueprintCallable) void AddSpeedMultiplier(float inMultiplier) { speedMultiplier += inMultiplier; } UFUNCTION(BlueprintPure) float GetHitPower() { return finalHitPower; } UFUNCTION(BlueprintCallable) void AddHitPower(float inHit) { pHitPower += inHit; } UFUNCTION(BlueprintPure) float GetHP() { return pHP; } UFUNCTION(BlueprintCallable) void AddHP(float inHP); UFUNCTION(BlueprintPure) bool getIsDead(){ return pIsDead; } UFUNCTION(BlueprintPure) ABreakableWall* GetCurrentWall() { return CurrentWall; } //parameters //speed:move speed multiplier(keep as 1, 1 is the fastest it can goes) //hit power: power for hitting the wall, can be take advantaged by joy (max 100+) //Joy: reduces over time, restored by consuming any powerup, impacted speed and hit power(max 100+) //HP: health of the player(decrease by time)(unused as intergrated to game mode) //pIsDead: determine player is dead or not(unused ad intergrated to game mode) protected: UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float pSpeed = 0.5f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float pStamina = 100.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float pJoy = 100.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float pHitPower = 20.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float staminaMultiplier = 3.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float joyMultiplier = 1.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float speedMultiplier = 0.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float pDefaultMax = 100.f; UPROPERTY(BlueprintReadOnly) float finalSpeed = 0.f; UPROPERTY(BlueprintReadOnly) float finalHitPower = 0.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Parameters") float pHP = 100.f; bool pIsDead = false; UPROPERTY(BlueprintReadOnly) FString pRole="client"; }; <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/GameModeBase.h" #include "MyProjectGameMode.generated.h" UCLASS(minimalapi) class AMyProjectGameMode : public AGameModeBase { GENERATED_BODY() public: AMyProjectGameMode(); virtual void Tick(float DeltaSeconds); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: //player id s(unused due to time limit, otherwise might implement the 2 bar HPs) UPROPERTY(BlueprintReadWrite, EditAnywhere) TArray<int> PlayerIDArr; //gHP health for both player could last in the game(like a timer) UPROPERTY(EditAnywhere, BlueprintReadWrite) float gHP = 100.f; UPROPERTY(VisibleAnywhere, BlueprintReadOnly) float maxHP = 0.f; FString gWinnerName = ""; UFUNCTION(BlueprintCallable) void timeDecrease(); UPROPERTY(BlueprintReadWrite) bool isInGasRm=false; UFUNCTION(BlueprintCallable) void SetWinner(FString inName); UFUNCTION(BlueprintPure) FString GetWinner() { return gWinnerName; } UFUNCTION(BlueprintCallable, NetMulticast, reliable) void AllLoser(); UFUNCTION(BlueprintImplementableEvent) void AllLoserBP(); UFUNCTION(BlueprintCallable, NetMulticast, reliable) void HasWinner(); UFUNCTION(BlueprintImplementableEvent) void HasWinnerBP(); }; <file_sep>HOW TO CONTROL: W/S/A/D: move forward/back/left/right objective: find the white object to end the game in a limited time interactive objects: -red line wall:breakable wall, keep move towards to break -red box:health pack, restores Health and Joy by 20%, hit the object to activate -green box: food pack, restores Stamina and Joy by 20%, activation same as above -pink box: speed pack, increases the player’s speed by 50% for 30 seconds, activation same as above -blue box: super pack, restores Stamina, Health and Joy by 50%, activation same as above -white box: end game pack, end the game and show who is the winner(who got that item), activation same as above. file structure: 2097Assignment2(working project folder) --ProjectA(working unreal project folder) --README.txt(copy of this read me text file) --class diagram.jpeg(class diagram of the project) --2019-11-08 19-57-43.mkv(video intro of the assignment) Custom meshes/blueprints/HUD' location in the project: content/blueprints, content/customMatl and content/HUDS Name of the main level: content/Maps/ThirdPersonExampleMap Customized starter content materials/objects: - M_Brick_Clay_Beveled - ThirdPersonCharacterPlayer gimmicks: third person top view camera, UI animation, post processing effects(chromatic abbrevation, grains, color grading, etc.) youtube video for the assignment:https://youtu.be/zNPafPiwh4E <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "MyProject/MyProjectGameMode.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeMyProjectGameMode() {} // Cross Module References MYPROJECT_API UClass* Z_Construct_UClass_AMyProjectGameMode_NoRegister(); MYPROJECT_API UClass* Z_Construct_UClass_AMyProjectGameMode(); ENGINE_API UClass* Z_Construct_UClass_AGameModeBase(); UPackage* Z_Construct_UPackage__Script_MyProject(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectGameMode_AllLoser(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectGameMode_GetWinner(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectGameMode_HasWinner(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectGameMode_SetWinner(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectGameMode_timeDecrease(); // End Cross Module References static FName NAME_AMyProjectGameMode_AllLoser = FName(TEXT("AllLoser")); void AMyProjectGameMode::AllLoser() { ProcessEvent(FindFunctionChecked(NAME_AMyProjectGameMode_AllLoser),NULL); } static FName NAME_AMyProjectGameMode_AllLoserBP = FName(TEXT("AllLoserBP")); void AMyProjectGameMode::AllLoserBP() { ProcessEvent(FindFunctionChecked(NAME_AMyProjectGameMode_AllLoserBP),NULL); } static FName NAME_AMyProjectGameMode_HasWinner = FName(TEXT("HasWinner")); void AMyProjectGameMode::HasWinner() { ProcessEvent(FindFunctionChecked(NAME_AMyProjectGameMode_HasWinner),NULL); } static FName NAME_AMyProjectGameMode_HasWinnerBP = FName(TEXT("HasWinnerBP")); void AMyProjectGameMode::HasWinnerBP() { ProcessEvent(FindFunctionChecked(NAME_AMyProjectGameMode_HasWinnerBP),NULL); } void AMyProjectGameMode::StaticRegisterNativesAMyProjectGameMode() { UClass* Class = AMyProjectGameMode::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "AllLoser", &AMyProjectGameMode::execAllLoser }, { "GetWinner", &AMyProjectGameMode::execGetWinner }, { "HasWinner", &AMyProjectGameMode::execHasWinner }, { "SetWinner", &AMyProjectGameMode::execSetWinner }, { "timeDecrease", &AMyProjectGameMode::exectimeDecrease }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_AMyProjectGameMode_AllLoser_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectGameMode_AllLoser_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectGameMode_AllLoser_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectGameMode, "AllLoser", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04024CC0, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectGameMode_AllLoser_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_AllLoser_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectGameMode_AllLoser() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectGameMode_AllLoser_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectGameMode, "AllLoserBP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x08020800, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics { struct MyProjectGameMode_eventGetWinner_Parms { FString ReturnValue; }; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Str, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(MyProjectGameMode_eventGetWinner_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectGameMode, "GetWinner", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(MyProjectGameMode_eventGetWinner_Parms), Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectGameMode_GetWinner() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectGameMode_GetWinner_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectGameMode_HasWinner_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectGameMode_HasWinner_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectGameMode_HasWinner_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectGameMode, "HasWinner", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04024CC0, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectGameMode_HasWinner_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_HasWinner_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectGameMode_HasWinner() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectGameMode_HasWinner_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectGameMode, "HasWinnerBP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x08020800, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics { struct MyProjectGameMode_eventSetWinner_Parms { FString inName; }; static const UE4CodeGen_Private::FStrPropertyParams NewProp_inName; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::NewProp_inName = { UE4CodeGen_Private::EPropertyClass::Str, "inName", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, STRUCT_OFFSET(MyProjectGameMode_eventSetWinner_Parms, inName), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::NewProp_inName, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectGameMode, "SetWinner", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(MyProjectGameMode_eventSetWinner_Parms), Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectGameMode_SetWinner() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectGameMode_SetWinner_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectGameMode_timeDecrease_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectGameMode_timeDecrease_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectGameMode_timeDecrease_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectGameMode, "timeDecrease", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectGameMode_timeDecrease_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectGameMode_timeDecrease_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectGameMode_timeDecrease() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectGameMode_timeDecrease_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_AMyProjectGameMode_NoRegister() { return AMyProjectGameMode::StaticClass(); } struct Z_Construct_UClass_AMyProjectGameMode_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_isInGasRm_MetaData[]; #endif static void NewProp_isInGasRm_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_isInGasRm; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_maxHP_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_maxHP; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_gHP_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_gHP; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_PlayerIDArr_MetaData[]; #endif static const UE4CodeGen_Private::FArrayPropertyParams NewProp_PlayerIDArr; static const UE4CodeGen_Private::FUnsizedIntPropertyParams NewProp_PlayerIDArr_Inner; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_AMyProjectGameMode_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AGameModeBase, (UObject* (*)())Z_Construct_UPackage__Script_MyProject, }; const FClassFunctionLinkInfo Z_Construct_UClass_AMyProjectGameMode_Statics::FuncInfo[] = { { &Z_Construct_UFunction_AMyProjectGameMode_AllLoser, "AllLoser" }, // 3751734982 { &Z_Construct_UFunction_AMyProjectGameMode_AllLoserBP, "AllLoserBP" }, // 942760015 { &Z_Construct_UFunction_AMyProjectGameMode_GetWinner, "GetWinner" }, // 1405243400 { &Z_Construct_UFunction_AMyProjectGameMode_HasWinner, "HasWinner" }, // 1221432476 { &Z_Construct_UFunction_AMyProjectGameMode_HasWinnerBP, "HasWinnerBP" }, // 2307333798 { &Z_Construct_UFunction_AMyProjectGameMode_SetWinner, "SetWinner" }, // 234593628 { &Z_Construct_UFunction_AMyProjectGameMode_timeDecrease, "timeDecrease" }, // 373168460 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectGameMode_Statics::Class_MetaDataParams[] = { { "HideCategories", "Info Rendering MovementReplication Replication Actor Input Movement Collision Rendering Utilities|Transformation" }, { "IncludePath", "MyProjectGameMode.h" }, { "ModuleRelativePath", "MyProjectGameMode.h" }, { "ShowCategories", "Input|MouseInput Input|TouchInput" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_isInGasRm_MetaData[] = { { "Category", "MyProjectGameMode" }, { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif void Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_isInGasRm_SetBit(void* Obj) { ((AMyProjectGameMode*)Obj)->isInGasRm = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_isInGasRm = { UE4CodeGen_Private::EPropertyClass::Bool, "isInGasRm", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000004, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(AMyProjectGameMode), &Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_isInGasRm_SetBit, METADATA_PARAMS(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_isInGasRm_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_isInGasRm_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_maxHP_MetaData[] = { { "Category", "MyProjectGameMode" }, { "ModuleRelativePath", "MyProjectGameMode.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_maxHP = { UE4CodeGen_Private::EPropertyClass::Float, "maxHP", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000020015, 1, nullptr, STRUCT_OFFSET(AMyProjectGameMode, maxHP), METADATA_PARAMS(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_maxHP_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_maxHP_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_gHP_MetaData[] = { { "Category", "MyProjectGameMode" }, { "ModuleRelativePath", "MyProjectGameMode.h" }, { "ToolTip", "gHP health for both player could last in the game(like a timer)" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_gHP = { UE4CodeGen_Private::EPropertyClass::Float, "gHP", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AMyProjectGameMode, gHP), METADATA_PARAMS(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_gHP_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_gHP_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_PlayerIDArr_MetaData[] = { { "Category", "MyProjectGameMode" }, { "ModuleRelativePath", "MyProjectGameMode.h" }, { "ToolTip", "player id s(unused due to time limit, otherwise might implement the 2 bar HPs)" }, }; #endif const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_PlayerIDArr = { UE4CodeGen_Private::EPropertyClass::Array, "PlayerIDArr", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000005, 1, nullptr, STRUCT_OFFSET(AMyProjectGameMode, PlayerIDArr), METADATA_PARAMS(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_PlayerIDArr_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_PlayerIDArr_MetaData)) }; const UE4CodeGen_Private::FUnsizedIntPropertyParams Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_PlayerIDArr_Inner = { UE4CodeGen_Private::EPropertyClass::Int, "PlayerIDArr", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0000000000000000, 1, nullptr, 0, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AMyProjectGameMode_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_isInGasRm, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_maxHP, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_gHP, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_PlayerIDArr, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectGameMode_Statics::NewProp_PlayerIDArr_Inner, }; const FCppClassTypeInfoStatic Z_Construct_UClass_AMyProjectGameMode_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<AMyProjectGameMode>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AMyProjectGameMode_Statics::ClassParams = { &AMyProjectGameMode::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x008802A8u, FuncInfo, ARRAY_COUNT(FuncInfo), Z_Construct_UClass_AMyProjectGameMode_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_AMyProjectGameMode_Statics::PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_AMyProjectGameMode_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_AMyProjectGameMode_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_AMyProjectGameMode() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AMyProjectGameMode_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AMyProjectGameMode, 2364767644); static FCompiledInDefer Z_CompiledInDefer_UClass_AMyProjectGameMode(Z_Construct_UClass_AMyProjectGameMode, &AMyProjectGameMode::StaticClass, TEXT("/Script/MyProject"), TEXT("AMyProjectGameMode"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AMyProjectGameMode); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS class ABreakableWall; #ifdef MYPROJECT_MyProjectCharacter_generated_h #error "MyProjectCharacter.generated.h already included, missing '#pragma once' in MyProjectCharacter.h" #endif #define MYPROJECT_MyProjectCharacter_generated_h #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_RPC_WRAPPERS \ \ DECLARE_FUNCTION(execGetCurrentWall) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(ABreakableWall**)Z_Param__Result=P_THIS->GetCurrentWall(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execgetIsDead) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->getIsDead(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddHP) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inHP); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddHP(Z_Param_inHP); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddHitPower) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inHit); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddHitPower(Z_Param_inHit); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetHitPower) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetHitPower(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddSpeedMultiplier) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inMultiplier); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddSpeedMultiplier(Z_Param_inMultiplier); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddStaminaJoy) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inStamina); \ P_GET_PROPERTY(UFloatProperty,Z_Param_inJoy); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddStaminaJoy(Z_Param_inStamina,Z_Param_inJoy); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddSpeed) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inSpeed); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddSpeed(Z_Param_inSpeed); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetSpeed) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetSpeed(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execmyRole) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->myRole(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_RPC_WRAPPERS_NO_PURE_DECLS \ \ DECLARE_FUNCTION(execGetCurrentWall) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(ABreakableWall**)Z_Param__Result=P_THIS->GetCurrentWall(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execgetIsDead) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->getIsDead(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddHP) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inHP); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddHP(Z_Param_inHP); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddHitPower) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inHit); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddHitPower(Z_Param_inHit); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetHitPower) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetHitPower(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddSpeedMultiplier) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inMultiplier); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddSpeedMultiplier(Z_Param_inMultiplier); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddStaminaJoy) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inStamina); \ P_GET_PROPERTY(UFloatProperty,Z_Param_inJoy); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddStaminaJoy(Z_Param_inStamina,Z_Param_inJoy); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execAddSpeed) \ { \ P_GET_PROPERTY(UFloatProperty,Z_Param_inSpeed); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->AddSpeed(Z_Param_inSpeed); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetSpeed) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetSpeed(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execmyRole) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->myRole(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesAMyProjectCharacter(); \ friend struct Z_Construct_UClass_AMyProjectCharacter_Statics; \ public: \ DECLARE_CLASS(AMyProjectCharacter, ACharacter, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(AMyProjectCharacter) #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_INCLASS \ private: \ static void StaticRegisterNativesAMyProjectCharacter(); \ friend struct Z_Construct_UClass_AMyProjectCharacter_Statics; \ public: \ DECLARE_CLASS(AMyProjectCharacter, ACharacter, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(AMyProjectCharacter) #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API AMyProjectCharacter(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(AMyProjectCharacter) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AMyProjectCharacter); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AMyProjectCharacter); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AMyProjectCharacter(AMyProjectCharacter&&); \ NO_API AMyProjectCharacter(const AMyProjectCharacter&); \ public: #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API AMyProjectCharacter(AMyProjectCharacter&&); \ NO_API AMyProjectCharacter(const AMyProjectCharacter&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, AMyProjectCharacter); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(AMyProjectCharacter); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(AMyProjectCharacter) #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_PRIVATE_PROPERTY_OFFSET \ FORCEINLINE static uint32 __PPO__CameraBoom() { return STRUCT_OFFSET(AMyProjectCharacter, CameraBoom); } \ FORCEINLINE static uint32 __PPO__FollowCamera() { return STRUCT_OFFSET(AMyProjectCharacter, FollowCamera); } \ FORCEINLINE static uint32 __PPO__pSpeed() { return STRUCT_OFFSET(AMyProjectCharacter, pSpeed); } \ FORCEINLINE static uint32 __PPO__pStamina() { return STRUCT_OFFSET(AMyProjectCharacter, pStamina); } \ FORCEINLINE static uint32 __PPO__pJoy() { return STRUCT_OFFSET(AMyProjectCharacter, pJoy); } \ FORCEINLINE static uint32 __PPO__pHitPower() { return STRUCT_OFFSET(AMyProjectCharacter, pHitPower); } \ FORCEINLINE static uint32 __PPO__staminaMultiplier() { return STRUCT_OFFSET(AMyProjectCharacter, staminaMultiplier); } \ FORCEINLINE static uint32 __PPO__joyMultiplier() { return STRUCT_OFFSET(AMyProjectCharacter, joyMultiplier); } \ FORCEINLINE static uint32 __PPO__speedMultiplier() { return STRUCT_OFFSET(AMyProjectCharacter, speedMultiplier); } \ FORCEINLINE static uint32 __PPO__pDefaultMax() { return STRUCT_OFFSET(AMyProjectCharacter, pDefaultMax); } \ FORCEINLINE static uint32 __PPO__finalSpeed() { return STRUCT_OFFSET(AMyProjectCharacter, finalSpeed); } \ FORCEINLINE static uint32 __PPO__finalHitPower() { return STRUCT_OFFSET(AMyProjectCharacter, finalHitPower); } \ FORCEINLINE static uint32 __PPO__pHP() { return STRUCT_OFFSET(AMyProjectCharacter, pHP); } \ FORCEINLINE static uint32 __PPO__pRole() { return STRUCT_OFFSET(AMyProjectCharacter, pRole); } #define MyProjectA_Source_MyProject_MyProjectCharacter_h_11_PROLOG #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_RPC_WRAPPERS \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_INCLASS \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MyProjectA_Source_MyProject_MyProjectCharacter_h_14_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_RPC_WRAPPERS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_INCLASS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_MyProjectCharacter_h_14_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MyProjectA_Source_MyProject_MyProjectCharacter_h PRAGMA_ENABLE_DEPRECATION_WARNINGS <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Engine/StaticMeshActor.h" #include "myActorMesh.generated.h" /** * */ UCLASS() class MYPROJECT_API AmyActorMesh : public AStaticMeshActor { GENERATED_BODY() public: AmyActorMesh(); //networking stuff void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>&OutLifetimeProps) const override; UFUNCTION(BlueprintPure) bool isActive(); UFUNCTION(BlueprintCallable) void setActive(bool inState); protected: UPROPERTY(ReplicatedUsing=OnRep_IsActive) bool bIsActive; UFUNCTION() virtual void OnRep_IsActive(); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "EmitPickup.h" #include "MyProject.h" #include "Net/UnrealNetwork.h" AEmitPickup::AEmitPickup() { // //Super::APickup(); pickupName = "default emit pickup"; pickupDisplayText = "default pickup display text"; } void AEmitPickup::BeginPlay() { Super::BeginPlay(); //pickupName = "default emit pickup"; //pickupDisplayText = "default pickup display text"; } void AEmitPickup::EmitExplosion_Implementation() { emitExplosionBP(); } <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "MyProject/MyProjectCharacter.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeMyProjectCharacter() {} // Cross Module References MYPROJECT_API UClass* Z_Construct_UClass_AMyProjectCharacter_NoRegister(); MYPROJECT_API UClass* Z_Construct_UClass_AMyProjectCharacter(); ENGINE_API UClass* Z_Construct_UClass_ACharacter(); UPackage* Z_Construct_UPackage__Script_MyProject(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddHitPower(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddHP(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddSpeed(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall(); MYPROJECT_API UClass* Z_Construct_UClass_ABreakableWall_NoRegister(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetHitPower(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetHP(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_getIsDead(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetSpeed(); MYPROJECT_API UFunction* Z_Construct_UFunction_AMyProjectCharacter_myRole(); ENGINE_API UClass* Z_Construct_UClass_UCameraComponent_NoRegister(); ENGINE_API UClass* Z_Construct_UClass_USpringArmComponent_NoRegister(); // End Cross Module References void AMyProjectCharacter::StaticRegisterNativesAMyProjectCharacter() { UClass* Class = AMyProjectCharacter::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "AddHitPower", &AMyProjectCharacter::execAddHitPower }, { "AddHP", &AMyProjectCharacter::execAddHP }, { "AddSpeed", &AMyProjectCharacter::execAddSpeed }, { "AddSpeedMultiplier", &AMyProjectCharacter::execAddSpeedMultiplier }, { "AddStaminaJoy", &AMyProjectCharacter::execAddStaminaJoy }, { "GetCurrentWall", &AMyProjectCharacter::execGetCurrentWall }, { "GetHitPower", &AMyProjectCharacter::execGetHitPower }, { "GetHP", &AMyProjectCharacter::execGetHP }, { "getIsDead", &AMyProjectCharacter::execgetIsDead }, { "GetSpeed", &AMyProjectCharacter::execGetSpeed }, { "myRole", &AMyProjectCharacter::execmyRole }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics { struct MyProjectCharacter_eventAddHitPower_Parms { float inHit; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_inHit; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::NewProp_inHit = { UE4CodeGen_Private::EPropertyClass::Float, "inHit", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventAddHitPower_Parms, inHit), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::NewProp_inHit, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "AddHitPower", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(MyProjectCharacter_eventAddHitPower_Parms), Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddHitPower() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_AddHitPower_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics { struct MyProjectCharacter_eventAddHP_Parms { float inHP; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_inHP; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::NewProp_inHP = { UE4CodeGen_Private::EPropertyClass::Float, "inHP", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventAddHP_Parms, inHP), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::NewProp_inHP, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "AddHP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(MyProjectCharacter_eventAddHP_Parms), Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddHP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_AddHP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics { struct MyProjectCharacter_eventAddSpeed_Parms { float inSpeed; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_inSpeed; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::NewProp_inSpeed = { UE4CodeGen_Private::EPropertyClass::Float, "inSpeed", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventAddSpeed_Parms, inSpeed), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::NewProp_inSpeed, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "AddSpeed", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(MyProjectCharacter_eventAddSpeed_Parms), Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddSpeed() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_AddSpeed_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics { struct MyProjectCharacter_eventAddSpeedMultiplier_Parms { float inMultiplier; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_inMultiplier; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::NewProp_inMultiplier = { UE4CodeGen_Private::EPropertyClass::Float, "inMultiplier", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventAddSpeedMultiplier_Parms, inMultiplier), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::NewProp_inMultiplier, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "AddSpeedMultiplier", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(MyProjectCharacter_eventAddSpeedMultiplier_Parms), Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics { struct MyProjectCharacter_eventAddStaminaJoy_Parms { float inStamina; float inJoy; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_inJoy; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_inStamina; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::NewProp_inJoy = { UE4CodeGen_Private::EPropertyClass::Float, "inJoy", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventAddStaminaJoy_Parms, inJoy), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::NewProp_inStamina = { UE4CodeGen_Private::EPropertyClass::Float, "inStamina", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventAddStaminaJoy_Parms, inStamina), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::NewProp_inJoy, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::NewProp_inStamina, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "AddStaminaJoy", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(MyProjectCharacter_eventAddStaminaJoy_Parms), Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics { struct MyProjectCharacter_eventGetCurrentWall_Parms { ABreakableWall* ReturnValue; }; static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Object, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventGetCurrentWall_Parms, ReturnValue), Z_Construct_UClass_ABreakableWall_NoRegister, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "GetCurrentWall", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(MyProjectCharacter_eventGetCurrentWall_Parms), Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics { struct MyProjectCharacter_eventGetHitPower_Parms { float ReturnValue; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Float, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventGetHitPower_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "GetHitPower", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(MyProjectCharacter_eventGetHitPower_Parms), Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetHitPower() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_GetHitPower_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics { struct MyProjectCharacter_eventGetHP_Parms { float ReturnValue; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Float, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventGetHP_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "GetHP", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(MyProjectCharacter_eventGetHP_Parms), Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetHP() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_GetHP_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics { struct MyProjectCharacter_eventgetIsDead_Parms { bool ReturnValue; }; static void NewProp_ReturnValue_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::NewProp_ReturnValue_SetBit(void* Obj) { ((MyProjectCharacter_eventgetIsDead_Parms*)Obj)->ReturnValue = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Bool, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(MyProjectCharacter_eventgetIsDead_Parms), &Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "getIsDead", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(MyProjectCharacter_eventgetIsDead_Parms), Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_getIsDead() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_getIsDead_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics { struct MyProjectCharacter_eventGetSpeed_Parms { float ReturnValue; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Float, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventGetSpeed_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, { "ToolTip", "accessor and mutator" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "GetSpeed", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(MyProjectCharacter_eventGetSpeed_Parms), Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_GetSpeed() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_GetSpeed_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics { struct MyProjectCharacter_eventmyRole_Parms { FString ReturnValue; }; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Str, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(MyProjectCharacter_eventmyRole_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMyProjectCharacter, "myRole", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(MyProjectCharacter_eventmyRole_Parms), Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_AMyProjectCharacter_myRole() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMyProjectCharacter_myRole_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_AMyProjectCharacter_NoRegister() { return AMyProjectCharacter::StaticClass(); } struct Z_Construct_UClass_AMyProjectCharacter_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pRole_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_pRole; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pHP_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_pHP; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_finalHitPower_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_finalHitPower; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_finalSpeed_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_finalSpeed; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pDefaultMax_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_pDefaultMax; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_speedMultiplier_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_speedMultiplier; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_joyMultiplier_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_joyMultiplier; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_staminaMultiplier_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_staminaMultiplier; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pHitPower_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_pHitPower; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pJoy_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_pJoy; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pStamina_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_pStamina; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pSpeed_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_pSpeed; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_PickupDisplayText_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_PickupDisplayText; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_PickupName_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_PickupName; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseLookUpRate_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseLookUpRate; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_BaseTurnRate_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_BaseTurnRate; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_FollowCamera_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_FollowCamera; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_CameraBoom_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_CameraBoom; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_AMyProjectCharacter_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_ACharacter, (UObject* (*)())Z_Construct_UPackage__Script_MyProject, }; const FClassFunctionLinkInfo Z_Construct_UClass_AMyProjectCharacter_Statics::FuncInfo[] = { { &Z_Construct_UFunction_AMyProjectCharacter_AddHitPower, "AddHitPower" }, // 1416665693 { &Z_Construct_UFunction_AMyProjectCharacter_AddHP, "AddHP" }, // 1585337960 { &Z_Construct_UFunction_AMyProjectCharacter_AddSpeed, "AddSpeed" }, // 3244243291 { &Z_Construct_UFunction_AMyProjectCharacter_AddSpeedMultiplier, "AddSpeedMultiplier" }, // 2608644773 { &Z_Construct_UFunction_AMyProjectCharacter_AddStaminaJoy, "AddStaminaJoy" }, // 2453719439 { &Z_Construct_UFunction_AMyProjectCharacter_GetCurrentWall, "GetCurrentWall" }, // 1134165411 { &Z_Construct_UFunction_AMyProjectCharacter_GetHitPower, "GetHitPower" }, // 1439350753 { &Z_Construct_UFunction_AMyProjectCharacter_GetHP, "GetHP" }, // 1333284250 { &Z_Construct_UFunction_AMyProjectCharacter_getIsDead, "getIsDead" }, // 1537669089 { &Z_Construct_UFunction_AMyProjectCharacter_GetSpeed, "GetSpeed" }, // 3299958592 { &Z_Construct_UFunction_AMyProjectCharacter_myRole, "myRole" }, // 2983219357 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::Class_MetaDataParams[] = { { "HideCategories", "Navigation" }, { "IncludePath", "MyProjectCharacter.h" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pRole_MetaData[] = { { "Category", "MyProjectCharacter" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pRole = { UE4CodeGen_Private::EPropertyClass::Str, "pRole", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000014, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, pRole), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pRole_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pRole_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHP_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHP = { UE4CodeGen_Private::EPropertyClass::Float, "pHP", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, pHP), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHP_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHP_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalHitPower_MetaData[] = { { "Category", "MyProjectCharacter" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalHitPower = { UE4CodeGen_Private::EPropertyClass::Float, "finalHitPower", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000014, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, finalHitPower), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalHitPower_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalHitPower_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalSpeed_MetaData[] = { { "Category", "MyProjectCharacter" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalSpeed = { UE4CodeGen_Private::EPropertyClass::Float, "finalSpeed", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000014, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, finalSpeed), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalSpeed_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalSpeed_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pDefaultMax_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pDefaultMax = { UE4CodeGen_Private::EPropertyClass::Float, "pDefaultMax", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, pDefaultMax), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pDefaultMax_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pDefaultMax_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_speedMultiplier_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_speedMultiplier = { UE4CodeGen_Private::EPropertyClass::Float, "speedMultiplier", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, speedMultiplier), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_speedMultiplier_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_speedMultiplier_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_joyMultiplier_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_joyMultiplier = { UE4CodeGen_Private::EPropertyClass::Float, "joyMultiplier", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, joyMultiplier), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_joyMultiplier_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_joyMultiplier_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_staminaMultiplier_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_staminaMultiplier = { UE4CodeGen_Private::EPropertyClass::Float, "staminaMultiplier", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, staminaMultiplier), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_staminaMultiplier_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_staminaMultiplier_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHitPower_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHitPower = { UE4CodeGen_Private::EPropertyClass::Float, "pHitPower", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, pHitPower), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHitPower_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHitPower_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pJoy_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pJoy = { UE4CodeGen_Private::EPropertyClass::Float, "pJoy", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, pJoy), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pJoy_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pJoy_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pStamina_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pStamina = { UE4CodeGen_Private::EPropertyClass::Float, "pStamina", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, pStamina), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pStamina_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pStamina_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pSpeed_MetaData[] = { { "Category", "Parameters" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pSpeed = { UE4CodeGen_Private::EPropertyClass::Float, "pSpeed", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, pSpeed), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pSpeed_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pSpeed_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupDisplayText_MetaData[] = { { "Category", "MyProjectCharacter" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupDisplayText = { UE4CodeGen_Private::EPropertyClass::Str, "PickupDisplayText", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000014, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, PickupDisplayText), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupDisplayText_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupDisplayText_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupName_MetaData[] = { { "Category", "MyProjectCharacter" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupName = { UE4CodeGen_Private::EPropertyClass::Str, "PickupName", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000014, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, PickupName), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupName_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupName_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseLookUpRate_MetaData[] = { { "Category", "Camera" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, { "ToolTip", "Base look up/down rate, in deg/sec. Other scaling may affect final rate." }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseLookUpRate = { UE4CodeGen_Private::EPropertyClass::Float, "BaseLookUpRate", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000020015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, BaseLookUpRate), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseLookUpRate_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseLookUpRate_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseTurnRate_MetaData[] = { { "Category", "Camera" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, { "ToolTip", "Base turn rate, in deg/sec. Other scaling may affect final turn rate." }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseTurnRate = { UE4CodeGen_Private::EPropertyClass::Float, "BaseTurnRate", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000020015, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, BaseTurnRate), METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseTurnRate_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseTurnRate_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_FollowCamera_MetaData[] = { { "AllowPrivateAccess", "true" }, { "Category", "Camera" }, { "EditInline", "true" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, { "ToolTip", "Follow camera" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_FollowCamera = { UE4CodeGen_Private::EPropertyClass::Object, "FollowCamera", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x00400000000a001d, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, FollowCamera), Z_Construct_UClass_UCameraComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_FollowCamera_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_FollowCamera_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_CameraBoom_MetaData[] = { { "AllowPrivateAccess", "true" }, { "Category", "Camera" }, { "EditInline", "true" }, { "ModuleRelativePath", "MyProjectCharacter.h" }, { "ToolTip", "Camera boom positioning the camera behind the character" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_CameraBoom = { UE4CodeGen_Private::EPropertyClass::Object, "CameraBoom", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x00400000000a001d, 1, nullptr, STRUCT_OFFSET(AMyProjectCharacter, CameraBoom), Z_Construct_UClass_USpringArmComponent_NoRegister, METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_CameraBoom_MetaData, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_CameraBoom_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_AMyProjectCharacter_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pRole, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHP, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalHitPower, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_finalSpeed, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pDefaultMax, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_speedMultiplier, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_joyMultiplier, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_staminaMultiplier, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pHitPower, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pJoy, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pStamina, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_pSpeed, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupDisplayText, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_PickupName, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseLookUpRate, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_BaseTurnRate, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_FollowCamera, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_AMyProjectCharacter_Statics::NewProp_CameraBoom, }; const FCppClassTypeInfoStatic Z_Construct_UClass_AMyProjectCharacter_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<AMyProjectCharacter>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AMyProjectCharacter_Statics::ClassParams = { &AMyProjectCharacter::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x008000A0u, FuncInfo, ARRAY_COUNT(FuncInfo), Z_Construct_UClass_AMyProjectCharacter_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::PropPointers), "Game", &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_AMyProjectCharacter_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_AMyProjectCharacter_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_AMyProjectCharacter() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AMyProjectCharacter_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(AMyProjectCharacter, 330752082); static FCompiledInDefer Z_CompiledInDefer_UClass_AMyProjectCharacter(Z_Construct_UClass_AMyProjectCharacter, &AMyProjectCharacter::StaticClass, TEXT("/Script/MyProject"), TEXT("AMyProjectCharacter"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(AMyProjectCharacter); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Pawn.h" #include "Components/ArrowComponent.h" #include"Camera/CameraComponent.h" #include "tankPlayer.generated.h" UCLASS() class MYPROJECT_API AtankPlayer : public APawn { GENERATED_BODY() public: // Sets default values for this character's properties AtankPlayer(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; // Called to bind functionality to input virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; //component to be visible UPROPERTY(EditAnywhere) UStaticMeshComponent* VisableComponent; //UPROPERTY(EditAnywhere) // UCapsuleComponent* CapsuleComponent; UPROPERTY(EditAnyWhere) UCameraComponent* Camera; protected: float speed = 500.0f; float shootPower = 10.f; float HP = 100.f; FVector MovementInput; float turningInput; void MoveForward(float Value); void TurnRight(float Value); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" /** * */ class MYPROJECT_API LineTrace { public: LineTrace(); ~LineTrace(); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "Pickup.h" #include "MyProject.h" #include "Net/UnrealNetwork.h" // Sets default values APickup::APickup() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. //PrimaryActorTick.bCanEverTick = true; bReplicates = true;//replicate the object to every player //moveable and physics enabled bReplicateMovement = true;//replicate the movement GetStaticMeshComponent()->SetMobility(EComponentMobility::Movable); GetStaticMeshComponent()->SetSimulatePhysics(true); //pickupArrow->AttachParent = RootComponent; //pickupBaseMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("pickupBaseMesh")); //pickupBaseMesh->SetupAttachment(RootComponent); //pickupArrow = CreateDefaultSubobject<UArrowComponent>(TEXT("pickupArrow")); //pickupArrow->SetupAttachment(RootComponent); } // Called when the game starts or when spawned void APickup::BeginPlay() { Super::BeginPlay(); } // Called every frame void APickup::Tick(float DeltaTime) { Super::Tick(DeltaTime); } FString APickup::GetPickupName() { return pickupName; } FString APickup::GetPickupDisplayText() { return pickupDisplayText; } void APickup::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); //these var. will be peramently replicated from server to client. DOREPLIFETIME(APickup, bIsActive); DOREPLIFETIME(APickup, HitCountA); DOREPLIFETIME(APickup, pickupDisplayText); } bool APickup::isActive() { return bIsActive; } void APickup::setActive(bool inState) { if (Role == ROLE_Authority) { bIsActive = inState; } } void APickup::OnRep_IsActive() { //bla bla bla code } void APickup::OnRep_HitCount() { } void APickup::OnRep_HitCountA() { } void APickup::OnRep_pickupDisplayText() { } bool APickup::checkIsPlayerHit() { //GetWorld()->player return false; } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Pickup.h" #include "EmitPickup.generated.h" /** * */ UCLASS() class MYPROJECT_API AEmitPickup : public APickup { GENERATED_BODY() public: // Sets default values for this actor's properties AEmitPickup(); UFUNCTION(BlueprintCallable,NetMulticast,reliable) void EmitExplosion(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; //only things to concern is the time, stamina and joy UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "parameters") float addSpeed = 0.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "parameters") float addPower = 0.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "parameters") float addHP = 0.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "parameters") float addStamina = 0.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "parameters") float addJoy = 0.f; UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "parameters") bool isEndGame = false; UFUNCTION(BlueprintImplementableEvent) void emitExplosionBP(); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "MyPickupWall.h" AMyPickupWall::AMyPickupWall() { pickupName = "default wall"; pickupDisplayText = "default pickup display text"; } void AMyPickupWall::BeginPlay() { Super::BeginPlay(); } void AMyPickupWall::BreakWall_Implementation() { BreakWallBP(); } <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/ObjectMacros.h" #include "UObject/ScriptMacros.h" PRAGMA_DISABLE_DEPRECATION_WARNINGS #ifdef MYPROJECT_BreakableWall_generated_h #error "BreakableWall.generated.h already included, missing '#pragma once' in BreakableWall.h" #endif #define MYPROJECT_BreakableWall_generated_h #define MyProjectA_Source_MyProject_BreakableWall_h_12_RPC_WRAPPERS \ virtual void WallBreak_Implementation(); \ virtual void UpdateWallRender_Implementation(); \ \ DECLARE_FUNCTION(execOnRep_wText) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_wText(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_topHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_topHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_wHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_wHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_IsActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_IsActive(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execaddHitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->addHitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execWallBreak) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->WallBreak_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execUpdateWallRender) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->UpdateWallRender_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execonHit) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->onHit(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetText) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->GetText(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetName) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->GetName(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execsetActive) \ { \ P_GET_UBOOL(Z_Param_inState); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->setActive(Z_Param_inState); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execisActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->isActive(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_BreakableWall_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ virtual void WallBreak_Implementation(); \ virtual void UpdateWallRender_Implementation(); \ \ DECLARE_FUNCTION(execOnRep_wText) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_wText(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_topHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_topHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_wHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_wHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execOnRep_IsActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->OnRep_IsActive(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execaddHitCount) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->addHitCount(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execWallBreak) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->WallBreak_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execUpdateWallRender) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->UpdateWallRender_Implementation(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execonHit) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->onHit(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetHP) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(float*)Z_Param__Result=P_THIS->GetHP(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetText) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->GetText(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execGetName) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(FString*)Z_Param__Result=P_THIS->GetName(); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execsetActive) \ { \ P_GET_UBOOL(Z_Param_inState); \ P_FINISH; \ P_NATIVE_BEGIN; \ P_THIS->setActive(Z_Param_inState); \ P_NATIVE_END; \ } \ \ DECLARE_FUNCTION(execisActive) \ { \ P_FINISH; \ P_NATIVE_BEGIN; \ *(bool*)Z_Param__Result=P_THIS->isActive(); \ P_NATIVE_END; \ } #define MyProjectA_Source_MyProject_BreakableWall_h_12_EVENT_PARMS #define MyProjectA_Source_MyProject_BreakableWall_h_12_CALLBACK_WRAPPERS #define MyProjectA_Source_MyProject_BreakableWall_h_12_INCLASS_NO_PURE_DECLS \ private: \ static void StaticRegisterNativesABreakableWall(); \ friend struct Z_Construct_UClass_ABreakableWall_Statics; \ public: \ DECLARE_CLASS(ABreakableWall, AStaticMeshActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(ABreakableWall) #define MyProjectA_Source_MyProject_BreakableWall_h_12_INCLASS \ private: \ static void StaticRegisterNativesABreakableWall(); \ friend struct Z_Construct_UClass_ABreakableWall_Statics; \ public: \ DECLARE_CLASS(ABreakableWall, AStaticMeshActor, COMPILED_IN_FLAGS(0), CASTCLASS_None, TEXT("/Script/MyProject"), NO_API) \ DECLARE_SERIALIZER(ABreakableWall) #define MyProjectA_Source_MyProject_BreakableWall_h_12_STANDARD_CONSTRUCTORS \ /** Standard constructor, called after all reflected properties have been initialized */ \ NO_API ABreakableWall(const FObjectInitializer& ObjectInitializer); \ DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(ABreakableWall) \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ABreakableWall); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ABreakableWall); \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ABreakableWall(ABreakableWall&&); \ NO_API ABreakableWall(const ABreakableWall&); \ public: #define MyProjectA_Source_MyProject_BreakableWall_h_12_ENHANCED_CONSTRUCTORS \ private: \ /** Private move- and copy-constructors, should never be used */ \ NO_API ABreakableWall(ABreakableWall&&); \ NO_API ABreakableWall(const ABreakableWall&); \ public: \ DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, ABreakableWall); \ DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(ABreakableWall); \ DEFINE_DEFAULT_CONSTRUCTOR_CALL(ABreakableWall) #define MyProjectA_Source_MyProject_BreakableWall_h_12_PRIVATE_PROPERTY_OFFSET \ FORCEINLINE static uint32 __PPO__wHP() { return STRUCT_OFFSET(ABreakableWall, wHP); } \ FORCEINLINE static uint32 __PPO__topHP() { return STRUCT_OFFSET(ABreakableWall, topHP); } \ FORCEINLINE static uint32 __PPO__wName() { return STRUCT_OFFSET(ABreakableWall, wName); } \ FORCEINLINE static uint32 __PPO__wText() { return STRUCT_OFFSET(ABreakableWall, wText); } \ FORCEINLINE static uint32 __PPO__bIsActive() { return STRUCT_OFFSET(ABreakableWall, bIsActive); } #define MyProjectA_Source_MyProject_BreakableWall_h_9_PROLOG \ MyProjectA_Source_MyProject_BreakableWall_h_12_EVENT_PARMS #define MyProjectA_Source_MyProject_BreakableWall_h_12_GENERATED_BODY_LEGACY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_BreakableWall_h_12_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_BreakableWall_h_12_RPC_WRAPPERS \ MyProjectA_Source_MyProject_BreakableWall_h_12_CALLBACK_WRAPPERS \ MyProjectA_Source_MyProject_BreakableWall_h_12_INCLASS \ MyProjectA_Source_MyProject_BreakableWall_h_12_STANDARD_CONSTRUCTORS \ public: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #define MyProjectA_Source_MyProject_BreakableWall_h_12_GENERATED_BODY \ PRAGMA_DISABLE_DEPRECATION_WARNINGS \ public: \ MyProjectA_Source_MyProject_BreakableWall_h_12_PRIVATE_PROPERTY_OFFSET \ MyProjectA_Source_MyProject_BreakableWall_h_12_RPC_WRAPPERS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_BreakableWall_h_12_CALLBACK_WRAPPERS \ MyProjectA_Source_MyProject_BreakableWall_h_12_INCLASS_NO_PURE_DECLS \ MyProjectA_Source_MyProject_BreakableWall_h_12_ENHANCED_CONSTRUCTORS \ private: \ PRAGMA_ENABLE_DEPRECATION_WARNINGS #undef CURRENT_FILE_ID #define CURRENT_FILE_ID MyProjectA_Source_MyProject_BreakableWall_h PRAGMA_ENABLE_DEPRECATION_WARNINGS <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "MyProjectCharacter.h" #include "HeadMountedDisplayFunctionLibrary.h" #include "Camera/CameraComponent.h" #include "Components/CapsuleComponent.h" #include "Components/InputComponent.h" #include "GameFramework/CharacterMovementComponent.h" #include "GameFramework/Controller.h" #include "GameFramework/SpringArmComponent.h" #include "DrawDebugHelpers.h" #include "Pickup.h" #include "BreakableWall.h" ////////////////////////////////////////////////////////////////////////// // AMyProjectCharacter AMyProjectCharacter::AMyProjectCharacter() { // Set size for collision capsule GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); // set our turn rates for input BaseTurnRate = 45.f; BaseLookUpRate = 45.f; // Don't rotate when the controller rotates. Let that just affect the camera. bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; // Configure character movement GetCharacterMovement()->bOrientRotationToMovement = true; // Character moves in the direction of input... GetCharacterMovement()->RotationRate = FRotator(0.0f, 540.0f, 0.0f); // ...at this rotation rate GetCharacterMovement()->JumpZVelocity = 600.f; GetCharacterMovement()->AirControl = 0.2f; // Create a camera boom (pulls in towards the player if there is a collision) CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->TargetArmLength = 0.f; // The camera follows at this distance behind the character CameraBoom->bUsePawnControlRotation = true; // Rotate the arm based on the controller // Create a follow camera FollowCamera = CreateDefaultSubobject<UCameraComponent>(TEXT("FollowCamera")); FollowCamera->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); // Attach the camera to the end of the boom and let the boom adjust to match the controller orientation FollowCamera->bUsePawnControlRotation = false; // Camera does not rotate relative to arm //Camera->SetupAttachment(CapsuleComponent); FollowCamera->SetRelativeLocation(FVector(0.f, 0.f, 500.f)); FollowCamera->SetRelativeRotation(FRotator(180.f, -90.f, 0.f)); // Note: The skeletal mesh and anim blueprint references on the Mesh component (inherited from Character) // are set in the derived blueprint asset named MyCharacter (to avoid direct content references in C++) } void AMyProjectCharacter::BeginPlay() { Super::BeginPlay(); if (Role == ROLE_Authority) { pRole="server"; } else { pRole = "client"; } } ////////////////////////////////////////////////////////////////////////// // Input void AMyProjectCharacter::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) { // Set up gameplay key bindings check(PlayerInputComponent); PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ACharacter::Jump); PlayerInputComponent->BindAction("Jump", IE_Released, this, &ACharacter::StopJumping); PlayerInputComponent->BindAxis("MoveForward", this, &AMyProjectCharacter::MoveForward); PlayerInputComponent->BindAxis("MoveRight", this, &AMyProjectCharacter::MoveRight); // We have 2 versions of the rotation bindings to handle different kinds of devices differently // "turn" handles devices that provide an absolute delta, such as a mouse. // "turnrate" is for devices that we choose to treat as a rate of change, such as an analog joystick PlayerInputComponent->BindAxis("Turn", this, &APawn::AddControllerYawInput); PlayerInputComponent->BindAxis("TurnRate", this, &AMyProjectCharacter::TurnAtRate); PlayerInputComponent->BindAxis("LookUp", this, &APawn::AddControllerPitchInput); PlayerInputComponent->BindAxis("LookUpRate", this, &AMyProjectCharacter::LookUpAtRate); // handle touch devices PlayerInputComponent->BindTouch(IE_Pressed, this, &AMyProjectCharacter::TouchStarted); PlayerInputComponent->BindTouch(IE_Released, this, &AMyProjectCharacter::TouchStopped); // VR headset functionality PlayerInputComponent->BindAction("ResetVR", IE_Pressed, this, &AMyProjectCharacter::OnResetVR); } FString AMyProjectCharacter::myRole() { if (Role == ROLE_Authority) { return TEXT("Server"); pRole = "server"; } else { return TEXT("Client"); pRole = "client"; } } void AMyProjectCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Call parent class tick function CallMyTrace(); //lock the stamina and joy when more than default max if (pStamina > pDefaultMax) { pStamina = pDefaultMax; } if (pJoy > pDefaultMax) { pJoy = pDefaultMax; } //Joy reduces over time pJoy -= DeltaTime*joyMultiplier; finalSpeed = pSpeed;//lock the stamina and joy when less than 0 if (pStamina <= 0.f) { pStamina = 0.f; finalSpeed *= 0.2; } else if (pJoy <= 0.f) { pJoy = 0.f; finalSpeed *= 0.5; } //speedMultiplier reduces over time speedMultiplier -= DeltaTime; //if there's a speed multiplier more than 0, multiply final speed by 2 if (speedMultiplier <= 0.f) { speedMultiplier = 0; } else if (speedMultiplier >= 30.f) { speedMultiplier = 30.f; } else { finalSpeed *= 2.f; } //define the final hit power finalHitPower = pHitPower * (1 + (pJoy / pDefaultMax)); } void AMyProjectCharacter::OnResetVR() { UHeadMountedDisplayFunctionLibrary::ResetOrientationAndPosition(); } void AMyProjectCharacter::TouchStarted(ETouchIndex::Type FingerIndex, FVector Location) { Jump(); } void AMyProjectCharacter::TouchStopped(ETouchIndex::Type FingerIndex, FVector Location) { StopJumping(); } void AMyProjectCharacter::TurnAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerYawInput(Rate * BaseTurnRate * GetWorld()->GetDeltaSeconds()); } void AMyProjectCharacter::LookUpAtRate(float Rate) { // calculate delta for this frame from the rate information AddControllerPitchInput(Rate * BaseLookUpRate * GetWorld()->GetDeltaSeconds()); } void AMyProjectCharacter::MoveForward(float Value) { if ((Controller != NULL) && (Value != 0.0f)) { // find out which way is forward const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get forward vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::X); AddMovementInput(Direction, (Value*finalSpeed)); //Stamina reduced by moving pStamina -= GetWorld()->DeltaTimeSeconds*staminaMultiplier; } } void AMyProjectCharacter::MoveRight(float Value) { if ( (Controller != NULL) && (Value != 0.0f) ) { // find out which way is right const FRotator Rotation = Controller->GetControlRotation(); const FRotator YawRotation(0, Rotation.Yaw, 0); // get right vector const FVector Direction = FRotationMatrix(YawRotation).GetUnitAxis(EAxis::Y); // add movement in that direction AddMovementInput(Direction, (Value*finalSpeed)); //Stamina reduced by moving pStamina -= GetWorld()->DeltaTimeSeconds*staminaMultiplier; } } //*************************************************************************************************** //** Trace functions - used to detect items we are looking at in the world //*************************************************************************************************** //*************************************************************************************************** //*************************************************************************************************** //** Trace() - called by our CallMyTrace() function which sets up our parameters and passes them through //*************************************************************************************************** bool AMyProjectCharacter::Trace( UWorld* World, TArray<AActor*>& ActorsToIgnore, const FVector& Start, const FVector& End, FHitResult& HitOut, ECollisionChannel CollisionChannel = ECC_Pawn, bool ReturnPhysMat = false ) { // The World parameter refers to our game world (map/level) // If there is no World, abort if (!World) { return false; } // Set up our TraceParams object FCollisionQueryParams TraceParams(FName(TEXT("My Trace")), true, ActorsToIgnore[0]); // Should we simple or complex collision? TraceParams.bTraceComplex = true; // We don't need Physics materials TraceParams.bReturnPhysicalMaterial = ReturnPhysMat; // Add our ActorsToIgnore TraceParams.AddIgnoredActors(ActorsToIgnore); // When we're debugging it is really useful to see where our trace is in the world // We can use World->DebugDrawTraceTag to tell Unreal to draw debug lines for our trace // (remove these lines to remove the debug - or better create a debug switch!) const FName TraceTag("MyTraceTag"); World->DebugDrawTraceTag = TraceTag; TraceParams.TraceTag = TraceTag; // Force clear the HitData which contains our results HitOut = FHitResult(ForceInit); // Perform our trace World->LineTraceSingleByChannel ( HitOut, //result Start, //start End, //end CollisionChannel, //collision channel TraceParams ); // If we hit an actor, return true return (HitOut.GetActor() != NULL); } //*************************************************************************************************** //** CallMyTrace() - sets up our parameters and then calls our Trace() function //*************************************************************************************************** void AMyProjectCharacter::CallMyTrace() { // Get the location of the camera (where we are looking from) and the direction we are looking in const FVector Start = GetActorLocation(); //const FVector ForwardVector = GetActorRotation().Vector(); // How for in front of our character do we want our trace to extend? // ForwardVector is a unit vector, so we multiply by the desired distance //const FVector End = Start + ForwardVector * 256; const FVector End = Start + GetActorForwardVector()*256; // Force clear the HitData which contains our results FHitResult HitData(ForceInit); // What Actors do we want our trace to Ignore? TArray<AActor*> ActorsToIgnore; //Ignore the player character - so you don't hit yourself! ActorsToIgnore.Add(this); // Call our Trace() function with the paramaters we have set up // If it Hits anything if (Trace(GetWorld(), ActorsToIgnore, Start, End, HitData, ECC_Visibility, false)) { // Process our HitData if (HitData.GetActor()) { //UE_LOG(LogClass, Warning, TEXT("This a testing statement. %s"), *HitData.GetActor()->GetName()); ProcessTraceHit(HitData); } else { // The trace did not return an Actor // An error has occurred // Record a message in the error log } } else { // We did not hit an Actor ClearPickupInfo(); } } //*************************************************************************************************** //** ProcessTraceHit() - process our Trace Hit result //*************************************************************************************************** void AMyProjectCharacter::ProcessTraceHit(FHitResult& HitOut) { // Cast the actor to APickup APickup* const TestPickup = Cast<APickup>(HitOut.GetActor()); ABreakableWall* const targetWall = Cast <ABreakableWall>(HitOut.GetActor()); //AMyPickupWall* const pickupWall= Cast <AMyPickupWall>(HitOut.GetActor()); if (TestPickup) { // Keep a pointer to the Pickup CurrentPickup = TestPickup; //assign the pickup name for HUD use/other function. PickupName = TestPickup->GetPickupName(); PickupDisplayText = TestPickup->GetPickupDisplayText(); // Set a local variable of the PickupName for the HUD //UE_LOG(LogClass, Warning, TEXT("PickupName: %s"), *TestPickup->GetPickupName()); if (Role == ROLE_Authority) { FString inText = "PickupName: " + TestPickup->GetPickupName(); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, inText ); } // Set a local variable of the PickupDisplayText for the HUD //UE_LOG(LogClass, Warning, TEXT("PickupDisplayText: %s"), *TestPickup->GetPickupDisplayText()); PickupFound = true; } else if (targetWall) { // Keep a pointer to the wall CurrentWall = targetWall; //display the name of the wall //PickupName = targetWall->GetName(); PickupName = targetWall->GetName(); PickupDisplayText = targetWall->GetText(); // Set a local variable of the PickupName for the HUD //UE_LOG(LogClass, Warning, TEXT("PickupName: %s"), *TestPickup->GetPickupName()); if (Role == ROLE_Authority) { FString inText = "PickupName: " + targetWall->GetName(); //GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, inText ); } // Set a local variable of the PickupDisplayText for the HUD //UE_LOG(LogClass, Warning, TEXT("PickupDisplayText: %s"), *TestPickup->GetPickupDisplayText()); PickupFound = true; } else { //UE_LOG(LogClass, Warning, TEXT("TestPickup is NOT a Pickup!")); ClearPickupInfo(); } } void AMyProjectCharacter::ClearPickupInfo() { PickupName = ""; PickupDisplayText = ""; CurrentWall = nullptr; CurrentPickup = nullptr; PickupFound = false; } void AMyProjectCharacter::AddStaminaJoy(float inStamina, float inJoy) { pStamina += inStamina; pJoy += inJoy; } void AMyProjectCharacter::AddHP(float inHP) { pHP += inHP; if (pHP <= 0) { pIsDead = true; pHP = 0; } } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "LineTrace.h" LineTrace::LineTrace() { } LineTrace::~LineTrace() { } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Pickup.h" #include "MyPickupWall.generated.h" /** * */ UCLASS() class MYPROJECT_API AMyPickupWall : public APickup { GENERATED_BODY() AMyPickupWall(); public: UFUNCTION(BlueprintCallable, NetMulticast, reliable) void BreakWall(); UFUNCTION(BlueprintImplementableEvent) void BreakWallBP(); protected: // Called when the game starts or when spawned virtual void BeginPlay() override; }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "myActorMesh.h" #include "MyProject.h" #include "Net/UnrealNetwork.h" AmyActorMesh::AmyActorMesh() { bReplicates = true; PrimaryActorTick.bCanEverTick = true; //moveable and physics enabled bReplicateMovement = true; GetStaticMeshComponent()->SetMobility(EComponentMobility::Movable); GetStaticMeshComponent()->SetSimulatePhysics(true); } void AmyActorMesh::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AmyActorMesh, bIsActive); } bool AmyActorMesh::isActive() { return bIsActive; } void AmyActorMesh::setActive(bool inState) { if (Role == ROLE_Authority) { bIsActive = inState; } } void AmyActorMesh::OnRep_IsActive() { //bla bla bla code } <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Engine/StaticMeshActor.h" #include "Components/ArrowComponent.h" #include "Pickup.generated.h" UCLASS() class MYPROJECT_API APickup : public AStaticMeshActor { GENERATED_BODY() public: // Sets default values for this actor's properties APickup(); //UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components") // class UStaticMeshComponent* pickupBaseMesh; //UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Components") // class UArrowComponent* pickupArrow; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; //properties UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "basic property") FString pickupName = "default pickup"; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "basic property",ReplicatedUsing = OnRep_pickupDisplayText) FString pickupDisplayText = "default pickup display text"; UPROPERTY(ReplicatedUsing = OnRep_HitCount, BlueprintReadWrite, EditAnywhere, Category = "basic property") float HitCount; UPROPERTY(ReplicatedUsing = OnRep_HitCountA, BlueprintReadWrite, EditAnywhere, Category = "basic property") float HitCountA; UPROPERTY(BlueprintReadWrite, EditAnywhere, Category = "basic property") FString name; public: // Called every frame virtual void Tick(float DeltaTime) override; //acessor for pickup name and display text FString GetPickupName(); FString GetPickupDisplayText(); //networking stuff virtual void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>&OutLifetimeProps) const override; UFUNCTION(BlueprintPure) bool isActive(); UFUNCTION(BlueprintCallable) void setActive(bool inState); UFUNCTION(BlueprintPure) float getHitCount() { return HitCount; } UFUNCTION(BlueprintCallable) void addHitCount() { if (Role == ROLE_Authority) { HitCountA++; pickupDisplayText =FString::SanitizeFloat(HitCountA); } else { } } protected: UPROPERTY(ReplicatedUsing = OnRep_IsActive) bool bIsActive; UFUNCTION() virtual void OnRep_IsActive(); UFUNCTION() virtual void OnRep_HitCount(); UFUNCTION() virtual void OnRep_HitCountA(); UFUNCTION() virtual void OnRep_pickupDisplayText(); UFUNCTION(BlueprintCallable) bool checkIsPlayerHit(); }; <file_sep>// Fill out your copyright notice in the Description page of Project Settings. #include "tankPlayer.h" #include "DrawDebugHelpers.h" #include "Components/CapsuleComponent.h" //#include "Components/InputComponent.h" #include "GameFramework/Controller.h" // Sets default values AtankPlayer::AtankPlayer() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; //receive input to do move actions AutoPossessPlayer = EAutoReceiveInput::Player0; //RootComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisableComponent")); // Set size for collision capsule //GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); //Connect components again //RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootComponent")); //VisableComponent = CreateDefaultSubobject<UCapsuleComponent>(TEXT("CapsuleComponent")); VisableComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("VisableComponent")); //VisableComponent->SetupAttachment(RootComponent); Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera")); //Camera->SetupAttachment(CapsuleComponent); Camera->SetRelativeLocation(FVector(-0, 0.f, 1000.f)); Camera->SetRelativeRotation(FRotator(-0.f, 0.f, 0.f)); // Set size for collision capsule //GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); } // Called when the game starts or when spawned void AtankPlayer::BeginPlay() { Super::BeginPlay(); } // Called every frame void AtankPlayer::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!MovementInput.IsZero()) { // get forward vector MovementInput.Normalize(); FVector NewLocation = GetActorLocation() + (MovementInput*speed*DeltaTime) ; SetActorLocation(NewLocation); AddMovementInput(MovementInput, speed,true); //RootComponent->add //AddActorLocalOffset(MovementInput, true); } if (turningInput != 0.f) { float newYaw = GetActorRotation().Yaw + (turningInput*DeltaTime); //AddActorLocalRotation(FRotator(0, turningInput*DeltaTime, 0)); AddControllerYawInput(turningInput*DeltaTime); //SetActorRotation(FRotator(0, newYaw, 0)); } } // Called to bind functionality to input void AtankPlayer::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("TurnRight", this, &AtankPlayer::TurnRight); PlayerInputComponent->BindAxis("MoveForward", this, &AtankPlayer::MoveForward); } void AtankPlayer::MoveForward(float Value) { MovementInput = GetActorForwardVector()*Value; } void AtankPlayer::TurnRight(float Value) { turningInput = Value * 30.f; } <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "MyProjectGameMode.h" #include "MyProjectCharacter.h" #include "UObject/ConstructorHelpers.h" AMyProjectGameMode::AMyProjectGameMode() { // set default pawn class to our Blueprinted character static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/ThirdPersonCPP/Blueprints/ThirdPersonCharacter")); //static ConstructorHelpers::FClassFinder<APawn> PlayerPawnBPClass(TEXT("/Game/mytankPlayer")); if (PlayerPawnBPClass.Class != NULL) { DefaultPawnClass = PlayerPawnBPClass.Class; } } // Called when the game starts or when spawned void AMyProjectGameMode::BeginPlay() { Super::BeginPlay(); maxHP = gHP; } void AMyProjectGameMode::Tick(float DeltaSeconds) { if (isInGasRm) { timeDecrease(); } //if winner name is obtained, stop the game and tell everyone that guy is win if (gWinnerName != "") { HasWinner(); } //otherwise, if there no time left, tell both player that they're all lost else if (gHP <= 0.f) { AllLoser(); } //if there's too much hp, block it back to max hp else if (gHP > 30.f) { gHP = maxHP; } } void AMyProjectGameMode::timeDecrease() { //timer action //reduces the players health by 1% of its max hp every 5 seconds gHP -= (GetWorld()->DeltaTimeSeconds * (maxHP* (0.01f/5.f))); } void AMyProjectGameMode::SetWinner(FString inName) { gWinnerName = inName; } void AMyProjectGameMode::AllLoser_Implementation() { AllLoserBP(); } void AMyProjectGameMode::HasWinner_Implementation() { HasWinnerBP(); } <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "MyProject/Pickup.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodePickup() {} // Cross Module References MYPROJECT_API UClass* Z_Construct_UClass_APickup_NoRegister(); MYPROJECT_API UClass* Z_Construct_UClass_APickup(); ENGINE_API UClass* Z_Construct_UClass_AStaticMeshActor(); UPackage* Z_Construct_UPackage__Script_MyProject(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_addHitCount(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_checkIsPlayerHit(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_getHitCount(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_isActive(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_OnRep_HitCount(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_OnRep_HitCountA(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_OnRep_IsActive(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_OnRep_pickupDisplayText(); MYPROJECT_API UFunction* Z_Construct_UFunction_APickup_setActive(); // End Cross Module References void APickup::StaticRegisterNativesAPickup() { UClass* Class = APickup::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "addHitCount", &APickup::execaddHitCount }, { "checkIsPlayerHit", &APickup::execcheckIsPlayerHit }, { "getHitCount", &APickup::execgetHitCount }, { "isActive", &APickup::execisActive }, { "OnRep_HitCount", &APickup::execOnRep_HitCount }, { "OnRep_HitCountA", &APickup::execOnRep_HitCountA }, { "OnRep_IsActive", &APickup::execOnRep_IsActive }, { "OnRep_pickupDisplayText", &APickup::execOnRep_pickupDisplayText }, { "setActive", &APickup::execsetActive }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_APickup_addHitCount_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_addHitCount_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_addHitCount_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "addHitCount", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_addHitCount_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_addHitCount_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_addHitCount() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_addHitCount_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics { struct Pickup_eventcheckIsPlayerHit_Parms { bool ReturnValue; }; static void NewProp_ReturnValue_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::NewProp_ReturnValue_SetBit(void* Obj) { ((Pickup_eventcheckIsPlayerHit_Parms*)Obj)->ReturnValue = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Bool, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(Pickup_eventcheckIsPlayerHit_Parms), &Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "checkIsPlayerHit", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04080401, sizeof(Pickup_eventcheckIsPlayerHit_Parms), Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_checkIsPlayerHit() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_checkIsPlayerHit_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_getHitCount_Statics { struct Pickup_eventgetHitCount_Parms { float ReturnValue; }; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_APickup_getHitCount_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Float, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, STRUCT_OFFSET(Pickup_eventgetHitCount_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_APickup_getHitCount_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_APickup_getHitCount_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_getHitCount_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_getHitCount_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "getHitCount", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(Pickup_eventgetHitCount_Parms), Z_Construct_UFunction_APickup_getHitCount_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_APickup_getHitCount_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_getHitCount_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_getHitCount_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_getHitCount() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_getHitCount_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_isActive_Statics { struct Pickup_eventisActive_Parms { bool ReturnValue; }; static void NewProp_ReturnValue_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_APickup_isActive_Statics::NewProp_ReturnValue_SetBit(void* Obj) { ((Pickup_eventisActive_Parms*)Obj)->ReturnValue = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_APickup_isActive_Statics::NewProp_ReturnValue = { UE4CodeGen_Private::EPropertyClass::Bool, "ReturnValue", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000580, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(Pickup_eventisActive_Parms), &Z_Construct_UFunction_APickup_isActive_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_APickup_isActive_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_APickup_isActive_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_isActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_isActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "isActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x14020401, sizeof(Pickup_eventisActive_Parms), Z_Construct_UFunction_APickup_isActive_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_APickup_isActive_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_isActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_isActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_isActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_isActive_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_OnRep_HitCount_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_OnRep_HitCount_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_OnRep_HitCount_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "OnRep_HitCount", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_OnRep_HitCount_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_OnRep_HitCount_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_OnRep_HitCount() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_OnRep_HitCount_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_OnRep_HitCountA_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_OnRep_HitCountA_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_OnRep_HitCountA_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "OnRep_HitCountA", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_OnRep_HitCountA_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_OnRep_HitCountA_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_OnRep_HitCountA() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_OnRep_HitCountA_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_OnRep_IsActive_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_OnRep_IsActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_OnRep_IsActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "OnRep_IsActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_OnRep_IsActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_OnRep_IsActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_OnRep_IsActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_OnRep_IsActive_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_OnRep_pickupDisplayText_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_OnRep_pickupDisplayText_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_OnRep_pickupDisplayText_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "OnRep_pickupDisplayText", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x00080400, 0, nullptr, 0, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_OnRep_pickupDisplayText_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_OnRep_pickupDisplayText_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_OnRep_pickupDisplayText() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_OnRep_pickupDisplayText_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_APickup_setActive_Statics { struct Pickup_eventsetActive_Parms { bool inState; }; static void NewProp_inState_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_inState; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; void Z_Construct_UFunction_APickup_setActive_Statics::NewProp_inState_SetBit(void* Obj) { ((Pickup_eventsetActive_Parms*)Obj)->inState = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_APickup_setActive_Statics::NewProp_inState = { UE4CodeGen_Private::EPropertyClass::Bool, "inState", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0010000000000080, 1, nullptr, sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(Pickup_eventsetActive_Parms), &Z_Construct_UFunction_APickup_setActive_Statics::NewProp_inState_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_APickup_setActive_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_APickup_setActive_Statics::NewProp_inState, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_APickup_setActive_Statics::Function_MetaDataParams[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_APickup_setActive_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_APickup, "setActive", RF_Public|RF_Transient|RF_MarkAsNative, nullptr, (EFunctionFlags)0x04020401, sizeof(Pickup_eventsetActive_Parms), Z_Construct_UFunction_APickup_setActive_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UFunction_APickup_setActive_Statics::PropPointers), 0, 0, METADATA_PARAMS(Z_Construct_UFunction_APickup_setActive_Statics::Function_MetaDataParams, ARRAY_COUNT(Z_Construct_UFunction_APickup_setActive_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_APickup_setActive() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_APickup_setActive_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_APickup_NoRegister() { return APickup::StaticClass(); } struct Z_Construct_UClass_APickup_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bIsActive_MetaData[]; #endif static void NewProp_bIsActive_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_bIsActive; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_name_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_name; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_HitCountA_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_HitCountA; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_HitCount_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_HitCount; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pickupDisplayText_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_pickupDisplayText; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_pickupName_MetaData[]; #endif static const UE4CodeGen_Private::FStrPropertyParams NewProp_pickupName; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_APickup_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AStaticMeshActor, (UObject* (*)())Z_Construct_UPackage__Script_MyProject, }; const FClassFunctionLinkInfo Z_Construct_UClass_APickup_Statics::FuncInfo[] = { { &Z_Construct_UFunction_APickup_addHitCount, "addHitCount" }, // 2991156564 { &Z_Construct_UFunction_APickup_checkIsPlayerHit, "checkIsPlayerHit" }, // 2411925270 { &Z_Construct_UFunction_APickup_getHitCount, "getHitCount" }, // 3175219966 { &Z_Construct_UFunction_APickup_isActive, "isActive" }, // 269850264 { &Z_Construct_UFunction_APickup_OnRep_HitCount, "OnRep_HitCount" }, // 3053454041 { &Z_Construct_UFunction_APickup_OnRep_HitCountA, "OnRep_HitCountA" }, // 2917935224 { &Z_Construct_UFunction_APickup_OnRep_IsActive, "OnRep_IsActive" }, // 1050222429 { &Z_Construct_UFunction_APickup_OnRep_pickupDisplayText, "OnRep_pickupDisplayText" }, // 3802865813 { &Z_Construct_UFunction_APickup_setActive, "setActive" }, // 612066414 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_APickup_Statics::Class_MetaDataParams[] = { { "HideCategories", "Input" }, { "IncludePath", "Pickup.h" }, { "ModuleRelativePath", "Pickup.h" }, { "ShowCategories", "Input|MouseInput Input|TouchInput" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_APickup_Statics::NewProp_bIsActive_MetaData[] = { { "ModuleRelativePath", "Pickup.h" }, }; #endif void Z_Construct_UClass_APickup_Statics::NewProp_bIsActive_SetBit(void* Obj) { ((APickup*)Obj)->bIsActive = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UClass_APickup_Statics::NewProp_bIsActive = { UE4CodeGen_Private::EPropertyClass::Bool, "bIsActive", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000020, 1, "OnRep_IsActive", sizeof(bool), UE4CodeGen_Private::ENativeBool::Native, sizeof(APickup), &Z_Construct_UClass_APickup_Statics::NewProp_bIsActive_SetBit, METADATA_PARAMS(Z_Construct_UClass_APickup_Statics::NewProp_bIsActive_MetaData, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::NewProp_bIsActive_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_APickup_Statics::NewProp_name_MetaData[] = { { "Category", "basic property" }, { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_APickup_Statics::NewProp_name = { UE4CodeGen_Private::EPropertyClass::Str, "name", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000005, 1, nullptr, STRUCT_OFFSET(APickup, name), METADATA_PARAMS(Z_Construct_UClass_APickup_Statics::NewProp_name_MetaData, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::NewProp_name_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_APickup_Statics::NewProp_HitCountA_MetaData[] = { { "Category", "basic property" }, { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_APickup_Statics::NewProp_HitCountA = { UE4CodeGen_Private::EPropertyClass::Float, "HitCountA", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000025, 1, "OnRep_HitCountA", STRUCT_OFFSET(APickup, HitCountA), METADATA_PARAMS(Z_Construct_UClass_APickup_Statics::NewProp_HitCountA_MetaData, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::NewProp_HitCountA_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_APickup_Statics::NewProp_HitCount_MetaData[] = { { "Category", "basic property" }, { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_APickup_Statics::NewProp_HitCount = { UE4CodeGen_Private::EPropertyClass::Float, "HitCount", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000025, 1, "OnRep_HitCount", STRUCT_OFFSET(APickup, HitCount), METADATA_PARAMS(Z_Construct_UClass_APickup_Statics::NewProp_HitCount_MetaData, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::NewProp_HitCount_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_APickup_Statics::NewProp_pickupDisplayText_MetaData[] = { { "Category", "basic property" }, { "ModuleRelativePath", "Pickup.h" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_APickup_Statics::NewProp_pickupDisplayText = { UE4CodeGen_Private::EPropertyClass::Str, "pickupDisplayText", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080100000025, 1, "OnRep_pickupDisplayText", STRUCT_OFFSET(APickup, pickupDisplayText), METADATA_PARAMS(Z_Construct_UClass_APickup_Statics::NewProp_pickupDisplayText_MetaData, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::NewProp_pickupDisplayText_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_APickup_Statics::NewProp_pickupName_MetaData[] = { { "Category", "basic property" }, { "ModuleRelativePath", "Pickup.h" }, { "ToolTip", "properties" }, }; #endif const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UClass_APickup_Statics::NewProp_pickupName = { UE4CodeGen_Private::EPropertyClass::Str, "pickupName", RF_Public|RF_Transient|RF_MarkAsNative, (EPropertyFlags)0x0020080000000005, 1, nullptr, STRUCT_OFFSET(APickup, pickupName), METADATA_PARAMS(Z_Construct_UClass_APickup_Statics::NewProp_pickupName_MetaData, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::NewProp_pickupName_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_APickup_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_APickup_Statics::NewProp_bIsActive, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_APickup_Statics::NewProp_name, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_APickup_Statics::NewProp_HitCountA, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_APickup_Statics::NewProp_HitCount, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_APickup_Statics::NewProp_pickupDisplayText, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_APickup_Statics::NewProp_pickupName, }; const FCppClassTypeInfoStatic Z_Construct_UClass_APickup_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<APickup>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_APickup_Statics::ClassParams = { &APickup::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x009000A0u, FuncInfo, ARRAY_COUNT(FuncInfo), Z_Construct_UClass_APickup_Statics::PropPointers, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::PropPointers), nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_APickup_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_APickup_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_APickup() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_APickup_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(APickup, 1841856936); static FCompiledInDefer Z_CompiledInDefer_UClass_APickup(Z_Construct_UClass_APickup, &APickup::StaticClass, TEXT("/Script/MyProject"), TEXT("APickup"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(APickup); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif <file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "MyProject/mesh001.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodemesh001() {} // Cross Module References MYPROJECT_API UClass* Z_Construct_UClass_Amesh001_NoRegister(); MYPROJECT_API UClass* Z_Construct_UClass_Amesh001(); ENGINE_API UClass* Z_Construct_UClass_AActor(); UPackage* Z_Construct_UPackage__Script_MyProject(); // End Cross Module References void Amesh001::StaticRegisterNativesAmesh001() { } UClass* Z_Construct_UClass_Amesh001_NoRegister() { return Amesh001::StaticClass(); } struct Z_Construct_UClass_Amesh001_Statics { static UObject* (*const DependentSingletons[])(); #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_Amesh001_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_AActor, (UObject* (*)())Z_Construct_UPackage__Script_MyProject, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_Amesh001_Statics::Class_MetaDataParams[] = { { "IncludePath", "mesh001.h" }, { "ModuleRelativePath", "mesh001.h" }, }; #endif const FCppClassTypeInfoStatic Z_Construct_UClass_Amesh001_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<Amesh001>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_Amesh001_Statics::ClassParams = { &Amesh001::StaticClass, DependentSingletons, ARRAY_COUNT(DependentSingletons), 0x009000A0u, nullptr, 0, nullptr, 0, nullptr, &StaticCppClassTypeInfo, nullptr, 0, METADATA_PARAMS(Z_Construct_UClass_Amesh001_Statics::Class_MetaDataParams, ARRAY_COUNT(Z_Construct_UClass_Amesh001_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_Amesh001() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_Amesh001_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(Amesh001, 677999597); static FCompiledInDefer Z_CompiledInDefer_UClass_Amesh001(Z_Construct_UClass_Amesh001, &Amesh001::StaticClass, TEXT("/Script/MyProject"), TEXT("Amesh001"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(Amesh001); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
f3376c06cf12367f2cb50ae2b1d1b41cdaef9e3e
[ "Text", "C++" ]
33
C++
bam1a/2097A2
4d19921bfc247acfa84234932161151cff464de5
256ce534d487c4ddceca2e45ffc158505dce8b73
refs/heads/master
<repo_name>etxpell/elvis<file_sep>/elvis_test.go // All material is licensed under the Apache License Version 2.0, January 2004 // http://www.apache.org/licenses/LICENSE-2.0 // go test -run none -bench . -benchtime 3s -benchmem // Tests to see how each algorithm compare. package main import ( "bytes" "testing" ) // Capture the time it takes to execute algorithm one. func BenchmarkAlgorithmOne(b *testing.B) { var output bytes.Buffer in := assembleInputStream() find := []byte("elvis") repl := []byte("Elvis") b.ResetTimer() for i := 0; i < b.N; i++ { output.Reset() algOne(in, find, repl, &output) } } // Capture the time it takes to execute algorithm two. func BenchmarkAlgorithmTwo(b *testing.B) { var output bytes.Buffer in := assembleInputStream() find := []byte("elvis") repl := []byte("Elvis") b.ResetTimer() for i := 0; i < b.N; i++ { output.Reset() algTwo(in, find, repl, &output) } } // Capture the time it takes to execute algorithm two. func BenchmarkAlgorithmThree(b *testing.B) { var output bytes.Buffer in := assembleInputStream() find := []byte("elvis") repl := []byte("Elvis") b.ResetTimer() for i := 0; i < b.N; i++ { output.Reset() algThree(in, find, repl, &output) } } func TestCheckAlgoThreeHappyCase(t *testing.T) { var output bytes.Buffer in := []byte("elvis") find := []byte("elvis") repl := []byte("Elvis") expected := []byte("Elvis") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got %s, expected %s", output.Bytes(), expected) } } func TestCheckAlgoThreeHappyCasePreBytes(t *testing.T) { var output bytes.Buffer in := []byte("aeelvis") find := []byte("elvis") repl := []byte("Elvis") expected := []byte("aeElvis") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got '%s', expected '%s'", output.Bytes(), expected) } } func TestCheckAlgoThreeHappyCasePostBytes(t *testing.T) { var output bytes.Buffer in := []byte("elvisae") find := []byte("elvis") repl := []byte("Elvis") expected := []byte("Elvisae") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got '%s', expected '%s'", output.Bytes(), expected) } } func TestCheckAlgoThreeHappyCaseNotFound(t *testing.T) { var output bytes.Buffer in := []byte("elxvisae") find := []byte("elvis") repl := []byte("Elvis") expected := []byte("elxvisae") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got '%s', expected '%s'", output.Bytes(), expected) } } func TestCheckAlgoThreeHappyCaseWholeReplUsed(t *testing.T) { var output bytes.Buffer in := []byte("elvisae") find := []byte("elvis") repl := []byte("ElviX") expected := []byte("ElviXae") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got '%s', expected '%s'", output.Bytes(), expected) } } func TestCheckAlgoThreeHappyCaseSameLetters(t *testing.T) { var output bytes.Buffer in := []byte("abcdepresleyab") find := []byte("presley") repl := []byte("Presley") expected := []byte("abcdePresleyab") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got '%s', expected '%s'", output.Bytes(), expected) } } func TestCheckAlgoThreeArrayOverRun(t *testing.T) { var output bytes.Buffer in := []byte("abcdepresley") find := []byte("presley") repl := []byte("Presley") expected := []byte("abcdePresley") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got '%s', expected '%s'", output.Bytes(), expected) } } func TestCheckAlgoThreeArrayUnderRun(t *testing.T) { var output bytes.Buffer in := []byte("velvis") find := []byte("elvis") repl := []byte("Elvis") expected := []byte("vElvis") algThree(in, find, repl, &output) if bytes.Compare(output.Bytes(), expected) != 0 { t.Errorf("got '%s', expected '%s'", output.Bytes(), expected) } }
ef53a38ec05ec0d2c8400c0b4d7c81e3a18cf462
[ "Go" ]
1
Go
etxpell/elvis
b6e5594652ac996e084899419ee594d8758a2371
baa9e08805c34e3266317183e342056b4424ca0c
refs/heads/master
<repo_name>Dee966/clothing<file_sep>/src/main/java/tech/yxing/clothing/pojo/vo/UserVo.java package tech.yxing.clothing.pojo.vo; import java.util.Date; public class UserVo { private String name; private String telephone; private String sex; private Date birthday; private String area; private String wechat; private String address; public UserVo(){ } public UserVo(String name, String telephone, String sex, Date birthday, String area, String wechat, String address) { this.name = name; this.telephone = telephone; this.sex = sex; this.birthday = birthday; this.area = area; this.wechat = wechat; this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public String getWechat() { return wechat; } public void setWechat(String wechat) { this.wechat = wechat; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "UserVo{" + "name='" + name + '\'' + ", telephone='" + telephone + '\'' + ", sex='" + sex + '\'' + ", birthday=" + birthday + ", area='" + area + '\'' + ", wechat='" + wechat + '\'' + ", address='" + address + '\'' + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/po/OrdersList.java package tech.yxing.clothing.pojo.po; import tech.yxing.clothing.pojo.vo.OrdersListVo; public class OrdersList { private Integer ordersListId; private String size; private Double price; private Integer quantities; private Double total; private String appraise; private Integer goodsId; private Integer orderId; private Integer userId; public OrdersList(){ } public OrdersList(OrdersListVo ordersListVo){ this.size = ordersListVo.getSize(); this.price = ordersListVo.getPrice(); this.quantities = ordersListVo.getQuantities(); this.total = ordersListVo.getPrice(); this.appraise = ordersListVo.getSize(); this.goodsId = ordersListVo.getGoodsId(); this.orderId = ordersListVo.getGoodsId(); this.userId = ordersListVo.getUserId(); } public OrdersList(Integer ordersListId, String size, Double price, Integer quantities, Double total, String appraise, Integer goodsId, Integer orderId, Integer userId) { this.ordersListId = ordersListId; this.size = size; this.price = price; this.quantities = quantities; this.total = total; this.appraise = appraise; this.goodsId = goodsId; this.orderId = orderId; this.userId = userId; } public Integer getOrdersListId() { return ordersListId; } public void setOrdersListId(Integer ordersListId) { this.ordersListId = ordersListId; } public String getSize() { return size; } public void setSize(String size) { this.size = size; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public Integer getQuantities() { return quantities; } public void setQuantities(Integer quantities) { this.quantities = quantities; } public Double getTotal() { return total; } public void setTotal(Double total) { this.total = total; } public String getAppraise() { return appraise; } public void setAppraise(String appraise) { this.appraise = appraise; } public Integer getGoodsId() { return goodsId; } public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Override public String toString() { return "OrdersList{" + "ordersListId=" + ordersListId + ", size='" + size + '\'' + ", price=" + price + ", quantities=" + quantities + ", total=" + total + ", appraise='" + appraise + '\'' + ", goodsId=" + goodsId + ", orderId=" + orderId + ", userId=" + userId + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/result/CodeMsg.java package tech.yxing.clothing.result; public class CodeMsg { private int code; private String msg; //通用模块错误码 public static CodeMsg SERVER_ERROR = new CodeMsg(500100, "服务端异常"); public static CodeMsg BIND_ERROR = new CodeMsg(500101, "参数校验异常:%s"); //用户模块模块错误码10 public static CodeMsg USER_INFO_INSERT_ERROR = new CodeMsg(10101,"信息添加失败,系统错误..."); public static CodeMsg USERNAME_NOT_EXIST = new CodeMsg(10102,"用户名不存在"); public static CodeMsg PASSWORD_ERROR = new CodeMsg(10103,"密码错误"); public static CodeMsg USER_EXIST = new CodeMsg(10104,"用户名已存在,请重新注册。"); public static CodeMsg NOT_YET_LOGIN = new CodeMsg(10106,"未登录或登录失效,请先进行登录"); //商品模块模块错误码20 public static CodeMsg SEARCH_GOODS_NULL = new CodeMsg(20101,"找不到相关商品!"); public static CodeMsg ROTATION_NULL = new CodeMsg(20102,"找不到任何轮播图!"); public static CodeMsg GOODS_NULL = new CodeMsg(20103,"找不到任何商品!"); public static CodeMsg TYPE_GOODS_NULL = new CodeMsg(20104,"找不到该分类的任何商品!"); //购物车模块错误码30 public static CodeMsg CART_NULL = new CodeMsg(30101,"购物车没有任何商品,快去选购吧!"); public static CodeMsg CART_ORDER_ERROR = new CodeMsg(30102,"下单失败,系统错误..."); //订单模块错误码40 public static CodeMsg ORDER_ERROR = new CodeMsg(40101,"下单失败,系统错误..."); public static CodeMsg STATE_ORDER_NULL = new CodeMsg(40102,"没有符合条件的订单。"); public static CodeMsg ORDER_NULL = new CodeMsg(40103,"找不到任何订单。"); public static CodeMsg GET_STATE_ORDER_ERROR = new CodeMsg(40104,"查询失败,系统错误..."); private CodeMsg() { } private CodeMsg(int code, String msg) { this.code = code; this.msg = msg; } //可以返回带参数的校验码 public CodeMsg fillArgs(Object... args) { int code = this.code; String message = String.format(this.msg, args); return new CodeMsg(code, message); } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return "CodeMsg{" + "code=" + code + ", msg='" + msg + '\'' + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/dto/GoodsDto.java package tech.yxing.clothing.pojo.dto; import tech.yxing.clothing.pojo.po.Goods; import java.util.List; public class GoodsDto { private List<Goods> goodsList; public GoodsDto(){} public GoodsDto(List<Goods> goodsList) { this.goodsList = goodsList; } public List<Goods> getGoodsList() { return goodsList; } public void setGoodsList(List<Goods> goodsList) { this.goodsList = goodsList; } @Override public String toString() { return "GoodsDto{" + "goodsList=" + goodsList + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/vo/RotationVo.java package tech.yxing.clothing.pojo.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @Author Joe * @Date */ @ApiModel(value = "RotationVo", description = "轮播图数据结构") public class RotationVo { @ApiModelProperty(value = "轮播图地址", name = "imge") private String imge; @ApiModelProperty(value = "操作管理员id", name = "managerId") private Integer managerId; @ApiModelProperty(value = "商品id", name = "goodsID") private Integer goodsID; public RotationVo() { } public RotationVo(String imge, Integer managerId, Integer goodsID) { this.imge = imge; this.managerId = managerId; this.goodsID = goodsID; } public String getImge() { return imge; } public void setImge(String imge) { this.imge = imge; } public Integer getManagerId() { return managerId; } public void setManagerId(Integer managerId) { this.managerId = managerId; } public Integer getGoodsID() { return goodsID; } public void setGoodsID(Integer goodsID) { this.goodsID = goodsID; } @Override public String toString() { return "RotationVo{" + "imge='" + imge + '\'' + ", managerId=" + managerId + ", goodsID=" + goodsID + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.focustar</groupId> <artifactId>air_cinema</artifactId> <version>0.0.1</version> <name>air_cinema</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency> <dependency> <groupId>io.undertow</groupId> <artifactId>undertow-core</artifactId> <version>2.0.27.Final</version> </dependency> <dependency> <groupId>io.undertow</groupId> <artifactId>undertow-servlet</artifactId> <version>2.0.27.Final</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- <dependency>--> <!-- <groupId>org.springframework.boot</groupId>--> <!-- <artifactId>spring-boot-starter-validation</artifactId>--> <!-- </dependency>--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.0.16.Final</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> <exclusions> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> </exclusion> <exclusion> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-annotations</artifactId> <version>1.5.21</version> </dependency> <dependency> <groupId>io.swagger</groupId> <artifactId>swagger-models</artifactId> <version>1.5.21</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.3.2</version> </dependency> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.2.0</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.5</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.40</version> </dependency> <!-- https://mvnrepository.com/artifact/tk.mybatis/mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper</artifactId> <version>4.1.5</version> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>2.1.5</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.16</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <groupId>net.sf.dozer</groupId> <artifactId>dozer</artifactId> <version>5.5.1</version> </dependency> <dependency> <groupId>javax.persistence</groupId> <artifactId>persistence-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>com.github.dozermapper</groupId> <artifactId>dozer-core</artifactId> <version>6.2.0</version> </dependency> <!-- <dependency>--> <!-- <groupId>org.flywaydb</groupId>--> <!-- <artifactId>flyway-core</artifactId>--> <!-- <version>6.0.8</version>--> <!-- </dependency>--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> <!-- https://mvnrepository.com/artifact/jdom/jdom --> <dependency> <groupId>jdom</groupId> <artifactId>jdom</artifactId> <version>1.1</version> </dependency> <!-- IssuerTcpCmdMessage 播放服务jar包 --> <dependency> <groupId>cinema</groupId> <artifactId>IssuerTcpCmdMessage</artifactId> <version>1.0</version> <scope>system</scope> <systemPath>${basedir}/src/main/resources/lib/IssuerTcpCmdMessage.jar</systemPath> </dependency> </dependencies> <build> <finalName>air_cinema</finalName> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <includeSystemScope>true</includeSystemScope> </configuration> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> <!-- 指定JDK编译版本 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <!--根据你把lib放的位置--> <compilerArguments> <extdirs>${basedir}/src/main/resources/lib</extdirs> </compilerArguments> </configuration> </plugin> </plugins> </build> </project> <file_sep>/src/main/java/tech/yxing/clothing/controller/LoginController.java package tech.yxing.clothing.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.ibatis.annotations.Param; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import tech.yxing.clothing.exception.GlobleException; import tech.yxing.clothing.pojo.vo.LoginVo; import tech.yxing.clothing.pojo.vo.TokenId; import tech.yxing.clothing.result.CodeMsg; import tech.yxing.clothing.result.Result; import tech.yxing.clothing.service.UserService; import tech.yxing.clothing.utils.JwtUtils; import java.io.UnsupportedEncodingException; /** * @Author Joe * @Date 2019-12-26 10:07 */ @Api(tags = "用户端-登录服务接口列表") @RestController @RequestMapping("/login") public class LoginController { @Autowired private UserService userService; /** * @methodDesc: 用户登录 * @Param: username.password * @return: Result<> * @Author: xiaoman */ @ApiOperation(value = "用户登录", notes = "用户端-用户登录") @PostMapping("/user_login") public Result<TokenId> userLogin(@RequestBody LoginVo loginVo){ System.out.println(loginVo.toString()); // LoginVo loginVo = new LoginVo(username,password); return Result.success(userService.userLogin(loginVo)); } /** * @methodDesc: 用户注册 * @Param: <PASSWORD>.password * @return: Result<> userId * @Author: xiaoman */ @ApiOperation(value = "用户注册", notes = "用户端-用户注册") @PostMapping("/user_register") public Result<Integer> managerLogin(@RequestBody LoginVo loginVo){ return Result.success(userService.userRegister(loginVo)); } /** * @methodDesc: 用户登录 测试接口 * @Param: username.password * @return: Result<> * @Author: xiaoman */ @ApiOperation(value = "用户登录-测试", notes = "用户端-用户登录-测试") @PostMapping("/test_login") public Result<String> userLoginTest(@RequestBody LoginVo loginVo) throws UnsupportedEncodingException { // //获取当前用户 // Subject subject = SecurityUtils.getSubject(); // //封装用户的登录数据 // UsernamePasswordToken token = new UsernamePasswordToken(loginVo.getUsername(),loginVo.getPassword()); // try { // subject.login(token);//执行登录方法,如果没有异常就说明ok了 // //生成返回的token //// JwtUtils jwtUtils = new JwtUtils(); //// String jwtToken = jwtUtils.refreshToken(loginVo.getUsername()); // return Result.success(token.toString()); // } catch (UnknownAccountException e) { // throw new GlobleException(CodeMsg.USERNAME_NOT_EXIST); // } catch (IncorrectCredentialsException e){ // throw new GlobleException(CodeMsg.PASSWORD_ERROR); // } JwtUtils jwtUtils = new JwtUtils(); String token = jwtUtils.sign(loginVo); return Result.success(token); } } <file_sep>/src/main/java/tech/yxing/clothing/swagger/MvcConfiguration.java package tech.yxing.clothing.swagger; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.util.List; /** * @Author Hoki(谭鸿兴) * @Date 2019/11/13 14:45 */ @Configuration public class MvcConfiguration extends WebMvcConfigurationSupport { @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); super.addResourceHandlers(registry); } } <file_sep>/src/main/java/tech/yxing/clothing/service/CartService.java package tech.yxing.clothing.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tech.yxing.clothing.dao.CartDao; import tech.yxing.clothing.dao.GoodsDao; import tech.yxing.clothing.dao.OrdersDao; import tech.yxing.clothing.dao.UserDao; import tech.yxing.clothing.exception.GlobleException; import tech.yxing.clothing.pojo.dto.CartAndGoodsDto; import tech.yxing.clothing.pojo.po.*; import tech.yxing.clothing.pojo.vo.CartVo; import tech.yxing.clothing.result.CodeMsg; import java.util.Date; import java.util.List; @Service public class CartService { @Autowired private CartDao cartDao; @Autowired private UserDao userDao; @Autowired private OrdersDao ordersDao; @Autowired private GoodsDao goodsDao; /** * @methodDesc: 商品加入购物车 * @Param: cartVo * @return: * @Author: Joe */ public void cartInsert(CartVo cartVo){ double total = cartVo.getPrice() * cartVo.getQuantities(); cartDao.cartInsert(new ShoppingCart(total,cartVo)); } /** * @methodDesc: 查询所有购物车 * @Param: userId * @return: List<ShoppingCart> * @Author: Joe */ public List<CartAndGoodsDto> cartShow(int userId){ // List<CartDto> cartDtos = new ArrayList<>(); // List<ShoppingCart> shoppingCarts = cartDao.cartShow(userId); //shoppingCarts为空 // if (shoppingCarts.isEmpty()){ // throw new GlobleException(CodeMsg.CART_NULL); // } // //不为空 // for (ShoppingCart shoppingCart : shoppingCarts) { // Goods goods = goodsDao.goodsShow(shoppingCart.getGoodsId()); // CartDto cartDto = new CartDto( // goods.getName(), // goods.getImge(), // shoppingCart.getSize(), // shoppingCart.getPrice(), // shoppingCart.getQuantities(), // shoppingCart.getTotal(), // shoppingCart.getCartId(), // goods.getGoodsId() // ); // cartDtos.add(cartDto); // } // return cartDtos; List<CartAndGoodsDto> cartAndGoodsDtos = cartDao.getCartAndGoods(userId); if (cartAndGoodsDtos.isEmpty()){ throw new GlobleException(CodeMsg.CART_NULL); } return cartAndGoodsDtos; } /** * @methodDesc: 用cartId删除购物车 * @Param: cartId * @return: * @Author: Joe */ public void cartDelete(int cartId){ cartDao.cartDelete(cartId); } /** * @methodDesc: 用购物车下单 * @Param: shoppingCart * @return: * @Author: Joe */ public Orders cartOrder(List<ShoppingCart> shoppingCartList){ Double total = 0.0; //1.用shoppingCart里的userId把用户信息查出来 User user = userDao.showInfo(shoppingCartList.get(0).getUserId()); for (int i = 0;i < shoppingCartList.size();i++) { total = total + shoppingCartList.get(i).getTotal(); } //把数据写入订单 Orders orders = new Orders( null, new Date(), total, 0, user.getName(), user.getAddress(), user.getTelephone(), user.getUserId() ); ordersDao.insertOrder(orders); //2.在orders_log里记录下单时间 ordersDao.markOrderTime(orders.getOrderTime(),orders.getOrderId()); //3.把订单写入订单列表 OrdersList ordersList = new OrdersList(); for (ShoppingCart shoppingCart : shoppingCartList) { ordersList.setSize(shoppingCart.getSize()); ordersList.setPrice(shoppingCart.getPrice()); ordersList.setQuantities(shoppingCart.getQuantities()); ordersList.setTotal(shoppingCart.getTotal()); ordersList.setGoodsId(shoppingCart.getGoodsId()); ordersList.setOrderId(orders.getOrderId()); ordersList.setUserId(user.getUserId()); ordersDao.insertOrderList(ordersList); //4.库存减去购买数量 goodsDao.reduceStock(shoppingCart.getGoodsId(),shoppingCart.getQuantities()); //5.减去该订单码数的数量 goodsDao.reduceSizeStock(shoppingCart.getSize(),shoppingCart.getQuantities(),shoppingCart.getGoodsId()); //6.删除已下单的购物车商品 cartDao.cartDelete(shoppingCart.getCartId()); } return orders; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/po/Rotation.java package tech.yxing.clothing.pojo.po; import tech.yxing.clothing.pojo.vo.RotationVo; //轮播图PO public class Rotation { private Integer rotationId;//轮播图id private String imge;//轮播图图片地址 private Integer goodsId;//商品id private Integer managerId;//上传该轮播图的管理员的id public Rotation() { } public Rotation(RotationVo rotationVo) { this.imge = rotationVo.getImge(); this.goodsId = rotationVo.getGoodsID(); this.managerId = rotationVo.getManagerId(); } public Rotation(Integer rotationId, String imge, Integer goodsId, Integer managerId) { this.rotationId = rotationId; this.imge = imge; this.goodsId = goodsId; this.managerId = managerId; } public Integer getRotationId() { return rotationId; } public void setRotationId(Integer rotationId) { this.rotationId = rotationId; } public String getImge() { return imge; } public void setImge(String imge) { this.imge = imge; } public Integer getGoodsId() { return goodsId; } public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; } public Integer getManagerId() { return managerId; } public void setManagerId(Integer managerId) { this.managerId = managerId; } @Override public String toString() { return "RotationVo{" + "rotationId=" + rotationId + ", imge='" + imge + '\'' + ", goodsId=" + goodsId + ", managerId=" + managerId + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/vo/ManagerVo.java package tech.yxing.clothing.pojo.vo; import java.util.Date; public class ManagerVo { private Integer managerId; private String name; private String sex; private String telephone; private Date workTime; public ManagerVo(){ } public ManagerVo(String name, String sex, String telephone, Date workTime) { this.name = name; this.sex = sex; this.telephone = telephone; this.workTime = workTime; } public Integer getManagerId() { return managerId; } public void setManagerId(Integer managerId) { this.managerId = managerId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public Date getWorkTime() { return workTime; } public void setWorkTime(Date workTime) { this.workTime = workTime; } @Override public String toString() { return "ManagerVo{" + "managerId=" + managerId + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", telephone='" + telephone + '\'' + ", workTime=" + workTime + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/service/ManagerService.java package tech.yxing.clothing.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tech.yxing.clothing.dao.ManagerDao; import tech.yxing.clothing.exception.GlobleException; import tech.yxing.clothing.myshiro.MyShiro; import tech.yxing.clothing.pojo.dto.GoodsSizeDto; import tech.yxing.clothing.pojo.po.Goods; import tech.yxing.clothing.pojo.po.GoodsSize; import tech.yxing.clothing.pojo.po.Manager; import tech.yxing.clothing.pojo.po.User; import tech.yxing.clothing.pojo.vo.LoginVo; import tech.yxing.clothing.pojo.vo.ManagerVo; import tech.yxing.clothing.pojo.vo.TokenId; import tech.yxing.clothing.result.CodeMsg; import java.util.Date; @Service public class ManagerService { @Autowired private ManagerDao managerDao; /** * @methodDesc: 管理员信息管理 修改信息 * @Param: managerVo * @return: managerVo * @Author: Joe */ public ManagerVo managerInfo(int managerId,ManagerVo managerVo){ managerDao.managerInfo(new Manager(managerId,managerVo)); Manager manager = managerDao.managerShow(managerVo.getManagerId()); ManagerVo managerVo1 = new ManagerVo(manager.getName(),manager.getSex(), manager.getTelephone(),manager.getWorkTime()); return managerVo1; } /** * @Param: managerId * @Return: Manager * @Author Joe * @Date */ public ManagerVo managerShow(int managerId){ Manager manager = managerDao.managerShow(managerId); ManagerVo managerVo = new ManagerVo(manager.getName(),manager.getSex(), manager.getTelephone(),manager.getWorkTime()); return managerVo; } /** * @Param: loginVo * @Return: Integer * @Author Joe * @Date */ public Integer managerRegister(LoginVo loginVo){ if (loginVo == null){ throw new GlobleException(CodeMsg.SERVER_ERROR); } String username = loginVo.getUsername(); String password = loginVo.getPassword(); System.out.println(username+"..."+password); //判断用户名是否已存在 Manager manager = managerDao.getByUsername(username); if (manager != null){ throw new GlobleException(CodeMsg.USER_EXIST); } Manager manager1 = new Manager(new LoginVo(username,password)); managerDao.managerRegister(manager1); return manager1.getManagerId(); } public TokenId managerLogin(LoginVo loginVo){ if (loginVo == null){ throw new GlobleException(CodeMsg.SERVER_ERROR); } String username = loginVo.getUsername(); String password = loginVo.getPassword(); //判断用户名是否存在 Manager manager = managerDao.getByUsername(username); if (manager == null){ throw new GlobleException(CodeMsg.USERNAME_NOT_EXIST); } //验证密码 String dBPassword = manager.getPassword(); String calcPassword = <PASSWORD>; if (!dBPassword.equals(calcPassword)){ throw new GlobleException(CodeMsg.PASSWORD_ERROR); } //生成token String token = MyShiro.createToken(loginVo); TokenId tokenId = new TokenId(token,manager.getManagerId()); return tokenId; } public Manager getManagerByUname(String username){ return managerDao.getByUsername(username); } public void editGoods(GoodsSizeDto goodsSizeDto){ int stock = 0; for (GoodsSize goodsSize : goodsSizeDto.getGoodsSizes()){ managerDao.editGoodsSize(goodsSize); stock = stock + goodsSize.getGoodsSizeStock(); } Goods goods = new Goods( goodsSizeDto.getGoodsId(), goodsSizeDto.getName(), goodsSizeDto.getPrice(), goodsSizeDto.getImge(), goodsSizeDto.getGoodDate(), goodsSizeDto.getDesc(), stock, goodsSizeDto.getGoodsTypeId() ); managerDao.editGoods(goods); } } <file_sep>/src/main/java/tech/yxing/clothing/dao/ManagerDao.java package tech.yxing.clothing.dao; import org.apache.ibatis.annotations.*; import org.springframework.stereotype.Repository; import tech.yxing.clothing.pojo.po.Goods; import tech.yxing.clothing.pojo.po.GoodsSize; import tech.yxing.clothing.pojo.po.Manager; @Mapper @Repository public interface ManagerDao { @Select("select * from manager where manager_id=#{managerId};") Manager managerShow(int managerId); @Update("update manager set " + "name=#{name},sex=#{sex},telephone=#{telephone},work_time=#{workTime} " + "where manager_id=#{managerId}") void managerInfo(Manager manager); @Select("select * from manager where username=#{username}") Manager getByUsername(String username); @Insert("insert into manager values(null,#{username},#{password},null,null,null,null)") @Options(useGeneratedKeys = true,keyProperty = "managerId",keyColumn = "manager_id") Integer managerRegister(Manager manager); @Update("update goods set `name`=#{name},price=#{price},`desc`=#{desc},stock=#{stock} where goods_id = #{goodsId}") void editGoods(Goods goods); @Update("update goods_size set goods_size_stock = #{goodsSizeStock} where goods_size_id = #{goodsSizeId}") void editGoodsSize(GoodsSize goodsSize); } <file_sep>/src/main/java/tech/yxing/clothing/rebbitmq/MQReceiver.java //package tech.yxing.clothing.rebbitmq; // //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import org.springframework.amqp.rabbit.annotation.RabbitListener; //import org.springframework.stereotype.Service; // //@Service //public class MQReceiver { // // private static Logger logger = LoggerFactory.getLogger(MQReceiver.class); // // @RabbitListener(queues = MQConfig.QUEUE) // public void receive(String massage){ // logger.info("receive message"+massage); // } // // @RabbitListener(queues=MQConfig.TOPIC_QUEUE1) // public void receiveTopic1(String message) { // logger.info(" topic queue1 message:"+message); // } // // @RabbitListener(queues = MQConfig.TOPIC_QUEUE2) // public void receiveTopic2(String message) { // logger.info(" topic queue2 message:" + message); // } // // @RabbitListener(queues = MQConfig.HEADER_QUEUE) // public void receiveHeaderQueue(byte[] message) { // logger.info(" header queue message:" + new String(message)); // } //} <file_sep>/src/main/java/tech/yxing/clothing/pojo/vo/ChangeStateVo.java package tech.yxing.clothing.pojo.vo; public class ChangeStateVo { private Integer managerId; private Integer orderId; public ChangeStateVo(){ } public ChangeStateVo(Integer managerId, Integer orderId) { this.managerId = managerId; this.orderId = orderId; } public Integer getManagerId() { return managerId; } public void setManagerId(Integer managerId) { this.managerId = managerId; } @Override public String toString() { return "ChangeStateVo{" + "managerId=" + managerId + ", orderId=" + orderId + '}'; } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/vo/LoginVo.java package tech.yxing.clothing.pojo.vo; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * @Author Hoki(谭鸿兴) * @Date 2019-12-25 22:19 */ @ApiModel(value = "LoginVo", description = "用户数据结构") public class LoginVo { @ApiModelProperty(value = "用户名", name = "name") private String username; @ApiModelProperty(value = "用户密码", name = "pword") private String password; public LoginVo() { } public LoginVo(String username, String password) { this.username = username; this.password = <PASSWORD>; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return <PASSWORD>; } public void setPassword(String password) { this.password = <PASSWORD>; } @Override public String toString() { return "LoginVo{" + "username='" + username + '\'' + ", password='" + <PASSWORD> + '\'' + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/po/Manager.java package tech.yxing.clothing.pojo.po; import tech.yxing.clothing.pojo.vo.LoginVo; import tech.yxing.clothing.pojo.vo.ManagerVo; import java.util.Date; public class Manager { private Integer managerId; private String username; private String password; private String name; private String sex; private String telephone; private Date workTime; public Manager(){ } public Manager(LoginVo loginVo){ this.username = loginVo.getUsername(); this.password = loginVo.getPassword(); } public Manager(int managerId,ManagerVo managerVo){ this.managerId = managerId; this.name = managerVo.getName(); this.sex = managerVo.getSex(); this.telephone = managerVo.getTelephone(); this.workTime = managerVo.getWorkTime(); } public Manager(Integer managerId, String username, String password, String name, String sex, String telephone, Date workTime) { this.managerId = managerId; this.username = username; this.password = <PASSWORD>; this.name = name; this.sex = sex; this.telephone = telephone; this.workTime = workTime; } public Integer getManagerId() { return managerId; } public void setManagerId(Integer managerId) { this.managerId = managerId; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public Date getWorkTime() { return workTime; } public void setWorkTime(Date workTime) { this.workTime = workTime; } @Override public String toString() { return "Manager{" + "managerId=" + managerId + ", username='" + username + '\'' + ", password='" + <PASSWORD> + '\'' + ", name='" + name + '\'' + ", sex='" + sex + '\'' + ", telephone='" + telephone + '\'' + ", workTime=" + workTime + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/pojo/po/Orders.java package tech.yxing.clothing.pojo.po; import java.util.Date; public class Orders { private Integer orderId; private Date orderTime; private Double total; private Integer state; private String name; private String address; private String telephone; private Integer userId; public Orders() { } public Orders(Integer orderId, Date orderTime, Double total, Integer state, String name, String address, String telephone, Integer userId) { this.orderId = orderId; this.orderTime = orderTime; this.total = total; this.state = state; this.name = name; this.address = address; this.telephone = telephone; this.userId = userId; } public Integer getOrderId() { return orderId; } public void setOrderId(Integer orderId) { this.orderId = orderId; } public Date getOrderTime() { return orderTime; } public void setOrderTime(Date orderTime) { this.orderTime = orderTime; } public double getTotal() { return total; } public void setTotal(double total) { this.total = total; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } @Override public String toString() { return "Orders{" + "orderId=" + orderId + ", orderTime=" + orderTime + ", total=" + total + ", state=" + state + ", name='" + name + '\'' + ", address='" + address + '\'' + ", telephone='" + telephone + '\'' + ", userId=" + userId + '}'; } } <file_sep>/src/main/java/tech/yxing/clothing/service/UserService.java package tech.yxing.clothing.service; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import tech.yxing.clothing.dao.UserDao; import tech.yxing.clothing.exception.GlobleException; import tech.yxing.clothing.myshiro.MyShiro; import tech.yxing.clothing.pojo.po.User; import tech.yxing.clothing.pojo.vo.LoginVo; import tech.yxing.clothing.pojo.vo.PagesVo; import tech.yxing.clothing.pojo.vo.TokenId; import tech.yxing.clothing.pojo.vo.UserVo; //import tech.yxing.clothing.redis.RedisService; import tech.yxing.clothing.redis.UserKey; import tech.yxing.clothing.result.CodeMsg; import tech.yxing.clothing.result.Result; import java.util.List; @Service public class UserService { @Autowired private UserDao userDao; // @Autowired // private RedisService redisService; /** * @methodDesc: 用户登录 * @Param: loginVo * @return: String * @Author: Joe */ public TokenId userLogin(LoginVo loginVo){ if (loginVo == null){ throw new GlobleException(CodeMsg.SERVER_ERROR); } String username = loginVo.getUsername(); String password = loginVo.getPassword(); //判断用户名是否存在 User user = userDao.getByUsername(username); if (user == null){ throw new GlobleException(CodeMsg.USERNAME_NOT_EXIST); } //验证密码 String dBPassword = user.getPassword(); String calcPassword = password; if (!dBPassword.equals(calcPassword)){ throw new GlobleException(CodeMsg.PASSWORD_ERROR); } //生成token String token = MyShiro.createToken(loginVo); Integer userId = user.getUserId(); TokenId tokenId = new TokenId(token,userId); return tokenId; } /** * @methodDesc: 用户注册 * @Param: loginVo * @return: int * @Author: Joe */ public int userRegister(LoginVo loginVo){ if (loginVo == null){ throw new GlobleException(CodeMsg.SERVER_ERROR); } String username = loginVo.getUsername(); String password = loginVo.getPassword(); //判断用户名是否已存在 User user = userDao.getByUsername(username); if (user != null){ throw new GlobleException(CodeMsg.USER_EXIST); } User user1 = new User(new LoginVo(username,password)); userDao.registerUser(user1); return user1.getUserId(); } /** * @methodDesc: 用户信息管理 * @Param: userVo * @return: Result<UserVo> * @Author: Joe */ public UserVo insertUserInfo(int userId,UserVo userVo){ try { userDao.insertUserInfo(new User(userId,userVo)); User user = userDao.showInfo(userId); UserVo userVo1 = new UserVo(user.getName(),user.getTelephone(),user.getSex(), user.getBirthday(),user.getArea(),user.getWechat(),user.getAddress()); return userVo1; } catch (Exception e){ throw new GlobleException(CodeMsg.USER_INFO_INSERT_ERROR); } } /** * @methodDesc: 查询用户信息 * @Param: userId * @return: Result<User> * @Author: Joe */ public UserVo getUserInfo(int userId){ //缓存中取用户对象 // User user = redisService.get(UserKey.infoById, ""+userId, User.class); // if (user != null){ // return new UserVo(user.getName(),user.getTelephone(),user.getSex(), // user.getBirthday(),user.getArea(),user.getWechat(),user.getAddress()); // } //走数据库 User user = userDao.showInfo(userId); // if (user != null){ // redisService.set(UserKey.infoById, ""+user.getUserId(), user); // } return new UserVo(user.getName(),user.getTelephone(),user.getSex(), user.getBirthday(),user.getArea(),user.getWechat(),user.getAddress()); } /** * @methodDesc: 查询用户余额 * @Param: userId * @return: Double * @Author: Joe */ public Double getBalance(int userId){ User user = userDao.showInfo(userId); //取缓存 // String balance1 = redisService.get(UserKey.balanceById, ""+user.getUserId(), String.class); // if (balance1 != null){ // return Double.parseDouble(balance1); // } //缓存中没有再走数据库 Double balance = user.getBalance(); // String yue = String.valueOf(balance); // if (balance != null){ // redisService.set(UserKey.balanceById, "" + user.getUserId(), yue); // } return balance; } /** * @methodDesc: 用用户名查询密码 * @Param: username * @return: String * @Author: Joe */ public User getUserByUname(String username){ User user = userDao.getUserByUname(username); return user; } public void delUser(int userId){ userDao.delUser(userId); } public PageInfo<User> listUser(PagesVo pagesVo){ // 1.设置分页 PageHelper.startPage(pagesVo.getPage(), pagesVo.getPageSize()); // 2.执行查询 List<User> users = userDao.listUser(); // 3.获取详细分页信息 PageInfo<User> pageInfo = new PageInfo<>(users); System.out.println(pageInfo.toString()); return pageInfo; } }
9209d7693c60e840cf8cbb4b9667fa99e5595de2
[ "Java", "Maven POM" ]
19
Java
Dee966/clothing
b65d2f91c85d2ca6dffc5e7fed82f7e961f41a7f
a16d3f62e9a9814a8874afdc75d6e52eb5143f39
refs/heads/master
<file_sep># Práctica 5 de Programación 1 ## Escuela de Ingeniería y Arquitectura. Universidad de Zaragoza Datos y código fuente de partida para la 5ª práctica de Programación 1. Puede clonarse o descargarse en formato ZIP y abrirse en CodeLite, seleccionando el fichero ``practica5.workspace``. Los ficheros de la carpeta ``datos`` proceden del [portal de datos abiertos del Ayuntamiento de Zaragoza](https://www.zaragoza.es/sede/portal/datos-abiertos/) y son relativos a los [usos del sistema Bizi Zaragoza](https://www.zaragoza.es/sede/servicio/catalogo/70\#CSV). * El fichero [`Usos Oct16-Mar17 1.csv`](http://www.zaragoza.es/contenidos/bici/UsosOct16-Mar17csv.zip) se encuentra disponible con un nombre simplificado (``usos-16.csv``) en la carpeta ``datos`` de este repositorio, comprimido también en formato ZIP debido a su tamaño. El contenido del fichero de este repositorio de la práctica ha sido modificado para eliminar una línea en la que faltaba el identificador del usuario y los datos de recogida. * El fichero [`UsosMar17_Ago17.csv](http://www.zaragoza.es/contenidos/bici/UsosMar17_Ago17.zip) se encuentra también disponible con un nombre simplificado (``usos-17.csv``) en la carpeta ``datos`` del repositorio de la práctica, comprimido también en formato ZIP debido a su tamaño. <file_sep>/********************************************************************************\ * Programación 1. Práctica 5 * Autores: <NAME> * Ultima revisión: 26 de noviembre de 2018 * Resumen: Fichero de interfaz «bizi-usos.h» de un módulo para trabajar con * registros que representan usos del sistema Bizi Zaragoza. * Codificación de caracteres original de este fichero: UTF-8 con BOM \********************************************************************************/ #ifndef BIZI_USOS_H_INCLUDED #define BIZI_USOS_H_INCLUDED #include <istream> using namespace std; /* * Longitud máxima de la línea de cabecera de los ficheros de usos. */ const int MAX_LONG_LINEA = 250; struct UsoBizi { // Define los campos necesarios para representar los siguientes datos de un // uso del sistema Bizi: el identificador del usuario que utiliza la // bicicleta, el código de la estación de la que se retira la bicicleta y el // código de la estación en la que se devuelve. }; /* * Pre: El flujo «f» está asociado con un fichero de texto con el formato de usos * del sistema Bizi establecido en el enunciado y en disposición de * leer desde el principio de una línea distinta a la de la cabecera. * Post: Ha intentado leer la línea mencionada en la precondición y, si no se han * terminado los datos del fichero en dicho intento, ha almacenado en los * campos del parámetro «uso» el identificador del usuario al que * corresponde la utilización de la línea leída y los códigos de las * estaciones de retira y devolución de la bicicleta. */ void leerUso(istream& f, UsoBizi& uso); /* * Pre: La cadena de caracteres «rutaFichero» respresenta la ruta de acceso y el * nombre de un fichero de texto con el formato de usos del sistema Bizi * establecido en el enunciado. * Post: Si el fichero de nombre «rutaFichero» se ha podido abrir y leer * correctamente, la función ha devuelto «true», «traslados» es el número de * usos entre estaciones distintas del sistema Bizi Zaragoza contenidos en * el fichero de nombre «rutaFichero» y «usosCirculares» es el número de * usos contenidos en dicho fichero que tienen como origen y destino la * misma estación. En caso contrario, la función ha devuelto «false». */ bool contarUsos(const char rutaFichero[], int& traslados, int& usosCirculares); #endif // BIZI_USOS_H_INCLUDED <file_sep>/********************************************************************************\ * Programación 1. Práctica 5 * Autores: <NAME> * Ultima revisión: 27 de noviembre de 2018 * Resumen: Fichero de interfaz «usuario-bizi.h» de un módulo para trabajar con * registros que permiten contabilizar el número de usos que cada usuario * hace del sistema Bizi. * Codificación de caracteres original de este fichero: UTF-8 con BOM \********************************************************************************/ #ifndef USUARIO_BIZI_H #define USUARIO_BIZI_H struct UsuarioBizi { // Define los campos necesarios para representar los siguientes datos de un // usuario del sistema Bizi: su identificador de usuario, el número de usos // entre estaciones distintas realizadas por ese usuario y el número de usos // entre la misma estación. }; /* * Pre: --- * Post: Ha devuelto el número total de usos del sistema Bizi * correspondiente a «usuario». */ int numUsosTotales(const UsuarioBizi usuario); /* * Pre: usuario1 = X y usuario2 = Y * Post: usuario1 = Y y usuario2 = X */ void intercambiar(UsuarioBizi& usuario1, UsuarioBizi& usuario2); /* * Pre: --- * Post: Ha escrito una línea en la pantalla que contiene la información del * registro «usuario» (identificador, número de usos entre estaciones * distintas, número de usos entre la misma estación y número de usos * totales), escrita en ese orden y utilizando un mínimo de 10 caracteres. */ void mostrar(const UsuarioBizi usuario); #endif <file_sep>/********************************************************************************* * Programación 1. Práctica 5 * Autor: <NAME> * Ultima revisión: 27 de noviembre de 2019 * Resumen: Fichero de interfaz «pedir-nombre-fichero-h» de un módulo que declara * una función denominada «pedirNombreFichero» que facilita la labor de * convertir el nombre de un fichero solicitado al usuario en una ruta de * acceso relativa al directorio de ejecución del proyecto solicitado * en esta tarea y en la siguiente. * Codificación de caracteres original de este fichero: UTF-8 sin BOM \********************************************************************************/ #ifndef PEDIR_NOMBRE_FICHERO_H_INCLUDED #define PEDIR_NOMBRE_FICHERO_H_INCLUDED const int MAX_LONG_NOMBRE_FICHERO = 200; const char RUTA_RELATIVA[] = "../../datos/"; /* * Pre: «nombreRelativo» una dimensión suficiente como para albergar una ruta * relativa a un fichero cuyo nombre escriba el usuario. * Post: Ha solicitado al usuario el nombre de un fichero de usos del sistema * Bizi, lo ha leído de teclado y ha asignado a «nombreRelativo» una ruta * de acceso relativa al mismo, constente en la concatenación de la cadena * «RUTA_RELATIVA» y el nombre de fichero leído de teclado. */ void pedirNombreFichero(char nombreRelativo[]); #endif // PEDIR_NOMBRE_FICHERO_H_INCLUDED
fc56970a9462385096c8c1e0f76075a2b4c789dd
[ "Markdown", "C", "C++" ]
4
Markdown
prog1-eina-2019-20/practica5
9ca8492b043c3494906f0de184237b51905e4728
35e33d442631eeb22217521ed80e082f5ffa0fae
refs/heads/master
<repo_name>pathrl/Worms<file_sep>/src/controllers/wormUpdate.js let wormObject; self.onmessage = function(msg) { wormObject = msg.data; // temp temporizador = setTimeout('update()',30); } function update() { // move worm wormObject.rotZ += (Math.random() - 0.5) * 0.7; // wormObject.velocity += Math.round((Math.random() - 0.5) * 4); wormObject.posX += Math.cos(wormObject.rotZ) * wormObject.velocity; wormObject.posY += Math.sin(wormObject.rotZ) * wormObject.velocity; wormObject.color.red += Math.round((Math.random() - 0.5) * 4); wormObject.color.blue += Math.round((Math.random() - 0.5) * 4); wormObject.green += Math.round((Math.random() - 0.5) * 4); // wormObject.size += Math.round((Math.random() - 0.5) * 4); /* if(wormObject.velocity <= 0) wormObject.velocity = 1; if(wormObject.velocity > wormObject.size) wormObject.velocity = wormObject.size; if(wormObject.size <= 0) wormObject.size = 1; if(wormObject.size > 10) wormObject.size = 10; */ // check Colision if (wormObject.posX < 0) { wormObject.rotZ += Math.PI; wormObject.posX = 1; } else if (wormObject.posX > 512) { wormObject.rotZ += Math.PI; wormObject.posX = 511; } if (wormObject.posY < 0) { wormObject.rotZ += Math.PI; wormObject.posY = 1; } else if (wormObject.posY > 512) { wormObject.rotZ += Math.PI; wormObject.posY = 511; } // Send update worm postMessage(wormObject); // temp clearTimeout(temporizador); temporizador = setTimeout('update()',30); } <file_sep>/src/logic/Worm.js var Worm = class { constructor(posX, posY, rotZ, color){ this.posX = posX; this.posY = posY; this.rotZ = rotZ; this.color = color; this.size = 10; this.velocity = 1; } drawWorm() { context.fillStyle = "rgb("+this.color.red+","+this.color.green+","+this.color.blue+")"; context.fillRect(this.posX, this.posX, this.size, this.size); } moveWorm() { this.rotZ += (Math.random() - 0.5) * 0.1; this.posX += Math.cos(this.rotZ) * this.velocity; this.posY += Math.sin(this.rotZ) * this.velocity; } checkColision() { if (this.posX < 0) { this.rotZ += Math.PI; this.posX = 1; } else if (this.posX > 512) { this.rotZ += Math.PI; this.posX = 511; } if (this.posY < 0) { this.rotZ += Math.PI; this.posY = 1; } else if (this.posY > 512) { this.rotZ += Math.PI; this.posY = 511; } } }
c821e86cd8f285d231e59b9a8cc95d67ef2f0132
[ "JavaScript" ]
2
JavaScript
pathrl/Worms
f7cf246435aedd1358e1acbb37940d81dcdc1421
b28149797964c170285628604d78773320698215
refs/heads/master
<file_sep>// // ViewController.swift // Spring Animation App // // Created by Igor on 21.09.2021. // import Spring class ViewController: UIViewController { // MARK: - IBOutlets @IBOutlet var animatedView: SpringView! @IBOutlet var animationInfoLabel: UILabel! { didSet { animationInfoLabel.textColor = .white animationInfoLabel.adjustsFontSizeToFitWidth = true animationInfoLabel.minimumScaleFactor = 0.5 } } @IBOutlet var runAnimateButton: SpringButton! // MARK: - Private properties private var animations = Animation.getAnimations().shuffled() private var animationCount = 0 // MARK: - Life cycle methods override func viewDidLoad() { super.viewDidLoad() setUpAnimationsSet() } // MARK: - IBActions @IBAction func runAnimateButtonPressed() { animateButton() animateView() } // MARK: - Private methods private func animateView() { let currentAnimation = animations[animationCount] animatedView.animation = currentAnimation.animation animatedView.duration = currentAnimation.duration animatedView.curve = currentAnimation.curve animatedView.force = currentAnimation.force animatedView.delay = currentAnimation.delay animatedView.animate() guard animations.count - 1 != animationCount else { setUpAnimationsSet() return } animationCount += 1 setAnimationInfo(animation: animations[animationCount]) guard animations[animationCount].animation != animations.last?.animation else { setButtonInfo(title: "Restart \(animations.first?.animation ?? "")") return } setButtonInfo(title: "Next \(animations[animationCount + 1].animation)") } private func animateButton() { runAnimateButton.animation = "fadeIn" runAnimateButton.curve = "spring" runAnimateButton.duration = 1.0 runAnimateButton.animate() } private func setUpAnimationsSet() { animationCount = 0 setAnimationInfo(animation: animations[animationCount]) setButtonInfo(title: "Next \(animations[animationCount + 1].animation)") } private func setAnimationInfo(animation: Animation) { animationInfoLabel.text = """ Animation: \(animation.animation) Duration: \(animation.duration) Curve: \(animation.curve) Force: \(animation.force) Delay: \(animation.delay) """ } private func setButtonInfo(title: String) { runAnimateButton.setTitle(title, for: .normal) } } <file_sep>// // Animation Model.swift // Spring Animation App // // Created by Igor on 22.09.2021. // struct Animation { let animation: String let duration: Double let curve: String var force: Double = 1.0 var delay: Double = 0 static func getAnimations() -> [Animation] { [ Animation(animation: "morph", duration: 1, curve: "easeOut", force: 1.0, delay: 0), Animation(animation: "pop", duration: 1, curve: "easeOut"), Animation(animation: "swing", duration: 0.7, curve: "spring", force: 1.5, delay: 0.1), Animation(animation: "wobble", duration: 1.1, curve: "spring", force: 0.5, delay: 0.2), ] } }
789e6f3aa48c4b8adcfc171fec1555ace7d0c17d
[ "Swift" ]
2
Swift
lexemz/Animation-App
51ce74e73f2ade366a526d46fcee7b7e2e2cceec
e4a2c601a9a7c33b7463f7c1db756407fa5747f1
refs/heads/main
<repo_name>petrussola/test-auth0<file_sep>/src/App.js import './App.css'; import { useAuth0 } from '@auth0/auth0-react'; function App() { return ( <div className='App'> <Login /> <Logout /> <Profile /> </div> ); } function Login() { const { loginWithRedirect } = useAuth0(); return <button onClick={() => loginWithRedirect()}>Log In</button>; } function Logout() { const { logout } = useAuth0(); return ( <button onClick={() => logout({ returnTo: window.location.origin })}> Log Out </button> ); } function Profile() { const { user, isAuthenticated, isLoading } = useAuth0(); if (isLoading) { return <div>Loading...</div>; } return ( isAuthenticated && ( <div> <img src={user.picture} alt={user.name} /> <h2>{user.name}</h2> <p>{user.email}</p> </div> ) ); } export default App;
835558f287dd6a169328aec9ad2e76bdd23022a3
[ "JavaScript" ]
1
JavaScript
petrussola/test-auth0
143100ed480a5bf42786ce22a9dfedce33c0489d
72ec4688e7f31de396b6132faf21e7ba466fd4c2
refs/heads/main
<file_sep>import kong from "../Assets/Images/kong.jpg"; import oblivion from "../Assets/Images/oblivion.jpg"; import blodshot from "../Assets/Images/blodshot.jpg"; import { Carousel } from "react-bootstrap"; import React, { useState } from "react"; import { searchMovie } from "../Store/Action/Movies"; import { Link } from "react-router-dom"; import { connect } from "react-redux"; function MovieCarousel(props) { const [search, setSearch] = useState(""); const handleSubmit = (e) => { e.preventDefault(); props.searchMovie({ query: search }); }; return ( <div> <div style={{ display: "flex", justifyContent: "center", }} > <form onSubmit={handleSubmit}> <input className="search-bar pl-2" value={search} placeholder="Search movie..." type="text" onChange={(e) => setSearch(e.target.value)} value={search} /> <br></br> <button style={{ display: "flex", justifyContent: "center", alignItems: "center", textAlign: "center", margin: "auto", marginTop: "8px", }} onClick={handleSubmit} class="btn btn-info" > <span>Search</span> </button> </form> </div> <div> {props.movieSearch.length === 0 ? ( <Carousel> <Carousel.Item> <div className="carousel-wrapper"> <img className="carousel-pict" src={kong} alt="First slide" /> </div> </Carousel.Item> <Carousel.Item> <div className="carousel-wrapper"> <img className="carousel-pict" src={oblivion} alt="Third slide" /> </div> </Carousel.Item> <Carousel.Item> <div className="carousel-wrapper"> <img className="carousel-pict" src={blodshot} alt="Third slide" /> </div> </Carousel.Item> </Carousel> ) : ( props.movieSearch.map((movie) => { return ( <div className="content-wrapper"> <div className="content-grid-wrapper"> <Link to={`/detail/${movie._id}`} > <div className="content-grid"> <img src={ movie.poster } /> <div className="content-grid-info"> <p className="font-weight-bold"> { movie.title } </p> <p className="font-weight-bold"> {movie.releaseDate.slice( 7, 12 )} </p> </div> <div className="content-grid-over"> <h4> Overview </h4> <p> { movie.synopsis } </p> </div> </div> </Link> </div> </div> ); }) )} </div> </div> ); } const mapStateToProps = (state) => { return { movieSearch: state.Movies.movieSearchData, }; }; export default connect(mapStateToProps, { searchMovie })(MovieCarousel); <file_sep>import React, { useState, useEffect } from "react"; import ReactStars from "react-rating-stars-component"; import { useParams } from "react-router-dom"; import { getMovieReviews, postReview } from "../../../Store/Action/Movies"; import { connect } from "react-redux"; import "../../../Styles/overview.css"; function Review(props) { const currentUser = localStorage.getItem("name"); console.log(currentUser); const params = useParams(); // const [countRating, setRating] = useState(0); const [objReview, setReview] = useState({ headline: "Review movie", rating: 0, comment: "", }); useEffect(() => { props.getMovieReviews(params.id); }, [params.id]); return ( <div className="container"> {!localStorage.getItem("my-token") ? null : ( <form className="review mt-4 ml-3"> <div className="review-img mr-4 pt-2"> <img src="https://icon-library.com/images/avatar-icon-free/avatar-icon-free-12.jpg" /> </div> <div className="review-form"> <label>{currentUser}</label> <ReactStars size={20} count={5} isHalf={true} value={objReview.rating} color={"grey"} activeColor={"yellow"} onChange={(newValue) => console.log({ newValue })} /> <textarea rows="4" cols="130" name="comment" form="usrform" placeholder="Input Review Here...." className="px-2 py-1" value={objReview.comment} onChange={(e) => setReview({ [e.target.name]: e.target.value })} /> <p>{objReview.comment}</p> <button className="btn-review py-1 px-3 mr-3 mt-2 float-right" onClick={(event) => { event.preventDefault(); postReview(params.id, { objReview }); }} > Submit </button> </div> </form> )} {/* {props.movieReview.length === 0 ? null : props.movieReview.map((review) => { return ( <div className="review mt-4 ml-3 w-75"> <div className="review-img mr-4 pt-2"> <img src="https://icon-library.com/images/avatar-icon-free/avatar-icon-free-12.jpg" /> </div> <div> <p className="font-weight-bold mb-0"> {review.user.username} </p> <p>{review.comment}</p> </div> </div> ); })} */} {props.movieReview.length === 0 ? null : props.movieReview.map((review) => review.length === 0 ? null : review.map((item) => { return ( <div className="review mt-4 ml-3 w-75"> <div className="review-img mr-4 pt-2"> <img src="https://icon-library.com/images/avatar-icon-free/avatar-icon-free-12.jpg" /> </div> <div> <p className="font-weight-bold mb-0"> {item.user === null ? "Anonymous" : item.user.username} </p> <p>{item.comment}</p> </div> </div> ); }) )} </div> ); } const mapStateToProps = (state) => { return { movieReview: state.Movies.reviewData, }; }; export default connect(mapStateToProps, { getMovieReviews, postReview })( Review ); <file_sep>import axios from "axios"; import { useEffect, useState } from "react"; import jwt_decode from "jwt-decode"; import "../Styles/Login.css"; import email from "../Assets/Images/email.png"; import password from "../Assets/Images/password.png"; import { useHistory, Link } from "react-router-dom"; const LoginPage = () => { const [logData, setLogData] = useState({ email: "", password: "", }); const [token, setToken] = useState(""); const [userData, setUserData] = useState([]); const handleChange = (e) => { setLogData({ ...logData, [e.target.name]: e.target.value, }); }; const history = useHistory(); const handleLogin = (e) => { e.preventDefault(); const body = { email: logData.email, password: <PASSWORD>, }; axios.post("https://laflix-api.herokuapp.com/api/login", body).then( (response) => { console.log(response); if (response.status === 200) { setToken(response.data.data.token); setUserData(jwt_decode(response.data.data.token)); console.log(token); console.log(userData.username); localStorage.setItem( "name", jwt_decode(response.data.data.token) .username ); localStorage.setItem( "my-token", response.data.data.token ); localStorage.setItem( "user-info", JSON.stringify( jwt_decode(response.data.data.token) ) ); history.push("/"); window.location.reload(true); } } ); }; useEffect(() => { if (localStorage.getItem("user-info")) { setUserData(JSON.parse(localStorage.getItem("user-info"))); } }, []); return ( <> <div className="login-form"> <div className="box"> <div className="form"> {/* <h2>Welcome {userData.username}</h2> <button onClick={logout}>Logout</button> */} <h1>Login LAFLIX</h1> <form onChange={handleChange}> <h3>Email</h3> <input type="text" name="email" className="input-form" /> <img src={email} alt="email" className="form-logo" /> <br /> <h3>Password</h3> <input type="<PASSWORD>" name="password" className="input-form" /> <img src={password} alt="password" className="form-logo" /> <br /> <button onClick={handleLogin} className="login-btn" > Login </button> <br /> <p> Doesn't Have One? Create an Account{" "} <Link to="/register"> Create an Account </Link> </p> </form> </div> </div> </div> </> ); }; export default LoginPage; <file_sep>import Logo from "../Assets/Images/logo.png"; import React from "react"; import "../Styles/NavBar.css"; import { NavLink, useHistory } from "react-router-dom"; import logout from "../Assets/Images/log-out.png"; const Navbar = () => { const history = useHistory(); const logOut = () => { localStorage.clear(); history.push("/login"); window.location.reload(true); }; const logInfo = localStorage.getItem("user-info"); console.log(logInfo); return ( <div className="navbar"> <div className="container"> <NavLink exact to="/" className="nav-link"> <div className="logo-wrapper"> <img alt="" src={Logo} className="laflix-logo" /> <h3>LAFLIXTV</h3> </div> </NavLink> {localStorage.getItem("user-info") ? ( <> <div className="signin-route"> <NavLink className="watch-list" to="/watch-list" > <h3>Watchlist</h3> </NavLink> <h5 className="username"> Sign In as:{" "} {localStorage.getItem("name")} </h5> </div> <div> <img src={logout} onClick={logOut} alt="logout" className="logout-btn" /> </div> </> ) : ( <> <NavLink to="/login"> <h3>SignIn</h3> </NavLink> </> )} </div> </div> ); }; export default Navbar;
eecb7ab27a117bbfefcadb5e7c27243dfae65ff6
[ "JavaScript" ]
4
JavaScript
naharnafi/movie-nahar
9032612eb2e7e41ed702ef450cbe5d1a3b0c7375
41d6d6bc963a7129e3a7fa5d7232934116b3d1b8
refs/heads/master
<file_sep>#!/bin/python3 import os from sys import exit result = os.popen('docker build .').readlines() result = [s.strip() for s in result] if "Successfully" in result[-1]: os.popen("docker tag {} 192.168.88.34:5000/gvm11".format(result[-1].split(" ")[-1])).read() else: print("error at build") [print(l) for l in result] print("error at build") exit(2) os.system("docker push 192.168.88.34:5000/gvm11")<file_sep>FROM alpine:3.11 VOLUME [ "/sys/fs/cgroup" ] RUN apk update RUN apk add openvas openvas-config gvmd gvm-libs greenbone-security-assistant ospd-openvas bash RUN apk add openrc dos2unix sudo tzdata COPY configgwm.sh /configgwm.sh COPY configpg.sh /configpg.sh COPY start.sh /start.sh RUN chmod +x /*.sh RUN dos2unix /*.sh ENTRYPOINT ["/start.sh"] <file_sep>#!/bin/bash /configpg.sh /configgwm.sh /etc/init.d/gvmd stop /etc/init.d/gvmd start --verbose<file_sep>#!/bin/bash exec sudo -u gvm /bin/sh - << 'EOF' gvm-manage-certs -a gvmd --create-user=admin --password=<PASSWORD> greenbone-scapdata-sync greenbone-certdata-sync EOF<file_sep>#!/bin/bash mkdir /run/openrc touch /run/openrc/softlevel /etc/init.d/postgresql setup /etc/init.d/postgresql start exec sudo -u postgres /bin/sh - << 'EOF' createuser -DRS gvm createdb -O gvm gvmd create role dba with superuser noinherit; grant dba to gvm; create extension if not exists "uuid-ossp"; create extension "pgcrypto"; exit EOF
62c69b978149f93dbc762bd404f2a49e3091841c
[ "Python", "Dockerfile", "Shell" ]
5
Python
physicalit/gwm11-docker
af0475c46ab54fa5ac81fd6b581e6fe33147075e
d30bd9cf861f881fbc3ccd4134753388e570b6a1
refs/heads/master
<file_sep>- https://cran.r-project.org/web/views/Optimization.html#general-purpose-continuous-solvers - https://cran.r-project.org/web/views/Optimization.html#least-squares-problems - nimble, Stan (as optimizer), brms (for nonlin problems) - sparsity - parameterization (logistic etc.) - reasons for nonlinear models - specific functions in mind - functional responses - ODE dynamics - photosynthetic curves - saturating curves - reparameterization of linear models - LD50 CIs - quick review of likelihood theory - MLE - profiles - Wald CIs - chapters 6/7 - least-squares - optimizers - derivative-free - - instability - Raue et al - geometry - parameter transformation: pros and cons - compress ranges - improve quadraticity/Wald-ness - decorrelate - multistart? - latent-variable stuff # examples - functional responses: Stier/Geange et al. - Ellner survival - Pujoni algae - Gonzalez integrated population models??? - tadpoles? - Owls? - McCoy tadpoles? - # questionnaire https://kaskr.github.io/adcomp/group__R__style__distribution.html <file_sep>--- title: "Likelihood intro/reminder" author: <NAME> (some material from <NAME>) date: "`r format(Sys.time(), '%d %B %Y ')`" --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. ```{r pkgs, echo=FALSE,message=FALSE} library(bbmle) library(emdbook) library(ellipse) ``` # Likelihood ## Definition - probability of data given a model (structure & parameters) - in R: distributions via `d*` functions (base, [Distributions Task View](https://cran.r-project.org/web/views/Distributions.html)) - usually: complex model for the *location*, simpler models for the *scale* and *shape* - e.g. Gamma with fixed shape, varying mean ## MLEs are consistent and asymptotically Normal - *consistent* = converge to the true values as the number of independent observations grows to infinity - asymptotic Normality is the basis for the approximate (Wald) standard errors from `summary()` ## MLEs are asymptotically efficient - important but a bit delicate. - as number of independent observations $n$ increases, the standard errors on each parameter decrease in proportion to $C/\sqrt{n}$ for some constant $C$ - **Asymptotically efficient** means that there is no unbiased way of estimating parameters for which the standard errors shrink at a strictly faster rate (e.g., a smaller value of $C$, or a higher power of $n$ in the denominator). ## MLEs = Swiss Army knife - MLEs make sense - lots of justifying theory - when it can do the job, it's rarely the best tool for the job but it's rarely much worse than the best (at least for large samples) - most statistical models (least-squares, GLMs) are special cases of MLE ## Inference - **Wald approximation**: quadratic approximation (parabolas/ellipses) - p-values: $Z$-scores ($\hat \beta/\sigma_{\hat \beta}$ \sim N(0,1)$) - confidence intervals: based on $N(\hat \beta, \sigma_{\hat \beta})$ - strongly asymptotic - **likelihood**: - p-values: likelihood ratio test ($-2 \Delta \log L \sim \chi^2_n$) - CIs: *likelihood profiles* - **bootstrapping** - nonparametric (slow, requires independence) - parametric (slow, model-dependent) - **Bayesian** - requires priors - strongly model-dependent - often slow - ... but solves many problems Beyond Normal errors, finite-size corrections are tricky ## ... ```{r gourd_def, cache=TRUE,echo=FALSE,message=FALSE} library(bbmle) library(emdbook) gourd <- function(x,y,s1=0,s2=3,a=1,s1exp=1,rot=FALSE,theta=pi/4){ if (rot) { newx <- cos(theta)*x+sin(theta)*y newy <- -sin(theta)*x+cos(theta)*y x<-newx y<-newy } a*((exp(s1+s1exp*y)*x)^2+(s2*y)^2) } fun1 <- function(x,y) gourd(x,y,s1exp=0,a=0.5) fun2 <- function(x,y) gourd(x,y,s1exp=0,a=0.5,rot=TRUE) fun3 <- function(x,y) gourd(x,y,s1exp=2,a=1) fun4 <- function(x,y) gourd(x,y,s1exp=2,a=1.2,rot=TRUE) c1 <- curve3d(fun1,from=c(-3,-2),to=c(3,2), sys3d="none") c2 <- curve3d(fun2,from=c(-3,-2),to=c(3,2), sys3d="none") c3 <- curve3d(fun3,from=c(-3,-2),to=c(3,2), sys3d="none",n=c(71,71)) c4 <- curve3d(fun4,from=c(-3,-2),to=c(3,2), sys3d="none",n=c(91,91)) tmpf <- function(fun0,c0,heights=c(-2.3,-1.7,-2), xpos = 2.35, quadlty=1,quadcol="darkgray", legend=FALSE) { ## 2D (univariate) confidence region contour(c0$x,c0$y,c0$z, levels=qchisq(0.95,1)/2, drawlabels=FALSE,axes=FALSE, xlab="",ylab="", xlim=c(-3,3.4), ylim=c(-2.4,1.8)) box(col="gray") m <- mle2(fun0,start=list(x=0,y=0)) p <- profile(m) s <- sliceOld(m) sliceconf.x = approx(s$profile$x$z, s$profile$x$par.vals[,"x"], xout = qnorm(c(0.025,0.975)))$y profconf.x = confint(p)["x",] profconf.y = approx(p@profile$x$z, y=p@profile$x$par.vals[,"y"], xout = qnorm(c(0.025,0.975)))$y ellconf.x = confint(m,method="quad")["x",] v = vcov(m) slope = v[1,2]/v[1,1] ellconf.y = ellconf.x*slope lines(ellipse(vcov(m),centre=coef(m), t=sqrt(qchisq(0.95,1))),lty=quadlty, col=quadcol) ## redraw contour(c0$x,c0$y,c0$z, levels=qchisq(0.95,1)/2, drawlabels=FALSE,add=TRUE) lines(p@profile$x$par.vals[,"x"],p@profile$x$par.vals[,"y"],lty=2) abline(a=0,b=slope) points(ellconf.x,ellconf.y,pch=2) points(profconf.x,profconf.y,pch=5) points(sliceconf.x,rep(0,2),pch=8) points(ellconf.x,rep(heights[1],2),pch=2) segments(ellconf.x[1],heights[1],ellconf.x[2],heights[1],pch=2) points(profconf.x,rep(heights[2],2),pch=5) segments(profconf.x[1],heights[2],profconf.x[2],heights[2]) points(sliceconf.x,rep(heights[3],2),pch=8) segments(sliceconf.x[1],heights[3],sliceconf.x[2],heights[3]) text(rep(xpos,3),heights,c("quad","profile","slice"),cex=0.75,adj=0) if (legend) { legend("topleft", c("conf. region", "quadratic", "profile"), lwd=2, lty=c(1,quadlty,2), col=c(1,quadcol,1), bty="n",cex=0.75) } } ``` ```{r gourd_draw,echo=FALSE} op <- par(mfrow=c(2,2),lwd=2,bty="l",las=1,cex=1.5, mar=c(0,0,0,0)) tmpf(fun1,c1) tmpf(fun2,c2) tmpf(fun3,c3,legend=TRUE) tmpf(fun4,c4) par(op) ``` <file_sep>library(emdbook) library(bbmle) data(ReedfrogSizepred) ##' @param x ##' @param sizep1 rate parameter (1/logit change scale) ##' @param sizep2 power ##' @param sizep3 half-maximum logist2 <- function(x,sizep1,sizep2,sizep3) { exp(sizep1*(sizep3-x))/(1+exp(sizep2*sizep1*(sizep3-x))) } ##' @param a scale ##' @param b y-scale ##' @param alpha power powricker <- function(x,a,b,alpha) { b*((x/a)*exp(1-(x/a)))^alpha } ## fit models mle_logist2 <- mle2(Kill ~ dbinom(logist2(TBL,sizep1,sizep2,sizep3), size=10), start=list(sizep1=0,sizep2=1,sizep3=12), data=ReedfrogSizepred, method="Nelder-Mead") mle_powricker <- mle2(Kill ~ dbinom(powricker(TBL,a,b,alpha), size=10), start=list(a=10,b=1,alpha=1), data=ReedfrogSizepred, method="Nelder-Mead") ## alternate fit (focal) mle_logist2C <- update(mle_logist2, method="BFGS", control=list(maxit=1000)) ## alternate fits (not used) mle_logist2B <- update(mle_logist2, method="BFGS", control=list(parscale=c(0.3,30,10))) mle_logist2D <- update(mle_logist2, start=as.list(coef(mle_logist2C)), control=list(maxit=1000)) slice2 <- calcslice(mle_logist2,mle_logist2C,n=1000) save.image(file="vonesh_slice_dat.rda") cc1 <- coef(mle_logist2) cc2 <- coef(mle_logist2C) dd <- expand.grid(sizep1=seq(cc1["sizep1"]*1.1,cc2["sizep1"]*1.1,length=41), sizep2=round(emdbook::lseq(1,65,9)), sizep3=seq(cc1["sizep3"]*1.1,cc2["sizep3"]*0.9,length=41), z=NA) for (i in 1:nrow(dd)) { dd$z[i] <- with(dd[i,], mle_logist2@minuslogl(sizep1,sizep2,sizep3)) } cc_pr <- coef(mle_powricker) dd_powricker <- expand.grid(a=seq(cc_pr["a"]*0.9,cc_pr["a"]*1.1,length=41), b=seq(cc_pr["b"]*0.9,cc_pr["b"]*1.1,length=41), alpha=seq(12,29,by=2), z=NA) for (i in 1:nrow(dd_powricker)) { dd_powricker$z[i] <- with(dd_powricker[i,], mle_powricker@minuslogl(a,b,alpha)) } library(ggplot2); theme_set(theme_bw()) library(viridisLite) get_zmin <- function(x,eps=0.001) log10(x-min(x)+eps) dd$zmin <- get_zmin(dd$z) dd_powricker$zmin <- get_zmin(dd_powricker$z) gg_vonesh <- ggplot(dd,aes(sizep1,sizep3,fill=zmin,z=z))+ geom_tile()+ scale_fill_viridis_c()+ geom_contour(colour="red",alpha=0.2)+ facet_wrap(~sizep2, labeller=label_both)+ scale_x_continuous(expand=c(0,0))+ scale_y_continuous(expand=c(0,0))+ theme(panel.spacing=grid::unit(0,"lines")) ggsave("vonesh_surface.png") ## png("vonesh_surface2.png",height=400,width=400) lattice::levelplot(zmin~sizep1*sizep3|sizep2, data=dd, as.table=TRUE, col.regions=viridis(100)) dev.off() png("vonesh_surface3.png",height=400,width=400) lattice::levelplot(zmin~a*b|alpha, data=dd_powricker, as.table=TRUE, col.regions=viridis(100)) dev.off() <file_sep>--- title: "Latent variables and mixed model examples" author: <NAME> date: "`r format(Sys.time(), '%H:%M %d %B %Y ')`" bibliography: ../nonlin.bib --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. NOTHING YET <file_sep>initial = function(mCall, data, LHS) { xy <- sortedXyData(mCall[["input"]], LHS, data) if (nrow(xy) < 5) { stop("too few distinct input values to fit a four-parameter logistic") } ## convert the response to a proportion (i.e. contained in (0,1)) rng <- range(xy$y); drng <- diff(rng) xy$prop <- (xy$y - rng[1L] + 0.05 * drng)/(1.1 * drng) ## inverse regression of the x values on the proportion ir <- as.vector(coef(lm(x ~ I(log(prop/(1-prop))), data = xy))) pars <- as.vector(coef(nls(y ~ cbind(1, 1/(1 + exp((xmid - x)/exp(lscal)))), data = xy, start = list(xmid = ir[1L], lscal = log(abs(ir[2L]))), algorithm = "plinear"))) setNames(c(pars[3L], pars[3L] + pars[4L], pars[1L], exp(pars[2L])), nm = mCall[c("A", "B", "xmid", "scal")]) }, parameters = c("A", "B", "xmid", "scal")) <file_sep>--- title: Nonlinear optimization author: <NAME> date: "`r format(Sys.time(), '%d %B %Y')`" bibliography: ../nonlin.bib --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. # Optimization ## no free lunch - [Wikipedia](https://en.wikipedia.org/wiki/No_free_lunch_in_search_and_optimization) - > "any two algorithms are equivalent when their performance is averaged across all possible problems." - a "good" optimization method is one that works on the kinds of problems you have ## implementations **the devil is in the details**; different implementations *of the same algorithm* may differ ... - performance - robustness - interface (arguments, return values) - controls - convergence testing # Local optimization ## derivative-based optimization - uses first (gradient/direction) and second (Hessian/curvature) information - assumes smooth objective function - R's optimization functions don't need user-supplied gradient functions - but will use **finite differences** instead ## derivative-based methods - see @Press+1994 (or later editions) - *gradient descent*: widely used in machine learning - easy, scalable - but can almost certainly do better! - *Newton's method*: simple but not actually practical (unstable, expensive) - Levenberg-Marquardt: specifically for least squares problems - conjugate gradients (CG), quasi-Newton (`BFGS`, `L-BFGS-B`) - various fancier methods ## derivative-free methods - for non-smooth surfaces, or when derivatives are expensive - Nelder-Mead - BOBYQA, COBYLA, NEWUOA (Powell) ... # Stochastic/global optimization ## stochastic optimization - for noisy surfaces, multi-modal problems ... - see [CRAN optimization task view section](https://cran.r-project.org/web/views/Optimization.html#global-and-stochastic-optimization) - classic method is *simulated annealing* (`method="SANN"`) - **slow** and needs lots of tuning ## simulated annealing - local search with decreasing noise - local "jumps" according to a **candidate distribution** - accept with probability $\exp(-\Delta G/T)$ - high temperature: random search - low temperature: local ratchet - tuning: candidate distribution, cooling schedule - very general (don't need continuous parameters) - compare Metropolis-Hastings in Markov chain Monte Carlo ## genetic algorithms - population-based - biological analogies - reproduction, selection, mutation, recombination ("crossover") - flexible - parameters often coded as bit strings - `genoud` package? ## differential evolution - population-based - derivative-free - continuous parameters - `DEoptim` package --- ![](pix/ugly2.png) <file_sep># Algal (non)-linear mixed model example Version `r as.character(Sys.time())` ```{r knitopts,echo=FALSE} knitr::opts_chunk$set(tidy=FALSE) ``` ## Preliminaries Inspired by a question from <NAME> [on r-sig-mixed](http://article.gmane.org/gmane.comp.lang.r.lme4.devel/9363/match=), and (a few days later, presumably because there was no response) [on r-help](http://article.gmane.org/gmane.comp.lang.r.general/283733). The parameters of the problem are that the intercept (0-day value) is known to be identical across groups and individuals. ```{r prelims,message=FALSE,warning=FALSE} library(nlme) library(lme4) library(TMB) ## library(reshape2) library(plyr) library(ggplot2) theme_set(theme_bw()) library(bbmle) ## for AICtab library(splines) ## for profiles library(broom.mixed) ``` Data: ```{r data} d <- data.frame(Day = rep(c(0,2,4,6,8,10),each=9), Group = rep(c("c","c","c","t1","t1","t1","t2","t2","t2"),6), Individual = factor(rep(1:9,6)), X = c(0.71,0.72,0.71,0.72,0.72,0.72,0.70,0.69,0.70,0.72,0.72, 0.71,0.72,0.72,0.71,0.71,0.70,0.71,0.73,0.73,0.69,0.74, 0.69,0.73,0.67,0.71,0.69,0.71,0.71,0.72,0.70,0.71,0.70, 0.52,0.64,0.60,0.70,0.73,0.73,0.67,0.66,0.71,0.47,0.56, 0.54,0.65,0.73,0.73,0.67,0.71,0.58,0.44,0.52,0.58)) ``` Just for the heck of it, plot the data both with `lattice` and with `ggplot2`. ```{r latticeplot,warning=FALSE} library(lattice) xyplot(jitter(X)~Day, groups=Group, data=d,type=c("a","p"), auto.key=list(space="right")) ``` `ggplot` version has two small advantages: 1. Add lines both by individual and group average [should be as easy with `stat_summary` as with `type="a"` in `xyplot`, but there is a bug in the latest `ggplot` version ...]); 2. Adjust point size rather than jittering to visualize overlapping points. (Both of these would of course be possible with a custom `panel.xyplot` ...) ```{r ggplot} ## have to aggregate by hand: stat_summary bug d2 <- ddply(d,c("Day","Group"),summarise,X=mean(X)) (g1 <- ggplot(d,aes(x=Day,y=X,colour=Group))+ stat_sum(aes(size=factor(..n..)),alpha=0.5)+ scale_size_discrete(range=c(2,5),name="npts")+ geom_line(aes(group=Individual),alpha=0.5)+ geom_line(data=d2,lwd=2,alpha=0.8)+ scale_colour_brewer(palette="Dark2")) ``` The main conclusions from these pictures are that (1) we probably ought to be using a nonlinear rather than a linear model; (2) there might be some heteroscedasticity (larger variance at lower means, as though there is a "ceiling" to the data at $\approx X=0.7$); it does look as though there could be among-individual variation (based especially on the `t2` data, where the individual curves are approximately parallel). However, we'll also try linear fits for illustration (even though they won't be very good): ## Using `nlme` Linear fits with `lme` fail: ```{r lmefit1,error=TRUE} LME <- lme(X ~ 1, random = ~Day|Individual, data=d) ``` If we run this with `control=lmeControl(msVerbose=TRUE)))` we get a lot of output, ending with: ```{r eval=FALSE} 47: -65.306481: 5.38940 0.705107 179.050 48: -65.306489: 5.42212 0.705107 184.783 49: -65.306493: 5.45375 0.705106 190.516 50: -65.306499: 5.47352 0.705104 194.382 50: -65.306499: 5.47352 0.705104 194.382 ``` Unsurprisingly, a more complex model allowing for `Group*Day` effects fails too: ```{r error=TRUE} LME1 <- lme(X ~ Group*Day, random = ~Day|Individual, data=d) ``` ` I tried to fit a non-linear model using `SSfpl`, a self-starting four-parameter logistic model (with parameters left-asymptote, right-asymptote, midpoint, scale parameter). This works fine for an `nls` fit, giving reasonable results: ```{r nlsfit1} nlsfit1 <- nls(X ~ SSfpl(Day, asymp.L, asymp.R, xmid, scale),data=d) coef(nlsfit1) ``` Can use `gnls` to fit group-level differences (although for some reason I need to specify starting values, even though the help file would lead me to believe I don't have to ... perhaps I do when `params` is specified?) My first attempt is apparently a little too ambitious for `gnls`: ```{r gnlsfit1, error=TRUE} svec <- list(asymp.L=0.7, asymp.R=c(0.6,0,0), xmid=c(5,0,0), scale=c(1,0,0)) gnlsfit1 <- gnls( X ~ SSfpl(Day, asymp.L, asymp.R, xmid, scale), data=d, params=list(asymp.R+scale+xmid~Group,asymp.L~1), start=svec) ``` But I can succeed if I allow only `asymp.R` to vary among groups: ```{r gnlsfit2} svec2 <- list(asymp.L=0.7, asymp.R=c(0.6,0,0), xmid=6, scale=1) gnlsfit2 <- gnls(X ~ SSfpl(Day, asymp.L, asymp.R, xmid, scale),data=d, params=list(asymp.R~Group,asymp.L++scale+xmid~1), start=svec2) ``` Plot predicted values: ```{r gnlspred} predframe <- with(d,expand.grid(Day=unique(Day),Group=levels(Group))) predframe$X <- predict(gnlsfit2,newdata=predframe) g1 + geom_line(data=predframe,linetype=3,lwd=2,alpha=0.8) ``` These look pretty good (it would be nice to get confidence intervals too, but that's a little bit too much of a pain for right now -- need to use either delta method or bootstrapping). ```{r resids} dp <- data.frame(d,res=resid(gnlsfit2),fitted=fitted(gnlsfit2)) (diagplot1 <- ggplot(dp,aes(x=factor(Individual), y=res,colour=Group))+ geom_boxplot(outlier.colour=NULL)+ scale_colour_brewer(palette="Dark2")) ``` With the exception of individual #7 there's not a lot of evidence for among-individual variation ... if we wanted an excuse to ignore among-individual variation we could use ```{r} anova(lm(res~Individual,data=dp)) ``` (whatever philosophical issues this raises about using a large $p$-value to accept the null hypothesis that among-individual variation is absent ...) More general diagnostic plot -- residual vs. fitted, with points from the same individual connected with lines. There is some hint of decreasing variance with increasing mean. ```{r} (diagplot2 <- ggplot(dp,aes(x=fitted,y=res,colour=Group))+geom_point()+ geom_smooth(aes(group=1),colour="black",method="loess")+ geom_path(aes(group=Individual))+ geom_hline(yintercept=0,lty=2)) ``` I can't use `nlme` with the more ambitious (three parameters varying by group) model, but I can if I only allow `asymp.R` to vary: ```{r} nlmefit1 <- nlme(model = X ~ SSfpl(Day, asymp.L, asymp.R, xmid, scale), fixed = list(asymp.R ~ Group, xmid+scale+asymp.L ~1), random = asymp.R ~ 1 | Individual, start = list(fixed=with(svec2,c(asymp.R,xmid,scale,asymp.L))), data=d) ``` The estimate of the variance in the right-hand asymptote is non-zero (yay): ```{r} VarCorr(nlmefit1) ``` Adding the random effects doesn't change the parameters much at all: ```{r} print(mm1 <- merge(data.frame(cc=coef(gnlsfit2)), data.frame(cc=fixef(nlmefit1)),by="row.names"), digits=4) maxdiff <- max(apply(mm1[,-1],1,function(x) abs(diff(x)/mean(x)))) ``` The biggest proportional difference is `r round(100*maxdiff,1)`% (in the `scale` parameter). ```{r nlmefit2} nlmefit2 <- update(nlmefit1,fixed = list(asymp.R+xmid+scale+asymp.L ~1), start = list(fixed=with(svec2,c(asymp.R[1],xmid,scale,asymp.L)))) ``` Wald test for asympR(groupt1)=asympR(groupt2)=0: is $\hat x V^{-1} {\hat x}^\top$ in the upper tail of $\chi^2_2$? ```{r} pars <- c("asymp.R.Groupt1","asymp.R.Groupt2") ests <- fixef(nlmefit1) V_hat <- vcov(nlmefit1) R <- rbind(rep(0,length(ests))) R[names(ests) %in% pars] <- 1 W = as.numeric(t(R %*% ests) %*% solve(R %*% V_hat %*% t(R)) %*% (R %*% ests)) pchisq(W,df=3,lower.tail=FALSE) ``` Better, we can compare the models via AIC or likelihood ratio test (`AICtab` from the `bbmle` package is not essential, but gives pretty output): ```{r modelcomp} AICtab(nlmefit1,nlmefit2,weights=TRUE) anova(nlmefit1,nlmefit2) ``` It would be nice to do an $F$ test rather than LRT (i.e. accounting for the finite-size correction), but it's a little bit more work (and probably not really necessary since the answer is so strong). Check that we have the right structure: ```{r} devdiff <- -2*c(logLik(nlmefit2)-logLik(nlmefit1)) pchisq(devdiff,df=2,lower.tail=FALSE) ## F-test with very large denominator: pf(devdiff/2,df1=2,df2=1000000,lower.tail=FALSE) ``` ```{r nlmefittab,echo=FALSE} printCoefmat(rename(data.frame(summary(nlmefit1)$tTable), c(p.value="Pr(|t|>1)"))) ``` We don't really know the relevant denominator df, but the summary above suggests the denominator df is 40 (based on the usual type of classical-block-design analogy for df counting, see Pinheiro and Bates 2000 or [the glmm wikidot faq](http://glmm.wikidot.com/faq)). ```{r} pf(devdiff/2,df1=2,df2=40,lower.tail=FALSE) ``` ## TMB ### Minimal example First try it without random effects, grouping variables, etc. (i.e. equivalent to `nls` fit above). ```{r algae1,cache=TRUE} writeLines(con="algae1.cpp", "// algae example #include <TMB.hpp> template<class Type> Type objective_function<Type>::operator() () { DATA_VECTOR(Day); DATA_VECTOR(X); PARAMETER(asympL); PARAMETER(asympR); PARAMETER(xmid); PARAMETER(scale); PARAMETER(logsd); ADREPORT(exp(2*logsd)); // for (i=0; i<pred.size(); i++) { vector<Type> pred(Day.size()); Type nll; pred = asympL+(asympR-asympL)/(1.0 + exp(-(Day-xmid)/scale)); nll = -sum(dnorm(X, pred, exp(logsd), true)); return nll; } ") compile("algae1.cpp") ``` ```{r} dyn.load(dynlib("algae1")) ## set up data: adjust names, etc. d0 <- subset(d,select=c(Day,X)) ## starting values: adjust names, add values svec3 <- svec2 names(svec3) <- gsub("\\.","",names(svec3)) ## remove dots svec3$asympR <- 0.6 ## single value svec3$logsd <- 1 obj <- MakeADFun(as.list(d[c("Day","X")]), svec3, DLL="algae1", silent=TRUE) do.call("optim",obj) class(obj) <- "TMB" ``` Works fine: ```{r echo=FALSE} tidy(obj) ``` ### Fixed effects model ```{r algae2, cache=TRUE} writeLines(con="algae2.cpp", "// algae example #include <TMB.hpp> template<class Type> Type objective_function<Type>::operator() () { DATA_VECTOR(Day); DATA_VECTOR(X); DATA_MATRIX(R_X); PARAMETER(asympL); PARAMETER_VECTOR(asympR); PARAMETER(xmid); PARAMETER(scale); PARAMETER(logsd); ADREPORT(exp(2*logsd)); vector<Type> pred(Day.size()); vector<Type> R_val(Day.size()); Type nll; R_val = R_X*asympR; pred = asympL+(R_val-asympL)/(1.0 + exp(-(Day-xmid)/scale)); nll = -sum(dnorm(X, pred, exp(logsd), true)); return nll; } ") compile("algae2.cpp") ``` ```{r run_algae2} dyn.load(dynlib("algae2")) R_X <- model.matrix(~Group,data=d) d1 <- c(d0,list(R_X=R_X)) names(svec2) <- gsub("\\.","",names(svec2)) ## remove dots svec2$logsd <- 1 obj <- MakeADFun(d1, svec2, DLL="algae2", silent=TRUE) do.call("optim",obj) class(obj) <- "TMB" ``` ```{r tidy_algae2} tidy(obj) ``` Works, with identical parameters (except for order/names), of course. ### Random effects Now adding the random effects. ```{r algae3,cache=TRUE} writeLines(con="algae3.cpp", "// algae example #include <TMB.hpp> template<class Type> Type objective_function<Type>::operator() () { DATA_VECTOR(Day); DATA_VECTOR(X); DATA_MATRIX(R_X); DATA_SPARSE_MATRIX(R_Z); PARAMETER(asympL); PARAMETER_VECTOR(asympR); PARAMETER_VECTOR(R_u); PARAMETER(xmid); PARAMETER(scale); PARAMETER(logsd); PARAMETER(logsd_u); ADREPORT(exp(2*logsd)); ADREPORT(exp(2*logsd_u)); vector<Type> pred(Day.size()); vector<Type> R_val(Day.size()); Type nll = 0.0; R_val = R_X*asympR+exp(logsd_u)*(R_Z*R_u); pred = asympL+(R_val-asympL)/(1.0 + exp(-(Day-xmid)/scale)); nll -= sum(dnorm(X, pred, exp(logsd), true)); nll -= sum(dnorm(R_u, 0.0, 1.0, true)); return nll; } ") compile("algae3.cpp") ``` ```{r run_algae3} dyn.load(dynlib("algae3")) R_Z <- Matrix::sparse.model.matrix(~Individual-1,data=d) d2 <- c(d1,list(R_Z=R_Z)) svec2B <- c(svec2, list(R_u=rep(0,9),logsd_u=0)) obj <- MakeADFun(d2, svec2B, DLL="algae3", random="R_u", silent=TRUE) oo1 <- do.call("optim",obj) class(obj) <- "TMB" tidy(obj) obj2 <- MakeADFun(d2, svec2B, map=list(asympR=factor(c(1,NA,NA))), DLL="algae3", random="R_u", silent=TRUE) oo2 <- do.call("optim",obj2) class(obj2) <- "TMB" tidy(obj2) ``` ```{r echo=FALSE,eval=FALSE} library(brms) prior1 <- prior(normal(0, 4), lb=0, nlpar = "asympL") + prior(normal(0, 4), lb=0, nlpar = "asympR") + prior(normal(5,10), lb=0, nlpar="xmid") + prior(normal(0,5), lb=0, nlpar="scale") fit1 <- brm(bf(X ~ asympL+(asympR-asympL)/(1.0 + exp(-(Day-xmid)/scale)), asympL+asympR + xmid+scale ~ 1, nl = TRUE), data = d, prior = prior1) pairs(fit1) fit2 <- brm(bf(X ~ asympL+(asympR-asympL)/(1.0 + exp(-(Day-xmid)/scale)), asympL+ xmid+scale ~ 1, asympR ~ Group, nl = TRUE), data = d, prior = prior1) ``` <file_sep>library(TMB) #Input data x = -5:6 y = c(8.8, 8.7, 9.4, 10.0, 8.8, 9.7, 10.7, 10.6, 9.6, 11.4, 10.7, 11.1) #Organize data for TMB dat = list(x=x, y=y) #Set initial values for parameters to estimate par = list(a=8, b=1, log_sigma=0) #Compile the model compile("linear_regression.cpp") dyn.load(dynlib("linear_regression")) #Combine data, parameters, and model to make objective function (i.e. nll) obj = MakeADFun(dat, par, DLL="linear_regression") #Optimize the objective function (i.e. minimize the nll) opt = nlminb(obj$par, obj$fn, obj$gr) #Output results summary(sdreport(obj)) <file_sep>--- title: Simple nonlinear examples author: <NAME> date: "`r format(Sys.time(), '%d %B %Y')`" bibliography: ../nonlin.bib --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. # Basics ## outline - explore data (plot) - define objective function (neg log likelihood) - decide on starting values - choose optimization function (`optim()` etc.) ## Set up objective function *either* - objective function as explicit function of parameter vector `p` - explicit - arbitrarily complex - *or* use `bbmle::mle2` formula interface - simpler, readable - allows use of `predict()`, `simulate()`, `residuals()` ... - don't have standalone prediction/log-likelihood function (except `@minuslogl`) # tadpoles (functional response) From @VoneshBolker2005. Suggested models: ```{r} frogs <- emdbook::ReedfrogFuncresp ## predicted number killed with two different rogers_pred <- function(N0, a, h, P, time) { N0 - emdbook::lambertW(a * h * N0 * exp(-a * (P * time - h * N0)))/(a * h) } holling_pred <- function(N0, a, h, P, time) { a*N0*P*time/(1+a*h*N0) } time <- 14 ## time period P <- 3 ## number of predators ``` - initial slope=$aPT$ ($a$ = predation rate per predator per unit time) - asymptote = $PT/h$ # caterpillar virus From @reilly_density-dependent_2008, a tiny data set: ```{r} dd <- read.table(header=TRUE, text=" density larvae surviving 1 90 60 5 90 60 10 89 56 15 87 41 20 93 31 ") ``` Suggested model: $S \sim \textrm{Binom}(p=\beta_0 + \beta_1 D^\beta_2$, N)$ ## references <file_sep>--- title: "Latent variables and mixed models" author: <NAME> date: "`r format(Sys.time(), '%H:%M %d %B %Y ')`" bibliography: ../nonlin.bib --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. ## latent/random variables - spatial - temporal - continuous mixtures (e.g. Normal) - finite mixtures (e.g. mixture models) - dynamic (state-space) models: process/observation errors ## generalized linear mixed models $$ \begin{split} \underbrace{Y_i}_{\text{response}} & \sim \overbrace{\text{Distr}}^{\substack{\text{conditional} \\ \text{distribution}}}(\underbrace{g^{-1}(\eta_i)}_{\substack{\text{inverse} \\ \text{link} \\ \text{function}}},\underbrace{\phi}_{\substack{\text{scale} \\ \text{parameter}}}) \\ \underbrace{\boldsymbol \eta}_{\substack{\text{linear} \\ \text{predictor}}} & = \underbrace{\boldsymbol X \boldsymbol \beta}_{\substack{\text{fixed} \\ \text{effects}}} + \underbrace{\boldsymbol Z \boldsymbol b}_{\substack{\text{random} \\ \text{effects}}} \\ \underbrace{\boldsymbol b}_{\substack{\text{conditional} \\ \text{modes}}} & \sim \text{MVN}(\boldsymbol 0, \underbrace{\Sigma(\boldsymbol \theta)}_{\substack{\text{variance-} \\ \text{covariance} \\ \text{matrix}}}) \end{split} $$ ## nonlinear mixed models - same, but use $\boldsymbol X$, $\boldsymbol Z$ to describe fixed and random effect variation *of parameters* (by hand) ## What are random effects/latent variables? A method for … - modeling correlation of different types - accounting for (hypothetical) unobserved variables - group membership (finite mixture models) - activity state (hidden Markov models) - spatial/temporal variation (moving average/CAR/etc.) - compromising between *complete pooling* (no among-block variance) and *fixed effects* (large among-block variance) - handling levels selected at random from a larger population - sharing information among levels (*shrinkage estimation*) - estimating variability among levels - allowing predictions for unmeasured levels ## latent-variable likelihoods - likelihood: $$L(x|\beta,\sigma) = \int L(x|\beta,u) \cdot L(u|\sigma) \, du$$ - likelihood is both *penalized* ($u$ values can't be too spread out) and *integrated* - need: - efficient ways to estimate $\hat u$ (high-dimensional) - reasonable ways to integrate over distribution of $u$ ## shrinkage - consequence of penalization - lower-information groups shrink more - "sharing strength" ## shrinkage: *Arabidopsis* conditional modes ```{r arabshrink,fig.height=6,fig.width=8, message=FALSE} load("../data/Banta.RData") library(plotrix) library(lme4) z<- subset(dat.tf,amd=="clipped" & nutrient=="1") m1 <- glm(total.fruits~gen-1,data=z,family="poisson") m2 <- glmer(total.fruits~1+(1|gen),data=z,family="poisson") tt <- table(z$gen) rr <- unlist(ranef(m2)$gen)[order(coef(m1))]+fixef(m2) m1s <- sort(coef(m1)) m1s[1:2] <- rep(-5,2) gsd <- attr(VarCorr(m2)$gen,"stddev") gm <- fixef(m2) nseq <- seq(-3,6,length.out=50) sizefun <- function(x,smin=0.5,smax=3,pow=2) { smin+(smax-smin)*((x-min(x))/diff(range(x)))^pow } nv <- dnorm(nseq,mean=gm,sd=gsd) ## op <- par(las=1,cex=1.5,bty="l") plot(exp(m1s),xlab="Genotype",ylab="Mean fruit set", axes=FALSE,xlim=c(-0.5,25),log="y",yaxs="i",xpd=NA, pch=16,cex=0.5) axis(side=1) axis(side=2,at=c(exp(-5),0.1,1,10,20), labels=c(0,0.1,1,10,20),cex=0.8) ## ylim=c(-3,5)) polygon(c(rep(0,50),nv*10),exp(c(rev(nseq),nseq)),col="gray",xpd=NA) n <- tt[order(coef(m1))] points(exp(rr),pch=16,col=adjustcolor("red",alpha=0.5), cex=sizefun(n),xpd=NA) ## text(seq_along(rr),rr,n,pos=3,xpd=NA,cex=0.6) box() axis.break(axis=2,breakpos=exp(-4)) legend("bottomright", c("group mean","shrinkage est."), pch=16,pt.cex=c(1,2), col=c("black",adjustcolor("red",alpha=0.5)), bty="n") par(op) ``` ## integration techniques: deterministic - penalized quasi-likelihood (GLMMs) (`nlme`/`MASS`) - Laplace approximation [@madsen_introduction_2011; @peng_advanced_nodate] [link](https://bookdown.org/rdpeng/advstatcomp/laplace-approximation.html#computing-the-posterior-mean): second-order Taylor expansion (`lme4`, `TMB`, `INLA`) - (adaptive) Gauss-Hermite quadrature (`lme4`, `GLMMadaptive`) Fast, flexible, inaccurate $\leftrightarrow$ slow, restrictive, accurate [@biswas2015] ## integration techniques: stochastic - Markov chain Monte Carlo (MCMC) - Gibbs sampling (JAGS, `NIMBLE`) - Hamiltonian Monte Carlo (Stan, `brms`, `rstanarm`, `tmbstan`) - Monte Carlo expectation-maximization (MCEM) (NIMBLE package) <file_sep>--- title: Intro material author: <NAME> date: "`r format(Sys.time(), '%d %B %Y')`" bibliography: ../nonlin.bib --- - introductions - course material: https://github.com/bbolker/quebec_2019 and https://bbolker.github.io/quebec_2019 - data sets - please ask questions! ## focus - "advanced" end users (modelers, not statisticians) - mechanistic rather than phenomenological models (cf. @breiman_statistical_2001) - work with packages when possible ... - ... but ... <!-- or: <div style="width:300px; height:200px"> ... </div> --> ![](pix/dracones-768x384.jpg){width=250px} [Rochester Digital Scholarship lab](https://dslab.lib.rochester.edu/hunt-lenox-globe/) - things used to be simple (`lm`, `glm`, `nlme`, `lme4` ...) - now "let a hundred flowers bloom" (`TMB`, `brms`, `greta`, NIMBLE, ...) ![](pix/Chinese-poster-flowers-smaller.jpg) [<NAME>](http://meuploads.com/2014/08/28/let-hundred-flowers-bloom/) ## outline - likelihood estimation and inference - nonlinear optimization methods - simple MLE examples - latent variables/random effects in nonlinear models - (extended generalized linear mixed models) - complex examples/nonlinear mixed models ![](pix/models-glmm.png) ## tentative schedule - 0830-1000: review of likelihood/inference, optimization methods, parameterization (from a geometric perspective) - 1000-1030: break - 1030-1200: simple examples with `bbmle`/`optim` - 1200-1330: lunch - 1330-1500: latent/mixed models - 1500-1530: break - 1530-1700: advanced examples with `nlmer`/`TMB`/etc. ## references <file_sep>frogs <- emdbook::ReedfrogFuncresp ## predicted number killed with two different rogers_pred <- function(N0, a, h, P, time) { N0 - emdbook::lambertW(a * h * N0 * exp(-a * (P * time - h * N0)))/(a * h) } holling_pred <- function(N0, a, h, P, time) { a*N0*P*time/(1+a*h*N0) } time <- 14 ## time period P <- 3 ## number of predators library(bbmle) plot(Killed ~ Initial, data=frogs) m1 <- mle2(Killed ~ dbinom(size=Initial, prob=holling_pred(Initial, a, h, P, time)/Initial), data=frogs, start=list(a=0.25,h=10)) plot(Killed ~ Initial, data=frogs) with(as.list(coef(m1)), curve(holling_pred(x,a=a,h=h,P=P,time=time), add=TRUE)) <file_sep>--- title: "Data sets" date: "`r format(Sys.time(), '%d %B %Y ')`" bibliography: nonlin.bib --- Data sets can be found [here](https://github.com/bbolker/quebec_2019/tree/master/data) ```{r tab,echo=FALSE} library(pander) x <- read.csv("datasets.csv",check.names=FALSE) pander(x,split.tables=Inf,justify="left") ``` ## References <file_sep>--- title: "Advanced toolboxes for nonlinear optimization" author: <NAME> date: "`r format(Sys.time(), '%H:%M %d %B %Y ')`" bibliography: ../nonlin.bib --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. ```{r pkgs,message=FALSE} library(rstan) library(Deriv) library(TMB) library(emdbook) library(nimble) ``` ## calculating derivatives - by hand (ugh) - `deriv(..., function.args=...)` - returns ```{r} (f1 <- deriv(~ 1/(a+b*exp(-x)), c("a","b"), function.arg=c("a","b","x"))) f1_g <- function(a,b,x) { attr(f1(a,b,x),"grad") } ``` (wasteful but I don't know of a better pattern) The `Deriv` package is much more flexible than the built-in `deriv()` function: allows user-specified rules ```{r} log_dpois_symb <- ~ x*log(lambda)-lambda/lfactorial(x) ## deriv(log_dpois_symb,"lambda") library("Deriv") drule[["dpois"]] <- alist(lambda=x/lambda - 1/lfactorial(x), x=log(lambda)-lambda*-digamma(x+1)/lfactorial(x)^2) Deriv(~dpois(y,1/(1+exp(a+b*x))),c("a","b")) ``` ## automatic differentiation - "magic" algorithm ([Wikipedia](https://en.wikipedia.org/wiki/Automatic_differentiation)) [@griewank_automatic_1989; @griewank_achieving_1992] - computing objective function and **all** derivatives for not much more than just the objective function cost - automated version of the chain rule ```{r} deriv(~x^2+y^2, c("x","y")) ``` ## Laplace approximation - built into TMB - also INLA ## TMB - Template Model Builder - autodiff+Laplace - `compile()` + `dyn.load()` + `MakeADFun()` + optimize ## TMB challenges - installing compilation tools - vectorization or not? - parameter types --- ![](pix/TMB_components.png) # Tadpoles in TMB ```{r} writeLines(con="tadpole1.cpp", "// Tadpole example #include <TMB.hpp> // next two lines are magic template<class Type> Type objective_function<Type>::operator() () { DATA_VECTOR(Initial); DATA_VECTOR(Killed); PARAMETER(a); // scalar parameters PARAMETER(h); Type nll = 0; // negative log-likelihood for (int i=0; i < Killed.size(); i++) { nll -= dbinom(Killed(i), Initial(i), a/(1+a*h*Initial(i)), true); } return nll; } ") ``` - [TMB documentation for probability distributions](https://kaskr.github.io/adcomp/group__R__style__distribution.html) (`dbinom`, `dnorm`, ...) - [TMB convenience functions](http://kaskr.github.io/adcomp/convenience_8hpp.html) (`invlogit`) ```{r compile,cache=TRUE} compile("tadpole1.cpp") ``` ```{r} dyn.load(dynlib("tadpole1")) data(ReedfrogFuncresp) obj <- MakeADFun(data=as.list(ReedfrogFuncresp), parameters=list(a=1, h=1), DLL="tadpole1") ## try out function and gradient obj$fn(a=1,h=1) obj$gr(a=1,h=1) res <- do.call("optim",obj) ## could also use nlminb etc. nlminb(start=obj$par,objective=obj$fn,gradient=obj$gr) ``` Inference: ```{r eval=FALSE} vv <- sdreport(obj)$cov.fixed sds <- sqrt(diag(vv)) tmbprofile(obj,"a") tmbroot(obj,"a") ``` **exercise**: ## Stan Stan [function reference](https://mc-stan.org/docs/2_18/functions-reference/) ```{r show_stanmodel,echo=FALSE} cat(readLines("tadpole.stan")) ``` ```{r build_stan,cache=TRUE} m <- stan_model(file = "tadpole.stan", model_name = "tadpole") ``` ```{r fit_stan} fit <- optimizing(m, data = c(as.list(ReedfrogFuncresp), N= nrow(ReedfrogFuncresp))) ``` ## NIMBLE ```{r cache=TRUE,message=FALSE} hollingprob <- nimbleFunction( run = function(x = integer(1), x0=integer(1), a = double(), h = double()) { returnType(double()) return(-sum(dbinom(x, prob=a/(1+a*h*x0), size=x0, log=TRUE))) }) with(ReedfrogFuncresp,hollingprob(Killed, Initial, a=0.01,h=1)) cc <- compileNimble(hollingprob, showCompilerOutput=TRUE) with(ReedfrogFuncresp,cc(Killed, Initial, a=0.01,h=1)) ``` ## other choices - [greta](https://greta-stats.org/): R -> Tensorflow interface. Hamiltonian Monte Carlo only - [NIMBLE](https://r-nimble.org/): modeling language -> MCMC, particle filtering, - [Rcpp](http://www.rcpp.org/): C++ in R; make objective function faster ... <file_sep>library(emdbook) data(ReedfrogFuncresp) ?ReedfrogFuncresp head(ReedfrogFuncresp) plot(Killed~Initial,data=ReedfrogFuncresp) plot(Killed/Initial~Initial,data=ReedfrogFuncresp, ylab="fraction killed") NLLfun <- function(p) { a <- p[1] h <- p[2] prob <- a/(1+a*h*ReedfrogFuncresp$Initial) prob <- pmin(prob, 0.999) lik <- dbinom(ReedfrogFuncresp$Killed, prob=prob, size = ReedfrogFuncresp$Initial) nll <- -sum(log(lik)) ## cat(a,h,nll,max(prob),"\n") return(nll) } options(warn=1) p0 <- c(a=0.5,h=0.03) NLLfun(p0) opt1 <- optim(fn=NLLfun, par=p0, method="L-BFGS-B", lower=c(0.01,0.01), hessian=TRUE) v <- solve(opt1$hessian) ## Wald var-cov matrix sqrt(diag(v)) library(bbmle) parnames(NLLfun) <- c("a","h") opt2 <- mle2(NLLfun,start=p0,vecpar=TRUE) coef(opt2) vcov(opt2) prof <- profile(opt2) plot(prof,show.points=TRUE) confint(prof) confint(opt2,method="quad") NLLfun2 <- function(p) { a <- p[1] h <- p[2] prob <- a/(1+a*h*Initial) prob <- pmin(prob, 0.999) nll <- -sum(dbinom(Killed, prob=prob, size = Initial, log=TRUE)) ## cat(a,h,nll,max(prob),"\n") return(nll) } parnames(NLLfun2) <- c("a","h") opt2 <- mle2(NLLfun2,start=p0,vecpar=TRUE, data=ReedfrogFuncresp) opt3 <- mle2(Killed ~ dbinom(size=Initial, prob=a/(1+a*h*Initial)), ## MUST USE initial parameters as list, not vector, here! start=as.list(p0), data=ReedfrogFuncresp) predict(opt3) simulate(opt3) simulate(opt3) nboot <- 200 set.seed(101) m <- matrix(NA,nrow=nboot,ncol=2) for (i in 1:nboot) { bootdata <- ReedfrogFuncresp[sample(nrow(ReedfrogFuncresp),replace=TRUE), ] bootfit <- update(opt2, data=bootdata) m[i,] <- coef(bootfit) } ## parametric bootstrap set.seed(101) m_par <- matrix(NA,nrow=nboot,ncol=2) for (i in 1:nboot) { ss <- simulate(opt3) bootdata <- transform(ReedfrogFuncresp,Killed=ss) suppressWarnings(bootfit <- update(opt3, data=bootdata)) m_par[i,] <- coef(bootfit) } plot(m[,1],m[,2]) points(m_par[,1],m_par[,2], col="blue") t(apply(m, MARGIN=2, FUN=quantile, c(0.025,0.975))) <file_sep>--- title: "Nonlinear mixed models" author: <NAME> date: "`r format(Sys.time(), '%H:%M %d %B %Y ')`" bibliography: ../nonlin.bib --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. ## Nonlinear mixed models - **Gaussian** response (i.e., not generalized) ## nlme package: advantages - well-established, stable - reasonably well-documented [@pinheiro_mixed-effects_2000] - flexible heteroscedasticity models (`weights` argument) - residual correlation/R-side effects (`correlation` argument) ## nlme: disadvantages - Gaussian responses only - relatively slow - crossed effects are hard ## lme4::nlmer - **in principle** way better - nonlin function needs derivatives provided - fixed effects are **hard** to incorporate (need to write the function yourself, or hack the output of `derivs`) <file_sep>load("vonesh_slice_dat.rda") png("vonesh_slice.png") op <- par(cex=1.5,mgp=c(2.5,1,0),las=1,lwd=2,bty="l") plot(slice2,type="l",ylab="Negative log-likelihood",xlab="") ## plot(slice2,type="l",ylab="Negative log-likelihood",xlab="",ylim=c(0,20)) points(0,-logLik(mle_logist2)) points(1,-logLik(mle_logist2C)) ##abline(h=-logLik(mle_logist2C)) abline(h=-logLik(mle_logist2C)) abline(h=-logLik(mle_logist2C)+qchisq(0.95,1)/2,lty=2) par(mar=c(2,2,0,0),bty="l",cex=0.7,lwd=1, mgp=c(1,0,0)) par(new=TRUE,fig=c(0.22,0.50,0.55,0.85)) plotrix::sizeplot(ReedfrogSizepred$TBL,ReedfrogSizepred$Kill, xlim=c(5,30),ylim=c(-0.4,10),axes=FALSE, xlab="size",ylab="killed",cex.lab=1.5) with(as.list(coef(mle_logist2)),curve(logist2(x,sizep1,sizep2,sizep3)*10,add=TRUE,lwd=2)) box() par(new=TRUE,fig=c(0.7,0.98,0.55,0.85)) plotrix::sizeplot(ReedfrogSizepred$TBL,ReedfrogSizepred$Kill, xlim=c(5,30),ylim=c(-0.4,10),axes=FALSE, xlab="size",ylab="killed",cex.lab=1.5) with(as.list(coef(mle_logist2C)),curve(logist2(x,sizep1,sizep2,sizep3)*10,add=TRUE,lwd=2)) box() par(op) dev.off() <file_sep>--- title: "Setup for nonlinear fitting master class" --- 1. Please make sure you have a **recent** version of R installed from [CRAN](https://cran.r-project.org/) (the latest version, 3.6.0, would be best; if you need to use a version older than 3.5, please let me know in advance). 2. The RStudio interface is strongly recommended; you can download it [here](https://www.rstudio.com/products/rstudio/download/) (get the free Desktop version). 3. Install primary fitting packages (and a variety of extras). Note that this list deliberately takes an [everything-but-the-kitchen-sink](https://en.wiktionary.org/wiki/everything_but_the_kitchen_sink#English) approach, since it will save time to have everything you might want installed in advance. If you have questions or problems, please contact me before the workshop. ```{r pkg1,eval=FALSE} ## modeling packages mod_pkgs <- c("alabama", "bbmle", "brms", "DEoptim", "Deriv", "dfoptim", "glmmTMB", "lme4", "maxLik", "minpack.lm", "minqa", "nimble", "nloptr", "nls2", "nlshelper", "nlstools", "nls.multstart", "numDeriv", "optimx", "RcppNumerical", "repeated", "subplex", "TMB") ## miscellaneous/data manipulation data_pkgs <- c("benchmark", "devtools", "emdbook", "pkgbuild", "plyr", "reshape2", "tidyverse") ## graphics graph_pkgs <- c("cowplot", "directlabels", "dotwhisker", "GGally", "ggalt", "ggplot2", "ggpubr", "ggstance", "gridExtra", "plotrix", "viridis") all_pkgs <- c(mod_pkgs,data_pkgs,graph_pkgs) avail_pkgs <- rownames(available.packages()) already_installed <- rownames(installed.packages()) to_install <- setdiff(all_pkgs,already_installed) if (length(to_install)>0) { install.packages(to_install,dependencies=TRUE) } ``` There is no need to (re)install packages such as `grid`, `nlme`, `MASS`, `mgcv`, as they come with a standard R installation. 4. Various advanced optimization tools such as [TMB](https://github.com/kaskr/adcomp), [Stan](https://mc-stan.org/), and [NIMBLE](https://r-nimble.org/) need compilers installed as well: - Windows: download Rtools from [here](https://cran.r-project.org/bin/windows/Rtools/) - MacOS: install Xcode; on recent versions of MacOS you need to open a Terminal, type `xcode-select --install` and then click "Install" and "Agree". (If you have an older version or want more details see [here](https://www.moncefbelyamani.com/how-to-install-xcode-homebrew-git-rvm-ruby-on-mac/); you only need to do "Step 1" of these instructions.) - Linux: make sure you have `gcc`/`g++` installed Also see [Checking the C++ toolchain](https://github.com/stan-dev/rstan/wiki/RStan-Getting-Started) from the Stan installation instructions. (Run `pkgbuild::has_build_tools(debug=TRUE)`.) ## TMB test Please check that the following code runs without an error on your system: if it doesn't, please send me an e-mail (`bbolker at gmail.com`) with the error message pasted in to the body of the message. ```{r TMB,eval=FALSE} library(TMB) writeLines(con="test.cpp", "#include <TMB.hpp> template<class Type> Type objective_function<Type>::operator() () { DATA_VECTOR(y); PARAMETER(mu); Type nll = -sum(dnorm(y, mu, 1, true)); return nll; } ") compile("test.cpp") ``` --- Last updated: `r Sys.time()` <file_sep>--- title: "Fitting challenges" author: <NAME> date: "`r format(Sys.time(), '%H:%M %d %B %Y ')`" bibliography: ../nonlin.bib --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. # challenges & solutions ## errors/problems optimization simply crashes due to: - predictions outside of feasible range (counts <0, prob outside of (0,1)) - underflow/overflow - convergence to extreme/flat ranges (`L-BFGS-B` is particularly non-robust) ## improve objective function - check for bugs! - use more robust expressions - compute on log scale if possible - `1/(1+exp(-x))` (or `plogis(x)`) rather than `exp(x)/(1+exp(x))` - use `lower.tail=` for tail probabilities - "clamping": impose minima/maxima to avoid over/underflow (e.g. see `make.link("cloglog")$linkinv`) - evaluate expressions in limits ## better starting conditions - better understanding of problem - neutral values (e.g. $\beta=0$ for linear-like models) - build up fit from less complex/reduced models - heuristic *self-starting* algorithms to find starting values `apropos("^SS[a-z]",ignore.case=FALSE)` ([link](https://github.com/wch/r-source/blob/5a156a0865362bb8381dcd69ac335f5174a4f60c/src/library/stats/R/zzModels.R#L306-L325), [code](SSfpl.R)) ## convergence warnings - always check `$convergence` (`$status` in `nloptr`)! `optim()` doesn't automatically report - from optimization algorithm (internal): e.g. see `?optim`, or this SO post on the [infamous nlminb "false convergence" warning](https://stackoverflow.com/questions/40039114/r-nlminb-what-does-false-convergence-actually-mean) ## KKT (Kuhn-Karush-Tucker) conditions - first and second order conditions for "nonlinear programming", i.e. nonlin optimization with constraints ([Wikipedia](https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions)) - `optextras::kktchk()` - unconstrained: simplifies to gradient=0, Hessian=positive definite (for minimization) ## lme4 warnings - "toast-scraping" (see [here](https://stat.ethz.ch/pipermail/r-sig-mixed-models/2018q2/026756.html)) - generally identifies less-stable problems (grad>0.1 is often a problem) - not many solutions other than scaling, centering, trying other optimizers ## lots of parameters (high dimensionality) - not really an intrinsic problem - hard to visualize - slow ## visualization - slices - `expand.grid()` plus ggplot (`geom_tile()` + `facet_grid()` works up to 4D: maybe `ggforce::facet_grid_paginate()` if you're crazy) ![](pix/vonesh_slice.png) ![](pix/vonesh_surface2.png) ## slowness - @ross_faster_2013 [link](http://www.noamross.net/blog/2013/4/25/faster-talk.html): - rewrite in C++ - parallelize (hard in this case) ## discontinuities and thresholds - Nelder-Mead - profiling across discrete values general approach for any "difficult" parameter, e.g. $t$ degrees of freedom ## multi-modality - can be very hard to tell (Simon Wood examples) - check convergence - KKT criteria, locally - multi-start algorithms - random - Latin hypercube - Sobol sequences - cumulative distribution of neg log likelihoods [@raue_lessons_2013] - stochastic global optimization ## constraints (box) - independent inequality constraints - built into some optimizers (`optim/L-BFGS-B`, `nloptr` tools) - transformations - convenient; can also improve Wald approximation, improve scaling - bad if parameter is actually *on* the boundary - e.g. negative binomial parameter: var=$\mu(1+\mu/k)$. Often use $\log(k)$ to keep it positive, but what if equi/underdispersed? Use $1/k$ with lower bound at 0? ## parameterization - mathematically pretty: $ax/(1+bx)$ - simpler units: $ax/(1+x/c)$ - traditional: $ax/(1+ahx)$ - separate features: $ax/(1+(a/d)x)$, $d>0$ ## references <file_sep>dd <-read.csv("../height_diameter.csv",header=TRUE,sep=";") library(ggplot2); theme_set(theme_bw()) ggplot(dd,aes(dbh_cm,height_h,group=interaction(plot_id,tree_id)))+ stat_binhex(aes(group=1))+ geom_line(alpha=0.1,col="red") ## Chapman-Richards: y*(1-exp(-kt)^p nls(height_h ~ hmax*(1-exp(-dbh_cm/exp(logr))), start=list(hmax=20, logr=1), data=dd) nls(height_h ~ hmax*(1-exp(-dbh_cm/exp(logr)))^p, start=list(hmax=20, logr=2.7,p=1), data=dd) library(nlme) ## https://stackoverflow.com/questions/36205261/error-in-pars-nm-incorrect-number-of-dimensions m0 <- nlme(height_h ~ hmax*(1-exp(-dbh_cm/exp(logr))), fixed=list(hmax+logr~1), random=hmax~1|plot_id/tree_id, start=c(hmax=22, logr=2.7), data=dd) m1 <- nlme(height_h ~ hmax*(1-exp(-dbh_cm/exp(logr)))^p, fixed=list(hmax+logr+p~1), random=hmax~1|plot_id/tree_id, start=c(hmax=22, logr=2.7,p=1), data=dd) m2 <- nlme(height_h ~ hmax*(1-exp(-dbh_cm/exp(logr)))^p, fixed=list(hmax+logr+p~1), random=hmax+logr+p~1|plot_id/tree_id, start=c(hmax=22, logr=2.7,p=1), data=dd) library(lme4) ff <- deriv(~ hmax*(1-exp(-dbh_cm/exp(logr)))^p, c("hmax","logr","p"), function.arg=c("dbh_cm","hmax","logr","p")) ## m3 <- nlmer(height_h ~ ff(dbh_cm,hmax,logr,p) ~ logr | plot_id/tree_id, ## start=c(hmax=22, logr=2.7,p=1), ## data=dd, ## control=nlmerControl(optimizer=nloptwrap), ## verbose=1) <file_sep>--- title: (Non)linearity author: <NAME> date: "`r format(Sys.time(), '%d %B %Y')`" --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. ## What is a "nonlinear" model? - a model whose objective function (usu. likelihood) *cannot* be expressed as a linear function of predictors ($\beta_0 + \beta_1 x_1 + \beta_2 x_2$ ...) ## What's so good about linear models? - solution by linear algebra, rather than iteration - *generalized* linear models - *iterative* linear algebra (IRLS: @kane_glms_2016, @arnold_computational_2019) - guarantees: - performance - convergence - unimodal, *log-quadratic* likelihoods - no hyperparameter tuning - no tests for convergence - no need to pick starting values - robust to parameter scaling and correlation - interpretability - convenient framework for covariates/interactions/etc. ## what does "linear" include? - additive models (splines for general smooth continuous functions) - linearization tricks - e.g. generalized Ricker: $y = a^b x e^{cx} \to \log(y) = \log(a) + b \log(x) + c x$ - Michaelis-Menten: $y = ax/(b+x) \to 1/y = (b/a) (1/x) + (1/a)$ - power-law (allometric) fitting: $y=ax^b \to \log(y) = a + b \log(x)$ - borderline: - generalized least squares - generalized linear models (link function) - (G)L mixed models ## Nonlinear models - everything else - "nonlinear" $\leftrightarrow$ most zoology = the study of non-elephant animals (Ulam) - many methods use *locally* linear approaches (gradient descent; Newton) - today's class focuses on less-canned/one-off solutions ## Simple examples - power-law curves (if additive: $y=ax^b$ can be linearized) - logistic curves, unknown asymptote ($K$, or prob <1), and generalizations (e.g. Richards equation) - simple movement models (log-Normal step length/von Mises turning angle) - saturating curves (functional responses: Holling/Rogers equation) ## Harder examples - trajectory-matching ODEs - seed shadow models - mixture models ## Special-case toolboxes Many classes of problems have special algorithms that linearize or otherwise solve most of the problem, then solve a *low-dimensional* nonlinear optimization problem - Kalman filtering - hidden Markov models (Viterbi algorithm) - linear mixed models - generalized linear (mixed) models (IRLS/penalized IRLS+Laplace/quadrature) - generalized least-squares - mixture models via expectation-maximization - capture-mark-recapture data - machine learning (neural networks, random forests, ...) ## General advice - simplify problem expression - use most efficient algorithms - good starting values (more later) <file_sep>--- title: "glmmTMB" author: <NAME> date: "`r format(Sys.time(), '%d %B %Y ')`" --- ![cc](pix/cc-attrib-nc.png) Licensed under the [Creative Commons attribution-noncommercial license](http://creativecommons.org/licenses/by-nc/3.0/). Please share \& remix noncommercially, mentioning its origin. ```{r pkgs, echo=FALSE,message=FALSE} library(glmmTMB) library(broom.mixed) ``` ## what does it do? - extended generalized linear mixed models - arbitrarily many, crossed random effects - zero-inflation, with fixed and random covariates - wide range of distributions (beta-binomial, Beta, COM-Poisson, generalized Poisson ...) - dispersion model (fixed covariates) - spatial and temporal correlations (new!) ## how does it work? - a flexible (pre-compiled) TMB file - data processing done in R, then passed to TMB ## speed (negative binomial model) ![](pix/bigfit1.png) ![](pix/bigfit2.png) ## example ```{r owls,message=FALSE} library(glmmTMB) data("Owls", package="glmmTMB") owls_nb1 <- glmmTMB(SiblingNegotiation ~ FoodTreatment*SexParent + (1|Nest)+offset(log(BroodSize)), family = nbinom1(), zi = ~FoodTreatment, data=Owls) summary(owls_nb1) tidy(owls_nb1) ``` ## what to worry about? - less graceful with singular fits than `lme4` - only does generalized *linear* mixed models
7a416e31705b8f1ae6ec940a3cf61973d3d0b066
[ "Markdown", "R", "RMarkdown" ]
22
Markdown
bbolker/quebec_2019
080d12d54dc33e97e5721d7990ec7ca377e4d0fe
d5c5e2c81618ebf8e2b27fe9304781509a4bceda
refs/heads/master
<repo_name>TheGreatRambler/Some_Mods<file_sep>/README.md # Some_Mods Some Minecraft mods, may eventually make some TODO use this https://www.spigotmc.org/wiki/creating-a-blank-spigot-plugin-in-vs-code/<file_sep>/Accelerate/AccelerateInfinitely/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion> 4.0.0 </modelVersion> <groupId> com.tgrcode.accelerateinfinitely </groupId> <artifactId> AccelerateInfinitely </artifactId> <version> 0.0.1 </version> <packaging> jar </packaging> <properties> <project.build.sourceEncoding> UTF-8 </project.build.sourceEncoding> <maven.compiler.source> 1.8 </maven.compiler.source> <maven.compiler.target> 1.8 </maven.compiler.target> </properties> <repositories> <repository> <id> spigot-repo </id> <url> https://hub.spigotmc.org/nexus/content/repositories/snapshots/ </url> </repository> </repositories> <dependencies> <dependency> <groupId> org.spigotmc </groupId> <artifactId> spigot-api </artifactId> <version> 1.14.4-R0.1-SNAPSHOT </version> <scope> provided </scope> </dependency> </dependencies> <build> <sourceDirectory> ${project.basedir}/src/main/java </sourceDirectory> <finalName> AccelerateInfinitely </finalName> <resources> <resource> <directory> ${project.basedir}/src/main/resources </directory> <includes> <include> plugin.yml </include> </includes> </resource> </resources> </build> </project> <file_sep>/Accelerate/AccelerateInfinitely/src/main/java/com/tgrcode/accelerateinfinitely/App.java package com.tgrcode.accelerateinfinitely; import org.bukkit.Bukkit; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.util.*; public class App extends JavaPlugin implements Listener { private enum AccelType { FORWARDS, BACKWARDS, DISABLED, } private float initialSpeed = 0.2f; private float speedMultiplier = 1.01f; private float currentSpeed = initialSpeed; private AccelType type = AccelType.FORWARDS; private int tickDelayAllowed = 5; private int currentTickDelay = 0; @Override public void onEnable() { getLogger().info("Accelerate Infinitely enabled"); getServer().getPluginManager().registerEvents(this, this); // getCommand("setaccel").setExecutor(this); // getCommand("setmultiplieraccel").setExecutor(this); Bukkit.getServer().getScheduler().runTaskTimer(this, new Runnable() { @Override public void run() { if(type != AccelType.DISABLED) { for(Player player : Bukkit.getServer().getOnlinePlayers()) { if(player.isOnGround() || !player.isSprinting()) { if(currentTickDelay < tickDelayAllowed) { currentTickDelay++; } else { currentSpeed = initialSpeed; } } else { if(type == AccelType.FORWARDS) { Vector targetVelocity = player.getLocation().getDirection().multiply(currentSpeed); // Don't modify the Y velocity targetVelocity.setY(player.getVelocity().getY()); player.setVelocity(targetVelocity); currentSpeed *= speedMultiplier; currentTickDelay = 0; } } } } } }, 20L, 1L); } @Override public void onDisable() { getLogger().info("Accelerate Infinitely disabled"); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(command.getName().equals("setaccel")) { if(label.equals("forwards")) { type = AccelType.FORWARDS; } else if(label.equals("backwards")) { type = AccelType.BACKWARDS; } else if(label.equals("disabled")) { type = AccelType.DISABLED; } } else if(command.getName().equals("setmultiplieraccel")) { speedMultiplier = Float.parseFloat(label); } return true; } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { /* if(event.getPlayer().isSprinting()) { if(type == AccelType.FORWARDS) { Vector movementVec = event.getPlayer().getVelocity(); event.getPlayer().setVelocity(movementVec.multiply(multiplier)); } } */ } @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { event.getPlayer().setFlying(false); } private Vector yawToVector(float yaw) { // Pitch is always 0 double pitchRadians = Math.toRadians(0); double yawRadians = Math.toRadians(yaw); double sinPitch = Math.sin(pitchRadians); double cosPitch = Math.cos(pitchRadians); double sinYaw = Math.sin(yawRadians); double cosYaw = Math.cos(yawRadians); return new Vector(-cosPitch * sinYaw, sinPitch, -cosPitch * cosYaw); } }
a5401e5fa9b9ae5b71c896f39fce1bc0c88d6448
[ "Markdown", "Java", "Maven POM" ]
3
Markdown
TheGreatRambler/Some_Mods
a2119082a01543a707f4ced4403c4553aaac1eab
56f3a90e605bedafbfe48b40c9d59f9bb2dcbd18
refs/heads/master
<repo_name>subo23/SampleJobAppForm<file_sep>/send.php <?php $firstname = $_POST["firstname"]; $lastname = $_POST["lastname"]; $email = $_POST["email"]; $gender = $_POST["optGender"]; $country = $_POST["selCountry"]; echo $firstName; echo $lastname; echo $email; echo $gender; echo $country; ?> <file_sep>/email.php <?php $firstName = $_POST["firstname"]; $lastName = $_POST["lastname"]; $email = $_POST["email"]; $gender = $_POST["optGender"]; $country = $_POST["selCountry"]; $to = $email; $subject = "Test Job Application Form"; $message = " <html> <head> <title>Sample Job Application Email</title> </head> <body> <table> <tr> <th>Firstname</th> <th>Lastname</th> <th>Gender</th> <th>Country</th> </tr> <tr> <td>". $firstName ."</td> <td>". $lastName ."</td> <td>". $gender ."</td> <td>". $country ."</td> </tr> </table> </body> </html> "; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; $headers .= 'Cc: <EMAIL>' . "\r\n"; mail($to,$subject,$message,$headers); ?>
b5dbb853337a342e0e9be4360e486a63e8ec2d84
[ "PHP" ]
2
PHP
subo23/SampleJobAppForm
2f8c6999fba0ff00cbca334c5c97141300ec2b0e
2eaa67253cfa780f64ea1acc360173bcc6fc1926
refs/heads/master
<repo_name>wangdong8500/BinomialTree<file_sep>/main.cpp #include <iostream> #include <cmath> #include "Tree.h" #include <unordered_map> #include "Date.h" #include <chrono> //for accurate multithreading time using std::chrono /*Black Scholes drift and Put payoffs */ double alpha(double t, double x, double sig, double alph){ return alph/sig; //alpha/sigma } double sigma(double t, double x, double sig){ return sig; //sigma'(x) } double payoff(double x, double k){ if(k>x){ return k-x; } else{ return 0; } } double discount(double t, double x, double dt, double r){ return exp(-r*dt); } double finv(double x, double sig){ return exp(sig*x)/sig; } /*End Black Scholes */ /*Begin interest rate "option" (bond pricing) assuming CIR underlying*/ double alphaR(double t, double x, double a, double b, double sig){ return (a*(b-x))/(sig*sqrt(x)); } double sigmaR(double t, double x, double sig){ return (.5*sig)/sqrt(x); } double payoffR(double x){ return 1; } double discountR(double t, double x, double dt){ return exp(-x*dt); } double finvR(double x, double sig){ return sig*sig*x*x*.25; } /*End interest rate "option" */ int main(){ //double alph=.1; int m=1000; /*Black Scholes drift and Put payoffs: Bermudan option*/ int numDates; std::vector<Date> timeCanExercise; //last value includes experiation date std::unordered_map<int, bool> exercise; timeCanExercise.push_back("2/4/2015"); timeCanExercise.push_back("3/15/2015"); timeCanExercise.push_back("4/1/2015"); timeCanExercise.push_back("6/8/2015"); timeCanExercise.push_back("9/1/2015"); Date startDate="1/1/2015"; numDates=timeCanExercise.size(); std::vector<double> diffDates(numDates); for(int i=0; i<numDates;i++){ timeCanExercise[i].setScale("year"); diffDates[i]=timeCanExercise[i]-startDate; std::cout<<diffDates[i]<<std::endl; exercise.insert({{(int)(m*diffDates[i]), true}}); } /*End Black Scholes bermudan */ double sig=.3; double k=50; double stockPrice=log(50*sig)/sig; //std::cout<<stockPrice<<std::endl; double r=.03; double initialR=2.0*sqrt(r)/sig; double t=diffDates[numDates-1]; double a=1; double b=.05;//long run r; /*Tree for BS*/ Tree treeBS(m, t, stockPrice, true);//american Tree treeBSE(m, t, stockPrice);//European Tree treeBSBermudan(m, t, stockPrice, exercise);//bermudan Tree treeCIR(m, t, initialR);//european treeBS.execute([&](double t, double x){return alpha(t, x, sig, r);}, [&](double t, double x){return sigma(t, x, sig);}, [&](double x){return finv(x, sig);}, [&](double x){return payoff(x, k);}, [&](double t, double x, double dt){return discount(t, x, dt, r);}); //ALPHA&& alpha, SIGMA&& sigma, FINV&& fInv, PAYOFF&& payoff, DISCOUNT&& discount treeBSBermudan.execute([&](double t, double x){return alpha(t, x, sig, r);}, [&](double t, double x){return sigma(t, x, sig);}, [&](double x){return finv(x, sig);}, [&](double x){return payoff(x, k);}, [&](double t, double x, double dt){return discount(t, x, dt, r);}); //ALPHA&& alpha, SIGMA&& sigma, FINV&& fInv, PAYOFF&& payoff, DISCOUNT&& discount treeBSE.execute([&](double t, double x){return alpha(t, x, sig, r);}, [&](double t, double x){return sigma(t, x, sig);}, [&](double x){return finv(x, sig);}, [&](double x){return payoff(x, k);}, [&](double t, double x, double dt){return discount(t, x, dt, r);}); //ALPHA&& alpha, SIGMA&& sigma, FINV&& fInv, PAYOFF&& payoff, DISCOUNT&& discount /*Tree for bond pricing */ auto start = std::chrono::system_clock::now(); treeCIR.execute([&](double t, double x){return alphaR(t, x, a, b, sig);}, [&](double t, double x){return sigmaR(t, x, sig);}, [&](double x){return finvR(x, sig);}, [&](double x){return payoffR(x);}, [&](double t, double x, double dt){return discountR(t, x, dt);}); //ALPHA&& alpha, SIGMA&& sigma, FINV&& fInv, PAYOFF&& payoff, DISCOUNT&& discount auto end=std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()-start); std::cout<<"Time it took: "<<end.count()/1000.0<<std::endl; std::cout<<treeBSBermudan.getPrice()<<std::endl; std::cout<<treeBSE.getPrice()<<std::endl; std::cout<<treeBS.getPrice()<<std::endl; std::cout<<treeCIR.getPrice()<<std::endl; } <file_sep>/zzzTree.cpp #include "Tree.h" Tree::Tree(int m_, double t, double x0_){ m=m_; maturity=t; dt=t/((double)m-1.0); optionPrice=std::vector<double>(m); x0=x0_; //exerciseNodes(m, 0);//default to all zero } Tree::Tree(int m_, double t, double x0_, std::unordered_map<int, bool> &exercise){ m=m_; maturity=t; dt=t/((double)m-1.0); exerciseNodes=exercise; optionPrice=std::vector<double>(m); x0=x0_; } Tree::Tree(int m_, double t, double x0_, bool isAmerican){ m=m_; maturity=t; dt=t/((double)m-1.0); if(isAmerican){ for(int i=0; i<m; i++){ exerciseNodes.insert({{i, true}}); } } optionPrice=std::vector<double>(m); x0=x0_; } double Tree::getPrice(){ return finalValue; } //double Tree::computeP(double x){ //} <file_sep>/Tree.h #ifndef __TREE_H_INCLUDED__ #define __TREE_H_INCLUDED__ #include <iostream> #include <cmath> #include <unordered_map> #include <vector> template<typename Number> auto computeTree( auto&, //function(t, x) for the drift ->alpha=alpha/sigma auto&, //function(t, x) for the volatility->sigma=sigma'(x) auto&, //inverse of the function g=\int 1/sig(x) dx auto&, //payoff function(x) auto&, //discount function(t, x, dt) int, //number of nodes double, //time Number&, //current value std::unordered_map<int, bool>& //nodes to exercise at ); template<typename Number> auto computeTree( auto&, //function(t, x) for the drift ->alpha=alpha/sigma auto&, //function(t, x) for the volatility->sigma=sigma'(x) auto&, //inverse of the function g=\int 1/sig(x) dx auto&, //payoff function(x) auto&, //discount function(t, x, dt) int, //number of nodes double, //time Number& //current value ); #include "Tree.hpp" #endif<file_sep>/zzzTree.h #ifndef __TREE_H_INCLUDED__ #define __TREE_H_INCLUDED__ #include <iostream> #include <cmath> #include <unordered_map> #include <vector> class Tree{ //simulates SDE of type dX=alpha(t, X)dt+sigma(t, X)dW...I think I need to figure out dividends! private: int m;//number of steps double maturity;//maturity in years double dt; double x0; double finalValue; int numberOfPChanged=0; std::unordered_map<int, bool> exerciseNodes; std::vector<double> optionPrice; public: Tree(int, double, double); Tree(int, double, double, std::unordered_map<int, bool>&); //include exercise nodes...use this in conjuctions with a date module! Tree(int, double, double, bool);//american or not template< typename ALPHA, typename SIGMA, typename FINV, typename PAYOFF, typename DISCOUNT> void execute(ALPHA&& alpha, SIGMA&& sigma, FINV&& fInv, PAYOFF&& payoff, DISCOUNT&& discount){ //alpha=alpha/sigma,sigma=sigma'(x), finv=the inverse of the function g=\int 1/sig(x) dx double p=0; double t=(m-1)*dt; double alph; double sig; //double underlyingX=0; double intrinsic=0; int mm=m; double sqrtDt=sqrt(dt); for(int i=0; i<mm; i++){ auto underlyingX=fInv(x0+sqrtDt*(mm-1-2*i)); optionPrice[i]=payoff(underlyingX); } mm--; for(int j=(m-2); j>=0; j--){ t=j*dt; for(int i=0; i<mm; i++){ underlyingX=fInv(x0+sqrtDt*(mm-1-2*i)); alph=alpha(t, underlyingX); sig=sigma(t, underlyingX); p=(alph-sig*.5)*.5*sqrtDt+.5; if(p>1){ p=1; numberOfPChanged++; } else if(p<0){ p=0; numberOfPChanged++; } optionPrice[i]=(p*optionPrice[i]+(1-p)*optionPrice[i+1])*discount(t, underlyingX, dt); if(exerciseNodes.find(i)!=exerciseNodes.end()){ //if the key exists if(exerciseNodes.at(i)){ //if the option can be exercised intrinsic=payoff(underlyingX); if(optionPrice[i]<intrinsic){ optionPrice[i]=intrinsic; } } } } optionPrice.pop_back(); mm--; } finalValue=optionPrice[0]; } double getPrice(); }; #endif <file_sep>/Tree.hpp //template< typename ALPHA, typename SIGMA, typename FINV, typename PAYOFF, typename DISCOUNT> template<typename Number> auto computeTree(auto& alpha, auto& sigma, auto& fInv, auto& payoff, auto& discount, int m, double t, const Number& x0, std::unordered_map<int, bool>& exerciseNodes){ //alpha=alpha/sigma,sigma=sigma'(x), finv=the inverse of the function g=\int 1/sig(x) dx //double t=(m-1)*dt; double dt=t/(m-1); std::vector<Number> optionPrice(m); int mm=m; double sqrtDt=sqrt(dt); for(int i=0; i<mm; i++){ auto underlyingX=fInv(t, x0+sqrtDt*(mm-1-2*i), dt, mm); optionPrice[i]=payoff(t, underlyingX, dt, mm); } mm--; for(int j=(m-2); j>=0; j--){ t=j*dt; for(int i=0; i<mm; i++){ auto underlyingX=fInv(t, x0+sqrtDt*(mm-1-2*i), dt, mm); auto alph=alpha(t, underlyingX, dt, mm); auto sig=sigma(t, underlyingX, dt, mm); auto p=(alph-sig*.5)*.5*sqrtDt+.5; if(p>1){ p=1; //numberOfPChanged++; } else if(p<0){ p=0; //numberOfPChanged++; } optionPrice[i]=(p*optionPrice[i]+(1-p)*optionPrice[i+1])*discount(t, underlyingX, dt, mm); if(exerciseNodes.find(i)!=exerciseNodes.end()){ //if the key exists if(exerciseNodes[i]){ //if the option can be exercised auto intrinsic=payoff(t, underlyingX, dt, mm); if(optionPrice[i]<intrinsic){ optionPrice[i]=intrinsic; } } } } optionPrice.pop_back(); mm--; } return optionPrice[0]; } template<typename Number> //american option auto computeTree(auto& alpha, auto& sigma, auto& fInv, auto& payoff, auto& discount, int m, double t, const Number& x0){ //alpha=alpha/sigma,sigma=sigma'(x), finv=the inverse of the function g=\int 1/sig(x) dx double dt=t/(m-1); std::vector<Number> optionPrice(m); int mm=m; // int numberOfPChanged=0; double sqrtDt=sqrt(dt); for(int i=0; i<mm; i++){ Number underlyingX=fInv(t, x0+sqrtDt*(mm-1-2*i), dt, mm); optionPrice[i]=payoff(t, underlyingX, dt, mm); } mm--; for(int j=(m-2); j>=0; j--){ t=j*dt; for(int i=0; i<mm; i++){ Number underlyingX=fInv(t, x0+sqrtDt*(mm-1-2*i), dt, mm); auto alph=alpha(t, underlyingX, dt, mm); auto sig=sigma(t, underlyingX, dt, mm); auto p=(alph-sig*.5)*.5*sqrtDt+.5; if(p>1.0){ p=1.0; //numberOfPChanged++; } else if(p<0.0){ p=0.0; //numberOfPChanged++; } optionPrice[i]=(p*optionPrice[i]+(1-p)*optionPrice[i+1])*discount(t, underlyingX, dt, mm); auto intrinsic=payoff(t, underlyingX, dt, mm); if(optionPrice[i]<intrinsic){ optionPrice[i]=intrinsic; } } optionPrice.pop_back(); mm--; } return optionPrice[0]; }<file_sep>/Swap.cpp #include "Swap.h" Swap::Swap(const std::vector<double> &libor_, double tenor_){ //maxT=horizon; //eg 30 (years) tenor=tenor_; //eg .5 (half a year) libor=libor_; //array of libor rates given as (b_i-b_{i+1})/(b_{i+1}*tenor) n=libor.size()+1; bonds=std::vector<double>(n);//b(t, t+tenor*i) bonds[0]=1;//b(t, t) for(int i=1; i<n; i++){ bonds[i]=bonds[i-1]/(tenor*libor[i-1]+1.0); //std::cout<<bonds[i]<<" "<<(std::pow(bonds[i], -1.0/(double)i)-1.0)/(tenor*i)<<std::endl; } } Swap::Swap(const std::vector<ForwardValue> &libor_){ //maxT=horizon; //eg 30 (years) //tenor=tenor_; //eg .5 (half a year) libor=libor_; //array of libor rates given as (b_i-b_{i+1})/(b_{i+1}*tenor) n=libor.size(); bonds=std::vector<ForwardValue>(n+1);//b(t, t+tenor*i) bonds[0].value=1;//b(t, t) bonds[0].beginDate=libor[0].beginDate;//b(t, t) bonds[0].endDate=libor[0].beginDate;//b(t, t) for(int i=1; i<(n+1); i++){ libor[i-1].endDate.setScale("year"); bonds[i].value=bonds[i-1].value/((libor[i-1].endDate-libor[i-1].beginDate)*libor[i-1].value+1.0); bonds[i].beginDate=libor[i-1].beginDate;//b(t, t) bonds[i].endDate=libor[i-1].endDate;//b(t, t) std::cout<<bonds[i].value<<" "<<(std::pow(bonds[i].value, -1.0/(double)i)-1.0)/(libor[i-1].endDate-libor[i-1].beginDate)<<std::endl; } } double Swap::getPrice(double timeToMaturity, double k){ return getPrice(timeToMaturity, 1, k); } double Swap::getPrice(double timeToMaturity, double discountToNextPayment, double k){ //k is the swap rate (should be a constant for each swap). discountToNextPayment is the (unannualized) discount from now to the first payment double khat=(1.0/tenor+k)*discountToNextPayment; //in case less than exactly "tenor" to next payment double tenorHat=tenor*discountToNextPayment; double price=0; int numToMaturity=(int)(timeToMaturity/tenor); for(int i=1; i<numToMaturity;i++){ //dont count first bond since the first payment occurs after the first tenor price=price+bonds[i]/tenorHat-bonds[i+1]*khat; } return price; } double Swap::getRate(double timeToMaturity){ //gets swap rate int numToMaturity=(int)(timeToMaturity/tenor); double den=0; double num=0; for(int i=1; i<numToMaturity; i++){ den+=bonds[i+1]; num+=bonds[i]; } return (num/den-1.0)/tenor; } double Swap::getBondPrice(double timeToMaturity){ int numToMaturity=(int)(timeToMaturity/tenor); return bonds[numToMaturity+1]; } double Swap::getBondYield(double timeToMaturity){ int numToMaturity=(int)(timeToMaturity/tenor); return (1.0/bonds[numToMaturity]-1.0)/timeToMaturity; //simple interest, no compounding } <file_sep>/README.md This is a very generic binomial tree calculator. The brains are in Tree.cpp and Tree.h. The "main.cpp" file is intended as a simple example of how to use the calculator. The calcluator can be used to price American and European style options for any payoff and any single dimensional SDE. <file_sep>/Swap.h #ifndef __SWAP_H_INCLUDED__ #define __SWAP_H_INCLUDED__ #include <vector> #include <cmath> #include <iostream> //for debugging #include "Date.h" #include "Double.h" class Swap { private: std::vector<double> libor; double tenor; int n; std::vector<double> bonds; struct ForwardValue{ Date beginDate; Date endDate; Double value; }; public: Swap(const std::vector<double>& , double); double getPrice(double, double); //returns price for a given time to maturity and swap rate double getPrice(double, double, double); //returns price at times when interval isn't exact double getRate(double); double getBondPrice(double); double getBondYield(double); }; #endif
6fdacb483d6819dda8c2a6846b9a8c8ae8eed7d0
[ "Markdown", "C++" ]
8
C++
wangdong8500/BinomialTree
d40d2ebbc9de0e1b7d30c3ec82d55c6d4346ef9a
424d2f6c5f74e6e867654eae9c0ee28d54ca332f
refs/heads/master
<file_sep>package com.company; public class Main { static int indexOF(int h, int length) { return h & (length -1); } public static void main(String[] args) { } }
6849aaf1231aec8b7f12216eedc1e0fe1ad29228
[ "Java" ]
1
Java
AndreyRudenko/Lecture20
a82e1f9b84b014b43a06c3a2a9c94715d7bee0ee
9509ea013915f5ae8e03b89962521d2b4bbbaae8
refs/heads/master
<file_sep># SCons tools A few helpers for different tasks which I do quite often when using SCons as a build-system. ## Usage Put the file containing the helpers you want to use somewhere in your path or provide path as well as toolname. env = Environment( # Supply the names of the tools you want to use ( you might want to add # 'default' to the list as well ). tools = ['cutest'], # This is where you might need to supply a path to where you put your # helper-files toolpath = ['sconslib'] ) And you are good to go. Your milage may wary... ## Documentation Look in the files for the different functionality implemented. Better documentation might appear here, but don't count on it. <file_sep>import re from SCons.Builder import Builder from SCons.Scanner import Scanner def generate(env,**kwargs): setup_environment(env) add_builders(env) def exists(env): return 1 def setup_environment(env): env.AppendUnique(TEST_CASES=[]) def add_builders(env): from string import Template template = Template(""" /* This is auto-generated code. Edit at your own peril. */ #include <stdio.h> #include "CuTest.h" $EXTTESTS void RunAllTests(void) { CuString *output = CuStringNew(); CuSuite* suite = CuSuiteNew(); $ADDTESTS CuSuiteRun(suite); CuSuiteSummary(suite, output); CuSuiteDetails(suite, output); printf("%s\\n", output->buffer); } int main(void) { RunAllTests(); return 0; } """) def GenerateAllTests(env, target, source, test_case = re.compile(r'^\s*void (Test[^\(\s]+)',re.M)): if not isinstance(target,list): target = [target] print ":: Generate tests %s < %s"%(str(target[0]),' '.join([str(s) for s in source])) assert(len(source)>=1) assert(len(target)<=1) if env.GetOption('clean'): return '' if(target == None): target[0] = 'AllTests.c' TEST_CASES = [] for node in source: print "\tscanning %s ..."%(str(node)) contents = node.get_text_contents() test_cases = test_case.findall(contents) TEST_CASES.extend(test_cases) f = open(str(target[0]),'w') f.write(template.substitute( EXTTESTS='\n'.join(["extern void %s(CuTest*);"%(case) for case in TEST_CASES]), ADDTESTS='\n'.join(["\tSUITE_ADD_TEST(suite, %s);"%(case) for case in TEST_CASES]))) f.flush() f.close() return target[0] env.AddMethod(GenerateAllTests) <file_sep>from SCons.Script import Builder def generate(env, **kwargs): setup_environment(env) setup_tools(env) add_builders(env) def exists(env): return 1 def setup_environment(env): pass def setup_tools(env): if not env.has_key('MMD'): env['MMD'] = 'multimarkdown' def generate_builder(fmt): return Builder( action = "$MMD -o $TARGET -t %s $SOURCE" % fmt, suffix = '.%s' % fmt, src_suffix = ['.txt','.md','.markdown'] ) def add_builders(env): env.Append(BUILDERS = { 'LaTeX' : generate_builder('latex'), 'HTML' : generate_builder('html') }) <file_sep> from SCons.Script import Builder def generate(env, **kwargs): setup_environment(env) setup_tools(env) add_flags(env) add_commands(env) def exists(env): return 1 def setup_environment(env): if env.has_key('AVRPATH'): env.AppendENVPath('PATH',env['AVRPATH']) def setup_tools(env): if None != env.WhereIs('avrdude'): env['AVRDUDE'] = 'avrdude' else: print "ERROR: avrdude not found on path" def add_flags(env): env['DUDEFLAGS'] = env['PROGRAMMER'] + ' -p $MCU' def add_commands(env): def read_fuse(env,source=None): env.Command('read_fuses',None,'$AVRDUDE $DUDEFLAGS -qq -U lfuse:r:/dev/stdout:h -U efuse:r:/dev/stdout:h -U hfuse:r:/dev/stdout:h') def flash(env,source): assert(len(source)==1) env.Command('flash',source,'$AVRDUDE $DUDEFLAGS -qq -U flash:w:$SOURCE:i') def erase_device(env,source=None): env.Command('erase',None,'$AVRDUDE $DUDEFLAGS -e') env.AddMethod(read_fuse, "ReadFuses") env.AddMethod(flash, "Flash") env.AddMethod(erase_device, "Erase")<file_sep>from os import environ from SCons.Builder import Builder # Why can't I have env.Program? =( def generate(env, **kwargs): setup_environment(env) setup_tools(env) add_flags(env) add_builders(env) def exists(env): return 1 def setup_environment(env): if env.has_key('AVRPATH'): env.AppendENVPath('PATH',env['AVRPATH']) def setup_tools(env): assert env.has_key('MCU'), "You need to specify processor (MCU=<cpu>)" if not env.has_key('PREFIX'): env['PREFIX'] = 'avr-' if not env.has_key('HEXFORMAT'): env['HEXFORMAT'] = 'ihex' gnu_tools = ['gcc','g++','ar',] for tool in gnu_tools: env.Tool(tool) env.Replace(CC=env['PREFIX']+'gcc') env.Replace(CXX=env['PREFIX']+'g++') env.Replace(AR=env['PREFIX']+'ar') env.Replace(RANLIB=env['PREFIX']+'ranlib') env.Replace(OBJCOPY=env['PREFIX']+'objcopy') env.Replace(OBJDUMP=env['PREFIX']+'objdump') env.Replace(SIZE=env['PREFIX']+'size') if None == env.WhereIs(env['CC']): print '%s not found on PATH'%(env['CC']) env['PROGSUFFIX'] = '.elf' def add_flags(env): assert(env['MCU']) env.Append(CFLAGS='-mmcu='+env['MCU']) env.Append(LINKFLAGS='-mmcu='+env['MCU']) def add_builders(env): def generate_elf(source, target, env, for_signature): sources = ' '.join([str(s) for s in source]) result = '$CC $CFLAGS' result += ' -o %s %s'%(target[0],sources) if(env.has_key('LIBPATH')): result += include_string('-L',env['LIBPATH']) if(env.has_key('LIBS')): result += include_string('-l',env['LIBS']) return result def display_disasm(source, target, env, for_signature): assert(len(source)==1) return '$OBJDUMP -d %s'%(source[0]) def display_sizes(source, target, env, for_signature): assert(len(source)>=1) result = '$SIZE' if env.has_key('TOTALS') and env['TOTALS']: result += ' --totals' result += include_string(elements=source) return result def generate_hex(source, target, env, for_signature): assert(len(source)==1) assert(len(target)==1) result = '$OBJCOPY -O $HEXFORMAT -j .text -j .data -j .bss' result += ' %s %s'%(source[0],target[0]) return result def generate_eep(source, target, env, for_signature): assert(len(source)==1) assert(len(target)==1) result = '$OBJCOPY -O $HEXFORMAT -j .eeprom' # result += ' --set-section-flags=.eeprom="alloc,load"' # result += ' --change-section-lma .eeprom=0' result += ' %s %s'%(source[0],target[0]) return result env.Append(BUILDERS={ # 'Program': Builder( # generator=generate_elf, # suffix=env['PROGSUFFIX'], # src_suffix='.o'), 'DisplayASM': Builder( generator=display_disasm, src_suffix=env['PROGSUFFIX']), 'DisplaySizes': Builder(generator=display_sizes), 'HexFile': Builder( generator=generate_hex, suffix='.hex', src_suffix='.elf'), 'EepFile': Builder( generator=generate_eep, suffix='.eep', src_suffix='.elf')}) def include_string(prefix='',elements=[]): """Creates a list for inclusion on the commandline""" if len(elements)>0: return ' '+' '.join(['%s%s'%(prefix,element) for element in elements]) else: return ''
93c22fbd8cde0e9d59bd9a2c0cae7fda2f2a90b8
[ "Markdown", "Python" ]
5
Markdown
asheidan/SCons-tools
308e085208e630d2d4d0cad5aa3e4f689f0e7714
350e79155337462bc64d3a78c54cd42b66887d73
refs/heads/master
<file_sep>def check_slovo(slovo): checkk = True i = 0 while i < len(slovo): if (slovo[i]> 192 or (slovo[i]>65 and slovo[i]<90) or (slovo[i]>97 and slovo[i]<122) or slovo[i] ==32) != True: checkk = False i +=1 return checkk def worlds127(name, fam): name = list(name) fam = list(fam) name, fam = unicod(name, fam) checkk_name = check_slovo(name) checkk_fam = check_slovo(fam) return checkk_name, checkk_fam def unicod(name, fam): i = 0 name = list(name) fam = list(fam) while i < len(name): name[i] = ord(name[i]) i +=1 i = 0 while i < len(fam): fam[i] = ord(fam[i]) i +=1 return name, fam def getting_tail(mass, n): i = 0 k = len(list(mass)) - n mass = mass[k:] tail = '' while i < len(list(mass)): tail = tail + str(chr(mass[i])) i +=1 return tail def add00(mass, n): i = 0 while i < n: mass.append(0) i +=1 return mass def work_ris1(name, fam, tail_str, result_sum, result_sum_ascii): if len(name) != len(fam): n = abs(len(name) - len(fam)) if len(name) < len(fam): tail_str = getting_tail(fam, n) name = add00(name, n) else: tail_str = getting_tail(name, n) fam = add00(fam, n) else: tail_str = '' i = 0 result_sum_ascii = [] while i < len(name): cakesumm = int(name[i])^int(fam[i]) result_sum_ascii.append(cakesumm) cakesumm = chr(cakesumm) result_sum = result_sum + cakesumm i +=1 return name, fam, tail_str, result_sum, result_sum_ascii
686671befb817563f0707db836d99a83f4d8367a
[ "Python" ]
1
Python
UlianaTret/distributed_information_system
8a10574309e299a4824b8ca557f0a50fee2a1944
ce9d7a5bc8b5064601334086871494f3cf26a3b4
refs/heads/master
<repo_name>jeffreycorpuz/mlm<file_sep>/database/migrations/2020_07_14_094724_create_members_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateMembersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('members', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('first_name'); $table->string('last_name'); $table->string('email'); $table->string('password'); $table->string('account_type'); $table->string('contact_number'); $table->string('bank')->nullable(); $table->string('bank_account_name')->nullable(); $table->string('bank_account_number')->nullable(); $table->string('bank_account_type')->nullable(); $table->string('gcash')->nullable(); $table->string('serial_number'); $table->string('referred_by'); $table->bigInteger('income'); $table->string('batch'); $table->string('parent_node'); $table->string('left_node'); $table->string('right_node'); $table->string('image_file')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('members'); } }
88578062516a93c9ce1311966414fdcd0acfbcff
[ "PHP" ]
1
PHP
jeffreycorpuz/mlm
37c6f75ed67db186aef70df77b33933429479cba
9796c06d3acc4434db4090390b18fbfc1b6b772f
refs/heads/master
<file_sep><?php /* calculate.php */ require('gump.class.php'); session_start(); class gumpVal extends GUMP { /** * Determine if the provided value is greater than value 1 and less than value 2 * * Usage: '<index>' => 'val_between, n1 n2' * * @access public * @param string $field * @param array $input * @return mixed */ public function validate_val_between($field, $input, $param = NULL){ if(!isset($input[$field]) || empty($input[$field])) { return; } $param = explode(chr(32), $param); if($input[$field] > $param[0] && $input[$field] < $param[1]) { return; } if(!is_numeric($input[$field])) { return array( 'field' => $field, 'value' => $input[$field], 'rule' => __FUNCTION__, 'param' => $param ); } } } function calculate($hours, $group) { $h = $hours - 1; //We have a flat fee set, so only need to calc addl hours switch($group) { case 1: // Pianist & Singer // Rate: Hourly // First: $300 ($150/piece) // Addl: $250 ($125/piece) $est = (300 + (250 * (int)$h)); break; case 2: // Pianist, Singer & Sax // Rate: Hourly // First: $450 ($150/piece) // Addl: $375 ($125/piece) $est = (450 + (375 * (int)$h)); break; case 3: // 9 Piece Band // Rate: Hourly // First: $1350 ($150/piece) // Addl: $1125 ($125/piece) $est = (1350 + (1125 * (int)$h)); break; case 4: // Telegram // Rate: Flat // First: $125 $est = 125; break; case 5: // DJ // Rate: Hourly // First: $150 // Addl: $125/hr $est = (150 + (125 * (int)$h)); break; case 6: // Karaoke // Rate: Hourly // First: $150 // Addl: $125/hr $est = (150 + (125 * (int)$h)); break; default: $est = 0; break; } setlocale(LC_MONETARY, 'en_US'); return money_format('%(#4n', $est); } function transType($type, $otherType) { switch($type) { case 1: return "Wedding Cocktail Hour"; break; case 2: return "Wedding Ceremony"; break; case 3: return "Wedding Reception"; break; case 4: return "Entire Wedding"; break; case 5: return "Restaurant/Lounge"; break; case 6: return "Private Party"; break; case 7: return "Other: " . $otherType; break; default: return "N/A"; break; } } function transLocation($location) { switch($location) { case 1: return "Local - Up to 50 miles"; break; case 2: return "Destination"; break; default: return "N/A"; break; } } function transGroup($group) { switch($group) { case 1: return "Pianist &amp; Singer"; break; case 2: return "Pianist, Singer &amp; Sax"; break; case 3: return "9 Piece Band"; break; case 4: return "Telegram"; break; case 5: return "DJ"; break; case 6: return "Karaoke"; break; default: return "N/A"; break; } } function emailHTML($fields) { $fields['estimate'] = calculate($fields['hours'], $fields['group']); $fields['type'] = transType($fields['type'], $fields['otherType']); $fields['location'] = transLocation($fields['location']); $fields['group'] = transGroup($fields['group']); $body = "<html lang='en'> <head> <meta charset='utf-8' /> <title></title> </head> <body> <table style='font-family:Trebuchet MS;width:400px;font-size:14px;border:1px solid#ccc;border-collapse:collapse;'> <thead> <tr> <td style='text-align:center;padding:0;'> <img src='besteventsingerlogo.png' alt='Best Event Singer Logo' title='<NAME> - Event Singer' /> </td> </tr> <tr> <td style='padding:5px;'> New submission from Best Event Singer! </td> </tr> </thead> <tbody> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Name </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['firstname'] . " " . $fields['lastname'] . " </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Email </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['email'] . " </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Phone </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['phone'] . " </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Event Date </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['date'] . " </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Event Type </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['type'] . " </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Event Location </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['location'] . " </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Event Duration </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['hours'] . " Hours </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Additional Info/Message </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['message'] . " </td> </tr> <tr> <th style='background-color:#e19ce0;text-align:left;padding:5px;'> Your Estimated Quote </th> </tr> <tr> <td style='padding:5px 5px 5px 20px;'> " . $fields['estimate'] . " </td> </tr> </tbody> </table> </body>"; return $body; } $gump = new gumpVal(); $fields = $gump->sanitize($_POST); $validation_rules = array( 'firstname' => 'required|alpha|max_len,40', 'lastname' => 'required|alpha|max_len,40', 'email' => 'required|valid_email|max_len,75', 'phone' => 'required|max_len,14', 'type' => 'required|integer|val_between,0 8', 'otherType' => 'alpha|max_len,50', 'date' => 'required|max_len,10', 'location' => 'required|integer|max_len,1|val_between,0 3', 'hours' => 'required|integer|max_len,1|val_between,1 7', 'group' => 'required|integer|max_len,1|val_between,0 7', 'message' => 'required|max_len,500' ); $validated_data = $gump->validate($fields, $validation_rules); if($validated_data !== TRUE) { // Failed Validation $_SESSION['ErrArray'] = $validated_data; $_SESSION['OrigArray'] = $fields; //header("location: http://besquote.macmannis.com/failed.php"); header("location: http://besquote.macmannis.com/index.php"); } else { $_SESSION['ErrArray'] = ''; $_SESSION['OrigArray'] = ''; $estimate = calculate($fields['hours'], $fields['group']); $to = $fields['email']; $subject = "BES Quote Tool"; $body = emailHTML($fields); $headers = "From: besquote.macmannis.com <<EMAIL>>\r\nMIME-Version: 1.0" . "\r\nContent-type:text/html;charset=UTF-8" . "\r\n"; $params = "-f <EMAIL>"; mail($to, $subject, $body, $headers, $params); header("location: http://besquote.macmannis.com/success.php"); } ?><file_sep># Best-Event-Singer-Quote-Tool A basic quote tool for calculating prices for an event singer and band. Comprised of PHP, jQuery and HTML5 <file_sep>CREATE TABLE IF NOT EXISTS `contact` ( `contact_id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(40) NOT NULL, `lastname` varchar(40) NOT NULL, `email` varchar(75) NOT NULL, `phone` varchar(14) NOT NULL, `type` int(11) NOT NULL, `otherType` varchar(50) NOT NULL, `date` date NOT NULL, `location` int(11) NOT NULL, `hours` int(11) NOT NULL, `group` int(11) NOT NULL, `message` varchar(500) NOT NULL, PRIMARY KEY (`contact_id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;<file_sep><?php /* failed.php */ session_start(); $ErrArray = $_SESSION['ErrArray']; $OrigArray = $_SESSION['OrigArray']; ?> <!DOCTYPE html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> body { background-color: white; } </style> </head> <body> <h1>Music Quote Generator</h1> <p>FAILED!</p> <p><?php echo var_dump($ErrArray); ?></p> <p>ORIGINAL!</p> <p><?php echo var_dump($OrigArray); ?></p> </body><file_sep><?php /* index.php */ session_start(); $ary = array(); $err = array(); if($_SESSION['ErrArray']) { $ary['firstname'] = ' value="' . $_SESSION['OrigArray']['firstname'] . '"'; $ary['lastname'] = ' value="' . $_SESSION['OrigArray']['lastname'] . '"'; $ary['email'] = ' value="' . $_SESSION['OrigArray']['email'] . '"'; $ary['phone'] = ' value="' . $_SESSION['OrigArray']['phone'] . '"'; switch($_SESSION['OrigArray']['type']) { case '1': $ary['type1'] = ' selected="selected"'; break; case '2': $ary['type2'] = ' selected="selected"'; break; case '3': $ary['type3'] = ' selected="selected"'; break; case '4': $ary['type4'] = ' selected="selected"'; break; case '5': $ary['type5'] = ' selected="selected"'; break; case '6': $ary['type6'] = ' selected="selected"'; break; case '7': $ary['type7'] = ' selected="selected"'; break; default: $ary['type0'] = ' selected="selected"'; break; } $ary['otherType'] = ' value="' . $_SESSION['OrigArray']['otherType'] . '"'; $ary['date'] = ' value="' . $_SESSION['OrigArray']['date'] . '"'; switch($_SESSION['OrigArray']['location']) { case '1': $ary['location1'] = ' selected="selected"'; break; case '2': $ary['location2'] = ' selected="selected"'; break; default: $ary['location0'] = ' selected="selected"'; break; } $ary['hours'] = ' value="' . $_SESSION['OrigArray']['hours'] . '"'; switch($_SESSION['OrigArray']['group']) { case '1': $ary['group1'] = ' selected="selected"'; break; case '2': $ary['group2'] = ' selected="selected"'; break; case '3': $ary['group3'] = ' selected="selected"'; break; case '4': $ary['group4'] = ' selected="selected"'; break; case '5': $ary['group5'] = ' selected="selected"'; break; case '6': $ary['group6'] = ' selected="selected"'; break; default: $ary['group0'] = ' selected="selected"'; break; } $ary['message'] = $_SESSION['OrigArray']['message']; $err = array(); $c = 0; $br = ''; foreach($_SESSION['ErrArray'] as $e) { $field = ucwords(str_replace(array('_','-'), chr(32), $e['field'])); $param = $e['param']; switch($e['rule']) { case 'validate_required': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field is required.$br"; break; case 'validate_valid_email': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must contain a valid email address.$br"; break; case 'validate_max_len': if($param == 1) { $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must be at least $param character in length.$br"; } else { $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must be at least $param characters in length.$br"; } break; case 'validate_min_len': if($param == 1) { $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must not exceed $param character in length.$br"; } else { $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must not exceed $param characters in length.$br"; } break; case 'validate_exact_len': if($param == 1) { $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must be exactly $param character in length.$br"; } else { $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must be exactly $param characters in length.$br"; } break; case 'validate_alpha': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must only contain alphabetical characters.$br"; break; case 'validate_alpha_numeric': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must only contain alpha-numeric characters.$br"; break; case 'validate_alpha_dash': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must only contain alpha-numeric characters, underscores, and dashes.$br"; break; case 'validate_numeric': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must only contain alpha-numeric characters, underscores, and dashes.$br"; break; case 'validate_integer': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must contain an integer.$br"; break; case 'validate_float': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must contain a decimal number.$br"; break; case 'validate_date': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field format must be MM-DD-YYYY.$br"; break; case 'validate_min_numeric': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must contain a number greater than $param.$br"; break; case 'validate_max_numeric': $err[$c]['id'] = $e['field']; $err[$c]['message'] = "The $field field must contain a number less than $param.$br"; break; } if($c > 0) { $br = '<br>'; } $c++; } if (!empty($err)) { $errAry = json_encode($err); } } ?> <!DOCTYPE html> <head> <meta charset="utf-8" /> <title></title> <link rel="stylesheet" href="css/pikaday.css" /> <link rel="stylesheet" href="css/tool.css" /> <script type="text/javascript" src="js/validate-min.js"></script> <script type="text/javascript" src="js/slideToggle.js"></script> <script type="text/javascript" src="js/moment-min.js"></script> <script type="text/javascript" src="js/pikaday.js"></script> </head> <body> <form name="musicQuote" action="src/calculate.php" method="post" id="musicQuoteForm"> <div id="errorMsg"></div> <table class="form-table"> <tbody> <tr> <td class="form-table-col-left" id="firstnameErr"> <label for="firstname" class="form-label">First Name</label> </td> <td class="form-table-col-right"> <input type="text" name="firstname" id="firstname" class="form-input" placeholder="e.g. John"<?php echo $ary['firstname']; ?> /> </td> </tr> <tr> <td class="form-table-col-left" id="lastnameErr"> <label for="lastname" class="form-label">Last Name</label> </td> <td class="form-table-col-right"> <input type="text" name="lastname" id="lastname" class="form-input" placeholder="e.g. Doe"<?php echo $ary['lastname']; ?> /> </td> </tr> <tr> <td class="form-table-col-left" id="emailErr"> <label for="email" class="form-label">E-mail Address</label> </td> <td class="form-table-col-right"> <input type="text" name="email" id="email" class="form-input" placeholder="e.g. <EMAIL>"<?php echo $ary['email']; ?> /> </td> </tr> <tr> <td class="form-table-col-left" id="phoneErr"> <label for="phone" class="form-label">Phone number</label> </td> <td class="form-table-col-right"> <input type="text" name="phone" id="phone" class="form-input" placeholder="e.g. 724-555-4321"<?php echo $ary['phone']; ?> /> <br /> <small>(Format: XXX-XXX-XXXX or 1-XXX-XXX-XXXX)</small> </td> </tr> <tr> <td class="form-table-col-left" id="typeErr"> <label for="type" class="form-label">Event Type</label> <div id="otherTypeErr"> <label for="otherType" class="form-label">Other Event Type</label> </div> </td> <td class="form-table-col-right"> <select name="type" id="type" class="form-dropdown" onchange="otherTypeBox(this.form.type)"> <option value=""<?php echo $ary['type0']; ?>> - - </option> <option value="1"<?php echo $ary['type1']; ?>>Wedding Cocktail Hour</option> <option value="2"<?php echo $ary['type2']; ?>>Wedding Ceremony</option> <option value="3"<?php echo $ary['type3']; ?>>Wedding Reception</option> <option value="4"<?php echo $ary['type4']; ?>>Entire Wedding</option> <option value="5"<?php echo $ary['type5']; ?>>Restaurant/Lounge</option> <option value="6"<?php echo $ary['type6']; ?>>Private Party</option> <option value="7"<?php echo $ary['type7']; ?>>Other</option> </select> <div id="otherBox"> <input type="text" name="otherType" id="otherType" class="form-input"<?php echo $ary['otherType']; ?> /> </div> </td> </tr> <tr> <td class="form-table-col-left" id="dateErr"> <label for="date" class="form-label">Date of Event</label> </td> <td class="form-table-col-right"> <input type="text" name="date" id="date" class="form-input" placeholder="e.g. 11-10-2014"<?php echo $ary['date']; ?> /> <br /> <small>(Format: MM-DD-YYYY)</small> </td> </tr> <tr> <td class="form-table-col-left" id="locationErr"> <label for="location" class="form-label">Event Location</label> </td> <td class="form-table-col-right"> <select name="location" id="location" class="form-dropdown"> <option value=""<?php echo $ary['location0']; ?>> - - </option> <option value="1"<?php echo $ary['location1']; ?>>Local - Up to 50 miles</option> <option value="2"<?php echo $ary['location2']; ?>>Destination</option> </select> </td> </tr> <tr> <td class="form-table-col-left" id="hoursErr"> <label for="hours" class="form-label">Hours</label> </td> <td class="form-table-col-right"> <input type="number" name="hours" id="hours" class="form-input" min="2" max="6" placeholder="e.g. 2-6"<?php echo $ary['hours']; ?> /> </td> </tr> <tr> <td class="form-table-col-left" id="groupErr"> <label for="group" class="form-label">Entertainment Needed</label> </td> <td class="form-table-col-right"> <select name="group" id="group" class="form-dropdown"> <option value=""<?php echo $ary['group0']; ?>> - - </option> <option value="1"<?php echo $ary['group1']; ?>>Pianist &amp; Singer</option> <option value="2"<?php echo $ary['group2']; ?>>Pianist, Singer &amp; Sax</option> <option value="3"<?php echo $ary['group3']; ?>>9 Piece Band</option> <option value="4"<?php echo $ary['group4']; ?>>Singing Telegram</option> <option value="5"<?php echo $ary['group5']; ?>>DJ</option> <option value="6"<?php echo $ary['group6']; ?>>Karaoke</option> </select> </td> </tr> <tr> <td class="form-table-col-left" id="messageErr"> <label for="message" class="form-label">Message</label> </td> <td class="form-table-col-right"> <textarea name="message" id="message" class="form-textbox" placeholder="Enter further details here..."><?php echo $ary['message']; ?></textarea> </td> </tr> <tr> <td class="form-table-col-both" colspan="2"> All fields required. Please complete form and submit. </td> </tr> <tr> <td class="form-table-col-both" colspan="2"> <button name="send_quote" type="submit" value="send_quote">Send me a quote!</button> </td> </tr> </tbody> </table> </form> <script type="text/javascript"> function findId(id) { return document.getElementById(id); } function otherTypeBox(s) { var o = s.options[s.selectedIndex].value; var t = findId('otherBox'); var s = new SlideToggle('otherBox'); var sl = new SlideToggle('otherTypeErr'); if (o === '7') { if(t.style.display === 'none' || t.style.display === '') { s.slideToggle(); sl.slideToggle(); } } else { if(t.style.display === 'block') { s.slideToggle(); sl.slideToggle(); } } } function errClose() { var s = new SlideToggle('errorMsg'); s.slideToggle(); } function filter(a, f) { var ret = []; for (var i = 0; i < a.length; ++i) { if (f(a[i])) { ret.push(a[i]); } } return ret; } function resetErr() { var elements = document.getElementsByTagName("*"); var logEl = filter(elements, function(el) { return /Err/.test(el.id); }); for (var i = 0; i < logEl.length; ++i) { logEl[i].style.color = '#000'; } return logEl; } function formValReq(f) { return (f !== null && f !== ''); } function checkErrors(e) { if(e) { var eMsg = new SlideToggle('errorMsg'); var errorMsg = findId('errorMsg'); if(errorMsg.style.display === 'block') { errorMsg.style.display = 'none'; } errorMsg.innerHTML = '<span id="errorClose" onclick="errClose()">close</span>'; for (var i = 0, errorLength = e.length; i < errorLength; i++) { var el = findId(e[i].id + 'Err'); var br = ''; if (i !== parseInt(e.length - 1)) { br = '<br>'; } el.style.color = '#ff0000'; errorMsg.innerHTML += e[i].message + br; } eMsg.slideToggle(); } } var postBackErrors = checkErrors(<?php echo $errAry; ?>); var picker = new Pikaday({ field: findId('date'), format: 'MM-DD-YYYY', firstDay: 1, minDate: new Date('01-01-2000'), maxDate: new Date('12-31-2020'), yearRange: [2000,2020] }); var validator = new FormValidator('musicQuote', [{ name: 'firstname', display: 'Firstname', rules: 'required|alpha|max_length[40]' }, { name: 'lastname', display: 'Lastname', rules: 'required|alpha|max_length[40]' }, { name: 'email', display: 'Email', rules: 'required|valid_email|max_length[75]' }, { name: 'phone', display: 'Phone', rules: 'required|max_length[14]|callback_PhoneRegEx' }, { name: 'type', display: 'Type', rules: 'required|numeric|less_than[8]|greater_than[0]|exact_length[1]' }, { name: 'otherType', display: 'Othertype', rules: '!callback_OtherTypeValidation|max_length[50]' }, { name: 'date', display: 'Date', rules: 'required|max_length[10]|callback_DateRegEx' }, { name: 'location', display: 'Location', rules: 'required|numeric|less_than[3]|greater_than[0]|exact_length[1]' }, { name: 'hours', display: 'Hours', rules: 'required|numeric|less_than[7]|greater_than[1]|exact_length[1]' }, { name: 'group', display: 'Group', rules: 'required|numeric|less_than[7]|greater_than[0]|exact_length[1]' }, { name: 'message', display: 'Message', rules: 'required|max_length[500]' }], function(errors, evt) { evt.preventDefault(); resetErr(); if (errors.length > 0) { checkErrors(errors); } else { var form = findId('musicQuoteForm'); form.submit(); } } ); validator.registerCallback('PhoneRegEx', function(v) { var RegEx = /^[0-9]{3,3}-[0-9]{3,3}-[0-9]{4,4}|[0-9]{1,1}-[0-9]{3,3}-[0-9]{3,3}-[0-9]{4,4}$/; return RegEx.test(v); }).setMessage('PhoneRegEx', 'The %s format must be XXX-XXX-XXXX or 1-XXX-XXX-XXXX.'); validator.registerCallback('DateRegEx', function(v) { var RegEx = /^[0-9]{2,2}-[0-9]{2,2}-[0-9]{4,4}$/; return RegEx.test(v); }).setMessage('DateRegEx', 'The %s format must be MM-DD-YYYY.'); validator.registerCallback('OtherTypeValidation', function(v) { var t = findId('type'); var o = String(t.options[t.selectedIndex].value); if (o === '7') { if(formValReq(v)) { return true; } else { return false; } } else { return true; } }).setMessage('OtherTypeValidation', "The Other Event Type is required when 'Other' is selected."); var p = findId('phone'); p.maxLength = 14; p.onkeyup = function(e) { e = e || window.event; if (e.keyCode >= 65 && e.keyCode <= 90) { this.value = this.value.substr(0, this.value.length - 1); return false; } else if (e.keyCode >= 37 && e.keyCode <= 40) { return true; } var v = (this.value.replace(/[^\d]/g, '')); if (v.length === 10) { this.value = (v.substring(0, 3) + "-" + v.substring(3, 6) + "-" + v.substring(6, 10)); } else if (v.length === 11) { this.value = (v.substring(0, 1) + "-" + v.substring(1, 4) + "-" + v.substring(4, 7) + "-" + v.substring(7, 11)); }; } var d = findId('date'); d.maxLength = 10; p.onpaste = d.onkeyup = function(e) { e = e || window.event; if (e.keyCode >= 65 && e.keyCode <= 90) { this.value = this.value.substr(0, this.value.length - 1); return false; } else if (e.keyCode >= 37 && e.keyCode <= 40) { return true; } var v = (this.value.replace(/[^\d]/g, '')); if (v.length === 8) { this.value = (v.substring(0, 2) + "-" + v.substring(2, 4) + "-" + v.substring(4, 8)); }; } </script> </body>
48d5fb64b2b570f65cd58583debbdd87afdd20c2
[ "Markdown", "SQL", "PHP" ]
5
PHP
Pmac627/Best-Event-Singer-Quote-Tool
881b916efb7ef6161868487b0da83b2e33444a1a
dbae0caae56bd20d59891dd0a1f4c2ef3943de1a
refs/heads/master
<file_sep><?php namespace App\Http\Controllers\Front; use App\Models\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; class HeadportController extends Controller { public function show(){ return view('front.headport'); } //头像上传处理 public function headdeal(Request $request){ $headport = $request->file('headport'); $reaname = $headport->getClientOriginalName(); if($headport->isValid()){ $reapath = $headport->getRealPath(); $savename = '/uploads/'.$reaname; $stat = Storage::disk('public')->put($reaname,file_get_contents($reapath)); if($stat) { $id = auth('admin')->user()->id; $user = User::find($id); $user->headphoto = $savename; $user->update(); if ($user) { return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '修改成功', 'tiaozhuan' => 'front.user']); } else { return redirect()->route('inc.prompt', ['notic' => 'error', 'message' => '修改失败', 'tiaozhuan' => 'front.headport']); } } else{ return redirect()->route('inc.prompt', ['notic' => 'error', 'message' => '修改失败', 'tiaozhuan' => 'front.headport']); } } } } <file_sep><?php namespace App\Http\Controllers\Front; use DB; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class SearchController extends Controller { // public function searach(Request $request){ $keyword = $request->keyword; $result = DB::table('contents') ->join('users','contents.user_id','=','users.id') ->where('title','like',"%$keyword%") ->orwhere('content','like',"%$keyword%") ->paginate(5); return view('front.searach',compact('result','keyword')); } } <file_sep><?php namespace App\Http\Controllers\Front; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; class DownfileController extends Controller { // public function down(Request $request){ $name =$request->name; $path = storage_path('/app/public/').$name; return response()->download($path); } } <file_sep><?php namespace App\Http\Controllers\Front; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\User; use App\Models\Content; class UserController extends Controller { public function showMes(){ if(auth('admin')->check()){ $username = auth('admin')->user()->name; $user = User::where('name','=',$username)->first(); $content = Content::where('user_id','=',$user->id)->get(); if($user->headphoto==null){ $userpoto ='front/image/photo.jpg'; } else{ $userpoto = $user->headphoto; } return view('front.user',compact('content','userpoto')); } else{ return redirect()->route('front.index'); } } } <file_sep><?php namespace App\Http\Controllers\Front; use App\Models\Comment; use App\Models\Content; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CommentController extends Controller { public function comment(Request $request){ $user_id = $request->input('user_id'); $content_id = $request->input('content_id'); $cont = Content::find($content_id)->first(); return view('front.comment',compact('user_id','cont','content_id')); } public function commentdeal(Request $request){ $userid = $request->user_id; $contentid = $request->content_id; $message = $request->message; $com = new Comment(); $com->content_id = $contentid; $com->user_id = $userid; $com->message = $message; $stat = $com->save(); if($stat){ return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '评论成功!', 'tiaozhuan' => 'front.user']); } else{ return redirect()->back('302'); } } } <file_sep><?php Route::get('/index','Admin\IndexController@showIndex'); //老式写法 //Route::group(['prefix'=>'front','namespace'=>'Front'],function (){ // //}); //用户前台和后台 Route::namespace('Front')->prefix('front')->group(function (){ //主界面显示 Route::get('index','IndexController@indexShow')->name('front.index'); //帖子列表的显示 Route::get('listpost','ListpostController@showPost')->name('front.listpost'); //登陆界面 Route::get('login','LoginController@login')->name('front.login'); //登陆相关处理 Route::post('login','LoginController@userDeal')->name('front.login'); //退出登陆 Route::get('/prompt','LoginController@loginout')->name('front.loginout'); //帖子发布页 Route::get('public','PublicController@show')->name('front.public'); //帖子添加页 Route::post('public','PublicController@add')->name('front.public'); //文件上传相关操作 Route::get('upload','FileController@showUpLoad')->name('front.showupload'); Route::post('upload','FileController@upload')->name('front.upload'); //文件下载 Route::get('down/{name}','DownfileController@down')->name('front.down'); //帖子内容显示 Route::get('content/{modid}/{contenttitle}/{username}/{created_at}','ContentController@showContent')->name('front.content'); //用户个人页面展示 Route::get('user','UserController@showMes')->name('front.user'); //用户帖子显示 Route::get('usershow/{contentid}','UserOpController@show')->name('front.show'); //用户帖子删除 Route::get('userdelete/{contentid}','UserOpController@delete')->name('front.userdelete'); //用户帖子编辑 Route::post('userupdate/{id}','UserOpController@update')->name('front.userupdate'); //用户头像修改 Route::get('headport','HeadportController@show')->name('front.headport'); Route::post('headport','HeadportController@headdeal')->name('front.headport'); //用户注册页 Route::get('regist','RegistController@regist')->name('front.regist'); Route::post('regist','RegistController@registdeal')->name('front.regist'); //搜索 Route::any('searach','SearchController@searach')->name('front.searach'); //留言评论 Route::get('comment','CommentController@comment')->name('front.comment'); Route::post('comment','CommentController@commentdeal')->name('front.comment'); }); Route::get('/prompt/{notic}/{message}/{tiaozhuan}','Inc\PromptController@showPrompt')->name('inc.prompt'); Route::get('/home', 'HomeController@index')->name('home'); <file_sep><?php namespace App\Http\Controllers\Front; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Storage; use App\Models\File; class FileController extends Controller { // public function showUpLoad(){ return view('front.upload'); } //上传文件 public function upload(Request $request){ $realname = $request->file('source')->getClientOriginalName(); $upfile = $request->file('source'); if($upfile->isValid()){ $path = $upfile->getRealPath(); $reapath = "/strong/app/public/".$realname; $user_id = auth('admin')->user()->id; $stat = Storage::disk('file')->put($realname,file_get_contents($path)); $mod = new File(); $mod->name = $realname; $mod->url = $reapath; $mod->user_id = $user_id; $stats = $mod->save(); if($stat && $stats){ return redirect()->route('inc.prompt',['notic'=>'ok','message'=>'上传成功','tiaozhuan'=>'front.index']); } else{ return redirect()->route('inc.prompt',['notic'=>'error','message'=>'上传失败,请重试','tiaozhuan'=>'front.upload']); } } } } <file_sep><?php namespace App\Http\Controllers\Front; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Module; use App\Models\Content; use App\Models\User; use Illuminate\Support\Facades\DB; class ListpostController extends Controller { // public function showPost(Request $request){ //查询模板对象 $mod = Module::all(); //获取到页面提交的模板id $getnum = request()->id; $count = Content::where('module_id','=',$getnum)->count(); $result1 = Module::where('id','=',$getnum)->first(); $modulename = $result1->module_name; $result3 = DB::table('contents')->join('users','contents.user_id','=','users.id')->where('module_id','=',$getnum)->paginate(5); return view('front.listpost',compact('mod','getnum','modulename','result1','result3','count')); } } <file_sep><?php namespace App\Http\Controllers\Front; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Content; class UserOpController extends Controller { // public function show(Request $request){ $conid = $request->contentid; $con = Content::where('id','=',$conid)->first(); return view('front.userupdate',compact('con')); } public function update(Request $request,$id){ $title = $request->title; $cont = $request->cont; $date = [ 'title'=>$title, 'content'=>$cont, ]; $stat = Content::where('id',$id)->update($date); if($stat>0){ return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '修改成功!', 'tiaozhuan' => 'front.user']); } else{ return redirect()->route('inc.prompt', ['notic' => 'error', 'message' => '修改失败,请重试!', 'tiaozhuan' => 'front.userupdate']); } } public function delete($contentid){ $stat = Content::destroy($contentid); return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '删除成功!', 'tiaozhuan' => 'front.user']); } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class RegistRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'user'=>'required|between:1,20|alpha_num|unique:users,name', 'password'=>'required|between:1,16|alpha_num', 'password_confirmation'=>'required|between:1,16|alpha_num|same:password', 'vcode'=>'required|captcha', ]; } public function messages() { return [ 'user.requid' => '用户名字不能为空', 'user.alpha' => '只能是字母或者数字', 'user.between' => '只能在1-10个字之间', 'user.unique' => '用户名已存在', 'password.required' => '密码不能为空', 'password.between' => '密码只能在1-16个单词之间', 'password,alp_num' => '密码只能是数字或者字母', 'password_confirmation.required'=>'确定密码不能为空', 'password_confirmation.between'=>'密码只能在1-16个单词之间', 'password_confirmation.alp_num'=>'密码只能是数字或者字母', 'password_confirmation.same:password'=>'两次密码不一致', 'vcode.required'=>'验证码不能为空', 'vcode.captcha'=>'验证码错误', ]; } } <file_sep><?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as AuthUser; class User extends AuthUser { // protected $guarded = []; //文章表关联 public function content(){ return $this->hasMany(Content::class); } } <file_sep><?php namespace App\Http\Controllers\Front; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Http\Requests\LoginRequest; use App\Models\User; use Auth; class LoginController extends Controller { public function login(){ return view('front.login'); } //用户登录处理 public function userDeal(LoginRequest $request){ $username = $request->input('user'); $password = $request->input('password'); // 验证用户名登录方式 $user= auth('admin')->attempt( ['name' => $username, 'password' => $password]); // dd($request->only('user','password')); // $user = auth('admin')->attempt($request->only('user','password')); if($user){ return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '登陆成功!', 'tiaozhuan' => 'front.index']); }else { return redirect()->route('inc.prompt', ['notic' => 'error', 'message' => '登陆失败,请重试!', 'tiaozhuan' => 'front.login']); } // The blog post is valid, store in database... } //注销处理 public function loginout(){ auth('admin')->logout(); return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '注销成功!', 'tiaozhuan' => 'front.index']); } } <file_sep><?php namespace App\Http\Controllers\Front; use App\Models\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Module; use App\Models\Content; use DB; class ContentController extends Controller { public function showContent(Request $request){ $modid = $request->modid; $contenttitle = $request->contenttitle; $cont = Content::where('title','=',$contenttitle)->first(); $username = $request->username; $created_at = $request->created_at; $mod = Module::find($modid); $user = User::where('name','=',$username)->first(); if($user->headphoto==null){ $userpoto ='front/image/photo.jpg'; } else{ $userpoto = $user->headphoto; } $result = DB::table('users') ->leftJoin('contents', 'users.id', 'contents.user_id') ->leftJoin('comments', 'contents.id', 'comments.content_id') ->where('contents.id','=',$cont->id) ->orWhere('comments.content_id','=',$cont->id)->get(); return view('front.content',compact('mod','cont','username','created_at','userpoto','result')); } } <file_sep><?php namespace App\Http\Controllers\Front; use App\Http\Requests\RegistRequest; use App\Models\User; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class RegistController extends Controller { // public function regist(){ return view('front.regist'); } //用户注册处理 public function registdeal(RegistRequest $request){ if($request){ $name = $request->user; $password = $request->password; $user = new User(); $user->name = $name; $user->password = $password; $stat = $user->save(); if($stat){ return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '注册成功!', 'tiaozhuan' => 'front.login']); } } else{ return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '注册失败,请重试!', 'tiaozhuan' => 'front.regist']); } } } <file_sep><?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class LoginRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'user' => 'required|alpha_num|between:1,10', 'password' => 'required|between:1,16|alpha_num', 'vcode'=> 'required|captcha' ]; } public function messages() { return [ 'user.requid' => '用户名不能为空', 'user.alpha' => '只能是字母或者数字', 'user.between' => '只能在1-10个字之间', 'user.unique' => '用户名已存在', 'password.required' => '<PASSWORD>', 'password.between' => '密码只能在1-16个单词之间', 'password,alp_num' => '密码只能是数字或者字母', 'vcode.required'=>'验证码不能为空', 'vcode.captcha'=>'验证码错误', ]; } } <file_sep><?php use Faker\Generator as Faker; $factory->define(App\Models\Module::class, function (Faker $faker) { return [ 'module_name'=>$faker->word, 'describe'=>$faker->sentence ]; }); <file_sep><?php namespace App\Http\Controllers\Front; use App\Models\Module; use Illuminate\Http\Request; use App\Http\Requests\PublicRequest; use App\Http\Controllers\Controller; use App\Models\Content; use Auth; class PublicController extends Controller { //展示发布视图 public function show(){ //查询分类板块 $mod = Module::all(); return view('front.public',compact('mod')); } //添加帖子 public function add(PublicRequest $request){ $userid = auth('admin')->user()->id; $moudleId = $request->input('module_id'); $titel = $request->input('title'); $conntent = $request->input('content'); $mod = new Content(); $mod->module_id = $moudleId; $mod->user_id = $userid; $mod->title = $titel; $mod->content = $conntent; $status = $mod->save(); if($status){ return redirect()->route('inc.prompt', ['notic' => 'ok', 'message' => '添加成功!', 'tiaozhuan' => 'front.index']); } else{ return redirect()->route('inc.prompt', ['notic' => 'error', 'message' => '添加失败,请重试!', 'tiaozhuan' => 'front.public']); } // create方法 // $data = [ // 'module_id'=>$moudleId, // 'user_id'=>$userid, // 'title'=> $titel, // 'content'=>$conntent, // ]; // $mod = Content::created($data); } } <file_sep><?php namespace App\Http\Controllers\Front; use App\Models\File; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Models\Module; use Auth; use Illuminate\Support\Facades\Storage; class IndexController extends Controller { public function indexShow(){ //获取模板对象 $mod = Module::all(); //获取文件对象 $fle = File::all(); return view('front.index',compact('mod','fle')); } } <file_sep><?php namespace App\Http\Controllers\Inc; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class PromptController extends Controller { // public function showPrompt(Request $request){ //传入参数 //提示的图片 $notic = $request->notic; //现实的信息 $message = $request->message; //跳转路由 $tiaozhuan = $request->tiaozhuan; return view('inc.remind',compact('notic','message','tiaozhuan')); } }
22c6cbec1e0c4453818a7b714a0c038436303766
[ "PHP" ]
19
PHP
amdrose/lavbbs
87b9db3f261a61d02d2e66a946b1f78228d3d78c
6ef4472578fbb587ee12714417e0d88ef1effe74
refs/heads/master
<repo_name>Cornett-Harmony-WPF/first_git_project<file_sep>/README.md first_git_project ================= first project: flow chart <file_sep>/Ternaries/script.js //Conditional Logic - Ternary Operators var gpa = 48; //if the gpa is over the min 2.0 score, the student can graduate if( gpa > 2.0){ console.log("You can graduate!") }else{ console.log("GPA is too low!"); }*/ (gpa > 2.0) ? console.log("you can graduate!") var age = 11; var book; //if the child is under 10, they get Green Eggs and Ham, otherwise they get the Time Machine. book = (age< 10) console.log(book);
77eb8919347f4b26d0cc44eafbd77d389de79b07
[ "Markdown", "JavaScript" ]
2
Markdown
Cornett-Harmony-WPF/first_git_project
2be6e5d3e4c39fc929e54fde6a89fec1be584b51
c88c5ed4819595bae8856ac89bf30ec00880839a
refs/heads/master
<file_sep># -*- coding: utf-8 -*- #code by xi4okv QQ:48011203 site:xiaokui.cc import urllib2 as url import urllib2 import string import urllib import re import sys import threading import time def help(): #帮助 print "python google.py keyword page" return def google_search(keyword,pn): #google搜索关键词,返回整个html p='q='+keyword res=url.urlopen("https://wen.lu/#"+p+"&start="+str(pn)) html=res.read() print html return html ''' def get_url(html): #从返回的html里提取出url import re if html: urls_pat=re.compile(r'url":"(.*?)"}') siteUrls=re.findall(urls_pat,html) return siteUrls else: print "ERROR!" siteUrls=False ''' def google_url(xk_url): #访问提取出得URL,获得真实URL try: google = urllib2.urlopen("http:"+xk_url) if google: return google.url else: print u"URL解析失败!" google.url=False except: print u"抓取失败!" def main(i): #主程序 fileName='result.lst' mode='a+' f=open(fileName,mode) pn = 10 * (i-1) html = google_search(keyword,pn) urls = get_url(html) for xk_url in urls: if "link?url" in xk_url: result = google_url(xk_url) try: f.write(result+"\n") print u"线程"+str(i)+"抓取结果:"+result except: print u"写入失败!" if __name__=='__main__': help() try: keyword = sys.argv[1] n = string.atoi(sys.argv[2]) print 'search '+keyword+' in google:' for t in range(1,n): t = threading.Thread(target=main,args=(t,)) t.start() # t.join() except: print "error!" <file_sep>#!/usr/bin/python2.6 print ' +==========================+' print ' |Google Search Spider v1.0 |' print ' | Code by Xi4oKui |' print ' | QQ:48011203 |' print ' +==========================+' print '*********************************************************' print 'Please enter the KeyWord:' keyword = raw_input(); print 'Please waiting for spider check google for '+keyword import urllib2,urllib import simplejson for x in range(10): page = x * 4 url = ('https://ajax.googleapis.com/ajax/services/search/web' '?v=1.0&q=%s&rsz=8&start=%s') % (urllib.quote(keyword),page) try: request = urllib2.Request( url, None, {'Referer': 'http://www.baidu.com'}) response = urllib2.urlopen(request) # Process the JSON string. results = simplejson.load(response) infoaaa = results['responseData']['results'] except Exception,e: print e else: for minfo in infoaaa: print minfo['url'] <file_sep>google_search.py ================
01a582b08d82fed1d4ca4add0ce693644493c634
[ "Markdown", "Python" ]
3
Python
yuxiaokui/google_search_py
54417bf24fe562a1773a74509a88892426458b14
411ba7c75177fdc3812caa2f22f87e44410e8bc9
refs/heads/master
<file_sep>package com.seckill.dao; import com.seckill.entity.SuccessKilled; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * Created by afas on 2017/4/12. */ @RunWith(SpringRunner.class) @SpringBootTest public class SuccessKilledDaoTest { @Autowired SuccessKilledDao successKilledDao; @Test public void insertSuccessKilled() throws Exception { long id = 1000L; long phone = 1234567893L; int count = successKilledDao.insertSuccessKilled(id, phone); System.out.println("count::" + count); } @Test public void queryByIdWithSeckill() throws Exception { SuccessKilled successKilled = successKilledDao.queryByIdWithSeckill(1000L, 1234567892L); System.out.println(successKilled); } }<file_sep>/* Navicat MySQL Data Transfer Source Server : mysql Source Server Version : 50717 Source Host : localhost:3306 Source Database : seckill Target Server Type : MYSQL Target Server Version : 50717 File Encoding : 65001 Date: 2017-04-11 16:46:38 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for seckill -- ---------------------------- DROP TABLE IF EXISTS `seckill`; CREATE TABLE `seckill` ( `seckill_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '商品库存id', `name` varchar(120) NOT NULL COMMENT '商品名称', `number` int(11) NOT NULL COMMENT '库存数量', `start_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '开始时间', `end_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '结束时间', `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间', PRIMARY KEY (`seckill_id`), KEY `idx_start_time` (`start_time`), KEY `idx_end_time` (`end_time`), KEY `idx_create_time` (`create_time`) ) ENGINE=InnoDB AUTO_INCREMENT=1002 DEFAULT CHARSET=utf8 COMMENT='秒杀库存表'; -- ---------------------------- -- Records of seckill -- ---------------------------- INSERT INTO `seckill` VALUES ('1000', '100元秒杀1', '100', '2017-04-03 00:00:20', '2017-04-04 22:00:00', '2017-04-03 22:23:52'); INSERT INTO `seckill` VALUES ('1001', '1000元秒杀2', '100', '2017-04-03 22:38:18', '2017-04-03 22:38:18', '2017-04-03 22:38:18'); -- ---------------------------- -- Table structure for success_killed -- ---------------------------- DROP TABLE IF EXISTS `success_killed`; CREATE TABLE `success_killed` ( `seckill_id` bigint(20) NOT NULL COMMENT '秒杀商品id', `user_phone` bigint(20) NOT NULL COMMENT '用户电话', `state` tinyint(4) NOT NULL COMMENT '状态标志:-1无效 0:成功 1:已付款 2:已发货', `create_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间', PRIMARY KEY (`seckill_id`,`user_phone`), KEY `inx_create_time` (`create_time`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='秒伤成功明细表'; -- ---------------------------- -- Records of success_killed -- ---------------------------- <file_sep># deckilldemo # 这是一个Demo ##运用技术 1. Spring Boot 2. Mybatis <file_sep>spring.datasource.url=jdbc:mysql://localhost:3306/seckill?useUnicode=true&characterEncoding=utf-8&useSSL=true spring.datasource.username=seckill spring.datasource.password=<PASSWORD> spring.datasource.driver-class-name=com.mysql.jdbc.Driver mybatis.mapper-locations=classpath:mybatis/mapper/*.xml mybatis.type-aliases-package=com.seckill.entity mybatis.configuration.map-underscore-to-camel-case=true mybatis.configuration.use-generated-keys=true mybatis.configuration.use-column-label=true logging.level.root=info spring.thymeleaf.cache=false
044d2f3ab85a4ad7421589d8dad3942a43e5823a
[ "Markdown", "Java", "SQL", "INI" ]
4
Java
afashi/deckilldemo
1fb6df09eaf4724ee4587fe7217005bd3fd9a1c7
02f84f821c3c5a54e131015dfb24974412cdb93e
refs/heads/master
<file_sep>#Importamos tablas, zona horaria y panel user from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.utils.html import format_html # para mostrar miniatura class Profesor(models.Model): ESTADOS_PROFESOR = ( #definimos los estados ('activo', 'Activo'), ('inactivo', 'Inactivo'), ) #codigo_curso = models.ForeignKey(Curso, on_delete=models.CASCADE) nombre = models.CharField(max_length=100) apellidos = models.CharField(max_length=150) profesion = models.CharField(max_length=150) descripcion = models.TextField() imagen = models.ImageField(null = True, upload_to='profesores/img') video = models.FileField(null = True, upload_to='profesores/video') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) estado = models.CharField(max_length=10,choices=ESTADOS_PROFESOR,default='activo') def getImage(self): if self.imagen: return format_html("<img src='{}' style='width:120px; height:100px;' >",self.imagen.url) else: return 'Sin imagen previa' getImage.short_description = 'Imagen previa' getImage.allow_tags = True class Meta: #Creamos la clase metadatos ordering = ('apellidos',) #Ordena por fecha def __str__(self): # función que devuelve el titulo return self.apellidos # Modelo de alumno class Alumno(models.Model): ESTADOS_ALUMNO = ( #definimos los estados ('activo', 'Activo'), ('inactivo', 'Inactivo'), ) #codigo_curso = models.ForeignKey(Curso, on_delete=models.CASCADE) nombre = models.CharField(max_length=100) apellidos = models.CharField(max_length=150) descripcion = models.TextField() imagen = models.ImageField(null = True, upload_to='alumnos/img') video = models.FileField(null = True, upload_to='alumnos/video') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) estado = models.CharField(max_length=10,choices=ESTADOS_ALUMNO,default='activo') def getImage(self): if self.imagen: return format_html("<img src='{}' style='width:120px; height:100px;' >",self.imagen.url) else: return 'Sin imagen previa' getImage.short_description = 'Imagen previa' getImage.allow_tags = True class Meta: #Creamos la clase metadatos ordering = ('apellidos',) #Ordena por fecha def __str__(self): # función que devuelve el titulo return self.nombre +" " + self.apellidos # Modelo de los cursos class Curso(models.Model): ESTADOS_CURSO = ( #definimos los estados ('activo', 'Activo'), ('inactivo', 'Inactivo'), ) codigo = models.IntegerField(null = False, unique = True) titulo = models.CharField(max_length=150) subtitulo = models.CharField(max_length=150) fecha_inicio = models.DateTimeField(auto_now=False) fecha_fin = models.DateTimeField(auto_now=False) num_horas = models.IntegerField(null = False) logo = models.ImageField(null = True, upload_to='cursos/img') profesores = models.ManyToManyField(Profesor) alumnos = models.ManyToManyField(Alumno) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) estado = models.CharField(max_length=10,choices=ESTADOS_CURSO,default='activo') def getImage(self): if self.logo: return format_html("<img src='{}' style='width:120px; height:100px;' >",self.logo.url) else: return 'Sin imagen previa' getImage.short_description = 'Imagen previa' getImage.allow_tags = True class Meta: #Creamos la clase metadatos ordering = ('titulo',) #Ordena por fecha def __str__(self): # función que devuelve el titulo return self.subtitulo # Modelo de los orla class Orla(models.Model): ESTADOS_ORLA = ( #definimos los estados ('activo', 'Activo'), ('inactivo', 'Inactivo'), ) codigo = models.IntegerField(null = False, unique = True) #id = models.AutoField(primary_key=True) titulo = models.CharField(max_length=150) modelo = models.ImageField(null = True, upload_to='orla/modelos') curso = models.ForeignKey(Curso,on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) estado = models.CharField(max_length=10,choices=ESTADOS_ORLA,default='activo') def getImage(self): if self.modelo: return format_html("<img src='{}' style='width:120px; height:100px;' >",self.modelo.url) else: return 'Sin imagen previa' getImage.short_description = 'Imagen previa' getImage.allow_tags = True class Meta: #Creamos la clase metadatos ordering = ('titulo',) #Ordena por fecha def __str__(self): # función que devuelve el titulo return self.titulo + "("+str(self.curso)+")"<file_sep>from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('orla.urls')), ] # Para servir ficheros estáticos from django.conf import settings if settings.DEBUG: from django.conf.urls.static import static urlpatterns += static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)<file_sep>from django.shortcuts import render,redirect from orla.forms import FormularioContacto from django.core.mail import send_mail, BadHeaderError from orla.models import Curso, Profesor, Alumno, Orla # Create your views here. def orla_list(request,id_orla): #curso = Curso.objects.filter(codigo='1') #profesores = Profesor.objects.filter(estado='activo') #alumnos = Alumno.objects.filter(estado='activo') # generar el formulario status = "inicial" if request.method == 'GET': form = FormularioContacto() else: form = FormularioContacto(request.POST) if form.is_valid(): name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_Email'] message = form.cleaned_data['message'] status = "correcto" try: mensaje = "Orla Virtual\nDE: " + name + " (" + from_email + ")\n" + message send_mail(subject,mensaje,['<EMAIL>'],['<EMAIL>'],fail_silently=False,) form = FormularioContacto() # reiciniar el formulario except BadHeaderError: status = "incorrecto" orlas = Orla.objects.filter(codigo=id_orla) # orla en forma de lista if orlas: orlaObject = Orla.objects.get(codigo=id_orla) # orla como objeto alumnos = Alumno.objects.filter(curso=orlaObject.curso) profesores = Profesor.objects.filter(curso=orlaObject.curso) print(orlaObject) return render(request, 'orla.html', {'profesores': profesores,'alumnos': alumnos,'orla':orlaObject,'form':form,'status':status}) else: return render(request, 'crearOrla.html') #if orlas.count() > 0: #return render(request, 'orla.html', {'curso': curso, 'profesores': profesores2,'alumnos': alumnos2,'orlas':orlas}) #else: # return render(request, 'crearOrla.html') def home(request): return redirect('orla/1') """ # Create your views here. def contactView(request): if request.method == 'GET': form = FormularioContacto() else: form = FormularioContacto(request.POST) if form.is_valid(): name = form.cleaned_data['name'] subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_Email'] message = form.cleaned_data['message'] try: mensaje = "Orla Virtual\nDE: " + name + " (" + from_email + ")\n" + message send_mail(subject,mensaje,['<EMAIL>'],['<EMAIL>'],fail_silently=False,) form = FormularioContacto() # reiciniar el formulario except BadHeaderError: return render(request,'orla.html',{'form':form,'status':"incorrecto"}) return render(request,'orla.html',{'form':form,'status':"correcto"}) return render(request,'orla.html',{'form':form}) """ <file_sep>from django.urls import path, include from orla import views urlpatterns = [ path('', views.home, name='home'), path('orla/<int:id_orla>', views.orla_list, name='orla') ]<file_sep># Orla Virtual La Orla Digital es una aplicación Web realizada como Ejercicio Final del Certificado de Profesionalidad "Programación con Lenguajes Orientados a Objetos y Bases de Datos Relacionales" impartido en La Unión de Diciembre de 2020 a Junio de 2021 y de 710 horas de duración, impartido en el Centro Homologado del SEF de PixelBlack. <file_sep>from django import forms class FormularioContacto(forms.Form): name = forms.CharField(required=True, label="Nombre") from_Email = forms.EmailField(required=True,label="Correo") subject = forms.CharField(required=True,label="Asunto") message = forms.CharField(widget=forms.Textarea(attrs={"rows":4, "cols":20}),required=True,label="Mensaje")<file_sep>from django.contrib import admin # Register your models here. from .models import Profesor, Alumno,Curso,Orla #Alumno class AlumnoAdmin(admin.ModelAdmin): # Campos visibles a la hora de crear Alumno fields = ('nombre','apellidos','descripcion','imagen','getImage','video','estado','created','updated',) # Campos que muestra en resumen list_display= ('apellidos','nombre','id','getImage','estado','created','updated',) readonly_fields = ('getImage','created','updated',) admin.site.register(Alumno,AlumnoAdmin) # Profesor class ProfesorAdmin(admin.ModelAdmin): # Campos visibles a la hora de crear Alumno fields = ('nombre','apellidos','profesion','descripcion','imagen','getImage','video','estado','created','updated',) # Campos que muestra en resumen list_display= ('apellidos','nombre','id','getImage','profesion','estado','created','updated',) readonly_fields = ('getImage','created','updated',) admin.site.register(Profesor,ProfesorAdmin) # Curso class CursoAdmin(admin.ModelAdmin): # Campos visibles a la hora de crear Alumno fields = ('codigo','titulo','subtitulo','fecha_inicio','fecha_fin','num_horas','logo','getImage','profesores','alumnos','estado','created','updated',) # Campos que muestra en resumen list_display= ('titulo','subtitulo','id','fecha_inicio','fecha_fin','num_horas','getImage','estado','created','updated',) readonly_fields = ('getImage','created','updated',) admin.site.register(Curso,CursoAdmin) # Curso class OrlaAdmin(admin.ModelAdmin): # Campos visibles a la hora de crear Alumno fields = ('codigo','titulo','modelo','getImage','curso','created','updated',) # Campos que muestra en resumen list_display= ('titulo','curso','getImage','created','updated',) readonly_fields = ('getImage','created','updated',) admin.site.register(Orla,OrlaAdmin) <file_sep># Generated by Django 3.2.4 on 2021-06-18 19:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('orla', '0002_orla_titulo3'), ] operations = [ migrations.RemoveField( model_name='orla', name='titulo3', ), ] <file_sep>asgiref==3.3.4 Django==3.2.4 django-cleanup==5.2.0 django-sendgrid-v5==0.9.1 future==0.18.2 Pillow==8.2.0 python-http-client==3.3.2 pytz==2021.1 sendgrid==6.7.1 sqlparse==0.4.1 starkbank-ecdsa==1.1.1 <file_sep># Generated by Django 3.2.4 on 2021-06-18 19:05 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Alumno', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=100)), ('apellidos', models.CharField(max_length=150)), ('descripcion', models.TextField()), ('imagen', models.ImageField(null=True, upload_to='alumnos/img')), ('video', models.FileField(null=True, upload_to='alumnos/video')), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('estado', models.CharField(choices=[('activo', 'Activo'), ('inactivo', 'Inactivo')], default='activo', max_length=10)), ], options={ 'ordering': ('apellidos',), }, ), migrations.CreateModel( name='Curso', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.IntegerField(unique=True)), ('titulo', models.CharField(max_length=150)), ('subtitulo', models.CharField(max_length=150)), ('fecha_inicio', models.DateTimeField()), ('fecha_fin', models.DateTimeField()), ('num_horas', models.IntegerField()), ('logo', models.ImageField(null=True, upload_to='cursos/img')), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('estado', models.CharField(choices=[('activo', 'Activo'), ('inactivo', 'Inactivo')], default='activo', max_length=10)), ('alumnos', models.ManyToManyField(to='orla.Alumno')), ], options={ 'ordering': ('titulo',), }, ), migrations.CreateModel( name='Profesor', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nombre', models.CharField(max_length=100)), ('apellidos', models.CharField(max_length=150)), ('profesion', models.CharField(max_length=150)), ('descripcion', models.TextField()), ('imagen', models.ImageField(null=True, upload_to='profesores/img')), ('video', models.FileField(null=True, upload_to='profesores/video')), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('estado', models.CharField(choices=[('activo', 'Activo'), ('inactivo', 'Inactivo')], default='activo', max_length=10)), ], options={ 'ordering': ('apellidos',), }, ), migrations.CreateModel( name='Orla', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('codigo', models.IntegerField(unique=True)), ('titulo', models.CharField(max_length=150)), ('modelo', models.ImageField(null=True, upload_to='orla/modelos')), ('created', models.DateTimeField(auto_now_add=True)), ('updated', models.DateTimeField(auto_now=True)), ('estado', models.CharField(choices=[('activo', 'Activo'), ('inactivo', 'Inactivo')], default='activo', max_length=10)), ('curso', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='orla.curso')), ], options={ 'ordering': ('titulo',), }, ), migrations.AddField( model_name='curso', name='profesores', field=models.ManyToManyField(to='orla.Profesor'), ), ]
057eaeeaa5d315e40912b5d8f68b031a4297db77
[ "Markdown", "Python", "Text" ]
10
Python
loopsw/orla_virtual
a17bffffe1f344542c3ef7422361c583061d1791
4c2b6e3f26d1d0153a29a98711e14c68f7984729
refs/heads/master
<repo_name>otokunaga2/spring-boot-relationship-manytomany-thymeleaf<file_sep>/src/main/java/com/dicka/examplerelationshiph2dbthymeleaf/repository/AddressRepository.java package com.dicka.examplerelationshiph2dbthymeleaf.repository; import com.dicka.examplerelationshiph2dbthymeleaf.entity.Address; import org.springframework.data.jpa.repository.JpaRepository; public interface AddressRepository extends JpaRepository<Address, Long> { } <file_sep>/src/main/java/com/dicka/examplerelationshiph2dbthymeleaf/repository/StudentRepository.java package com.dicka.examplerelationshiph2dbthymeleaf.repository; import com.dicka.examplerelationshiph2dbthymeleaf.entity.Student; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface StudentRepository extends JpaRepository<Student, Long> { Student findByStudentId(Long studentId); @Query("SELECT s FROM Student s WHERE s.firstname = :firstname") List<Student> cariStudentBerdasarkanFirstname(@Param(value = "firstname")String firstname); } <file_sep>/src/main/java/com/dicka/examplerelationshiph2dbthymeleaf/controller/StudentApi.java package com.dicka.examplerelationshiph2dbthymeleaf.controller; import com.dicka.examplerelationshiph2dbthymeleaf.entity.Course; import com.dicka.examplerelationshiph2dbthymeleaf.entity.Student; import com.dicka.examplerelationshiph2dbthymeleaf.model.RequestStudentCourse; import com.dicka.examplerelationshiph2dbthymeleaf.model.ResponseData; import com.dicka.examplerelationshiph2dbthymeleaf.repository.CourseRepository; import com.dicka.examplerelationshiph2dbthymeleaf.repository.StudentRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.Date; import java.util.List; @RestController @RequestMapping(value = "/api/student") public class StudentApi { private static final Logger log = LoggerFactory.getLogger(StudentApi.class); @Autowired private StudentRepository studentRepository; @Autowired private CourseRepository courseRepository; @GetMapping public List<Student> listStudent(){ List<Student> students = new ArrayList<>(); List<Student> studentRepos = studentRepository.findAll(); for (Student student : studentRepos) students.add(student); return students; } @PostMapping(value = "/create") public ResponseEntity<Student> createStudentAndCourse(@RequestBody RequestStudentCourse studentCourse){ Student entityStudent = null; try{ Course course; List<Course> courseList = new ArrayList<>(); for (int i=0; i < studentCourse.getCourses().length; i++){ course = new Course(); course.setCourserName(studentCourse.getCourses()[i]); courseList.add(course); courseRepository.save(course); } entityStudent = new Student(); entityStudent.setFirstname(studentCourse.getFirstname()); entityStudent.setLastname(studentCourse.getLastname()); entityStudent.setEmail(studentCourse.getEmail()); entityStudent.getCourses().addAll(courseList); studentRepository.save(entityStudent); log.info("createStudentAndCourse : "+entityStudent.toString()); }catch (NullPointerException e){ log.info("createStudentAndCourse : "+e.toString()); e.printStackTrace(); } return new ResponseEntity<Student>(entityStudent, HttpStatus.CREATED); } }
95e81aa821ecc0e216efa5e23a89b97c7f080576
[ "Java" ]
3
Java
otokunaga2/spring-boot-relationship-manytomany-thymeleaf
0c4fe2f0d51c1c9fe2798b9cebc9433859409b96
d250d881904478287e353fef6e1759ee901fbd4c
refs/heads/master
<repo_name>SAURABH-UPRETI/React-Js-DarkMode<file_sep>/src/App.js import "./App.css"; import Navbar from "./Components/Navbar"; import React, { useState } from 'react'; function App() { const [mode, setMode] = useState('light')// Whether dark mod is enable or not const toggleMod = () =>{ if(mode==='light'){ setMode('dark'); document.body.style.backgroundColor = 'gray'; } else{ setMode('light'); document.body.style.backgroundColor = 'white'; } } return ( <> <Navbar mode={mode} toggleMod={toggleMod}/> </> ); } export default App;
16fd12339c7df6096362e6497d76e30a9198db16
[ "JavaScript" ]
1
JavaScript
SAURABH-UPRETI/React-Js-DarkMode
2ca1db150cbcb5329aa00b22c7241ac2db7729a1
9453d461a70776c0835f550a1d2374c81f35466f
refs/heads/master
<file_sep>package com.jpl.iotchallenge.device; import com.jpl.iotchallenge.services.APIServices; import com.jpl.iotchallenge.user.LhingsUser; import com.lhings.library.Action; import com.lhings.library.LhingsDevice; import javafx.application.Platform; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * IoT Challenge 2014 * @author <NAME> */ public class DInterface extends LhingsDevice { private final BooleanProperty checkedIn=new SimpleBooleanProperty(false); private final BooleanProperty light=new SimpleBooleanProperty(false); private final BooleanProperty availability=new SimpleBooleanProperty(false); private final StringProperty notify=new SimpleStringProperty(""); public DInterface(){ super(LhingsUser.getInstance().getUser(), LhingsUser.getInstance().getPass(), 6000, "Interface"); } @Override public void setup() { } @Override public void loop() { try { Thread.sleep(50); } catch (InterruptedException e) { } } /*********************************** ************** TABLE ************** ***********************************/ @Action(name = "checkIn", description = "action used to notify checked in event in Table", argumentNames = {"apikey"}, argumentTypes = {"string"}) public void actionCheckIn(String apikey){ Platform.runLater(()->{ LhingsUser.getInstance().setApiKeyCoworking(apikey); checkedIn.set(true); }); } @Action(name = "checkStatus", description = "action used to notify status changes in Table", argumentNames = {}, argumentTypes = {}) public void actionCheckStatus(){ Platform.runLater(()-> { JSONArray listStatus = APIServices.listStatus(LhingsUser.getInstance().getUuidTable()); if(listStatus!=null){ for(int i=0; i<listStatus.length(); i++){ JSONObject jsonObj=listStatus.getJSONObject(i); // System.out.println("j: "+jsonObj.toString()); String r; boolean res; try{ r=jsonObj.getString("value"); res=Boolean.parseBoolean(r); } catch(JSONException j){ res=jsonObj.getBoolean("value"); } switch(jsonObj.getString("name")){ case "checkedIn": checkedIn.set(res); break; case "light": light.set(res); break; case "availability": availability.set(res); break; } } } }); } @Action(name = "notifications", description = "action used to notify status changes in Table", argumentNames = {"text"}, argumentTypes = {"string"}) public void actionNotifications(String text){ Platform.runLater(()->notify.set(text)); } public BooleanProperty checkedInProperty() { return checkedIn; } public BooleanProperty lightProperty() { return light; } public BooleanProperty availabilityProperty() { return availability; } public StringProperty notifyProperty() { return notify; } public void resetActions(){ notify.set(""); } } <file_sep>package com.jpl.iotchallenge; import com.jpl.iotchallenge.device.DInterface; import com.jpl.iotchallenge.services.APIServices; import com.jpl.iotchallenge.user.LhingsUser; import com.jpl.iotchallenge.user.Login; import com.jpl.iotchallenge.utils.Utils; import eu.hansolo.enzo.common.SymbolType; import eu.hansolo.enzo.onoffswitch.IconSwitch; import eu.hansolo.enzo.onoffswitch.SelectionEvent; import java.net.URL; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Locale; import java.util.ResourceBundle; import javafx.animation.FadeTransition; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.property.StringProperty; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Cursor; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import javafx.scene.shape.SVGPath; import javafx.scene.text.Text; import javafx.util.Duration; /** * IoT Challenge 2014 * @author <NAME> */ public class DashboardController implements Initializable { @FXML private Label lblUser; @FXML private ImageView imgAvatar; @FXML private ImageView imgNet; @FXML private Label lblStatus; @FXML private Tab tabDevices; @FXML private SVGPath svgTable; @FXML private Text lblChecked; @FXML private Label lblTimeTable; @FXML private HBox hTable; private IconSwitch onOffTable; @FXML private SVGPath svgAvailable; @FXML private Text lblAvailable; @FXML private Label lblTimeAvailable; @FXML private HBox hAvailable; private IconSwitch onOffAvailable; @FXML private SVGPath svgTaxi; @FXML private Text lblTaxi; @FXML private Label lblTimeTaxi; @FXML private HBox hTaxi; private IconSwitch onOffTaxi; @FXML private SVGPath svgLamp; @FXML private Text lblLamp; @FXML private Label lblTimeLamp; @FXML private HBox hLight; private IconSwitch onOffLight; private final Image imgNetOn = new Image(getClass().getResourceAsStream("resources/netOn.png")); private final Image imgNetOff = new Image(getClass().getResourceAsStream("resources/netOff.png")); private FadeTransition messageTransition = null; private final DateTimeFormatter fmd =DateTimeFormatter.ofPattern("d'th of' MMMM").withLocale(Locale.ENGLISH); private final DateTimeFormatter fmt =DateTimeFormatter.ofPattern("HH:mm:ss").withZone(ZoneId.systemDefault());; private final StringProperty uuidTable=new SimpleStringProperty(""); private DInterface devInterface; /** * Initializes the controller class. * @param url * @param rb */ @Override public void initialize(URL url, ResourceBundle rb) { lblStatus.setText("Validating user..."); Label label = new Label("\uf10b"); label.getStyleClass().add("awesome"); reset(); lblTimeTable.setText(""); lblChecked.setText(""); onOffTable = new IconSwitch(); onOffTable.setSymbolType(SymbolType.NONE); onOffTable.setMinSize(80,30); hTable.getChildren().add(onOffTable); hTable.setDisable(true); onOffAvailable = new IconSwitch(); onOffAvailable.setSymbolType(SymbolType.NONE); onOffAvailable.setMinSize(80,30); hAvailable.getChildren().add(onOffAvailable); hAvailable.setDisable(true); onOffTaxi = new IconSwitch(); onOffTaxi.setSymbolType(SymbolType.NONE); onOffTaxi.setMinSize(80,30); hTaxi.getChildren().add(onOffTaxi); hTaxi.setDisable(true); onOffLight = new IconSwitch(); onOffLight.setSymbolType(SymbolType.NONE); onOffLight.setMinSize(80,30); hLight.getChildren().add(onOffLight); hLight.setDisable(true); tabDevices.setGraphic(label); tabDevices.setDisable(true); } private void reset(){ svgTable.setContent(Utils.TABLE_OFF); svgTable.setId("status-gray"); svgAvailable.setId("status-gray"); svgTaxi.setId("status-gray"); lblAvailable.setText(""); lblTimeAvailable.setText(""); lblTaxi.setText(""); lblTimeTaxi.setText(""); svgLamp.setId("status-gray"); lblLamp.setText(""); lblTimeLamp.setText(""); } public void login(Scene scene){ scene.setCursor(Cursor.WAIT); Login login=new Login(); login.loggedProperty().addListener((ov,b,b1)->{ if(b1){ String url=LhingsUser.getInstance().getAvatar(); if(url!=null && !url.isEmpty()){ url=url.replace("\\", ""); imgAvatar.setImage(new Image(url)); } lblUser.setText(String.join(" ",LhingsUser.getInstance().getName(), LhingsUser.getInstance().getSurname1())); imgNet.setImage(imgNetOn); tabDevices.setDisable(false); createDevice(); displayMessage("User validated"); } else { displayMessage("User not validated"); logout(); } scene.setCursor(Cursor.DEFAULT); }); if(LhingsUser.getInstance().getUser().isEmpty() || LhingsUser.getInstance().getPass().isEmpty()){ login.showLoginDialog(); } else { login.validateUser(); } } public void logout(){ imgAvatar.setImage(new Image(getClass().getResource("resources/user.png").toExternalForm())); lblUser.setText("No user"); imgNet.setImage(imgNetOff); } private final EventHandler<SelectionEvent> c=e -> { Platform.runLater(()->APIServices.doDeviceAction(LhingsUser.getInstance().getUuidTable(), "toggleCheckin")); }; private void switchTable(boolean status){ onOffTable.setOnSelect(null); onOffTable.setOnDeselect(null); onOffTable.setSelected(status); onOffTable.setOnSelect(c); onOffTable.setOnDeselect(c); } private final EventHandler<SelectionEvent> c1=e -> { Platform.runLater(()->APIServices.doDeviceAction(LhingsUser.getInstance().getUuidTable(), "toggleLight")); }; private void switchLight(boolean status){ onOffLight.setOnSelect(null); onOffLight.setOnDeselect(null); onOffLight.setSelected(status); onOffLight.setOnSelect(c1); onOffLight.setOnDeselect(c1); } private final EventHandler<SelectionEvent> c2=e -> { Platform.runLater(()->APIServices.doDeviceAction(LhingsUser.getInstance().getUuidTable(), "toggleAvailable")); }; private void switchAvailable(boolean status){ onOffAvailable.setOnSelect(null); onOffAvailable.setOnDeselect(null); onOffAvailable.setSelected(status); onOffAvailable.setOnSelect(c2); onOffAvailable.setOnDeselect(c2); } private String getDateTime(){ return LocalDate.now().format(fmd).concat(" at ").concat(LocalTime.now().format(fmt)); } private void createDevice(){ devInterface=new DInterface(); hTable.disableProperty().bind(devInterface.checkedInProperty().not()); hAvailable.disableProperty().bind(devInterface.checkedInProperty().not()); hTaxi.disableProperty().bind(devInterface.checkedInProperty().not()); hLight.disableProperty().bind(devInterface.checkedInProperty().not()); /* TABLE */ uuidTable.addListener((ov,s,s1)->{ if(s1.isEmpty()){ System.out.println("**DISABLE TABLE"); switchTable(false); } else { System.out.println("**ENABLE TABLE: "+s1); Platform.runLater(()->{ LhingsUser.getInstance().setUuidTable(s1); svgTable.setContent(Utils.TABLE_ON); svgTable.setId("status-green"); lblChecked.setText("You have checked in this CoWorking Table Device"); lblTimeTable.setText(getDateTime()); switchTable(true); }); } }); devInterface.checkedInProperty().addListener((ov,b,b1)->{ if(b1){ System.out.println("Retrieving Table from Coworking"); uuidTable.set(APIServices.getLhingsDeviceByName(LhingsUser.getInstance().getApiKeyCoworking(),"Table")); } else { svgTable.setContent(Utils.TABLE_OFF); svgTable.setId("status-off"); lblChecked.setText("You have checked out this CoWorking Table Device"); lblTimeTable.setText(getDateTime()); svgAvailable.setId("status-gray"); lblAvailable.setText(""); lblTimeAvailable.setText(""); svgTaxi.setId("status-gray"); lblTaxi.setText(""); lblTimeTaxi.setText(""); svgLamp.setId("status-gray"); lblLamp.setText(""); lblTimeLamp.setText(""); uuidTable.set(""); } }); devInterface.notifyProperty().addListener((ov,s,s1)->{ if(!s1.isEmpty()){ devInterface.resetActions(); } }); devInterface.lightProperty().addListener((ov,b,b1)->{ if(b1){ svgLamp.setId("status-green"); lblLamp.setText("You have turned on the Lamp in this CoWorking Table Device"); lblTimeLamp.setText(getDateTime()); switchLight(true); } else if(devInterface.checkedInProperty().get()){ svgLamp.setId("status-off"); lblLamp.setText("You have turned off the Lamp in this CoWorking Table Device"); lblTimeLamp.setText(getDateTime()); switchLight(false); } }); devInterface.availabilityProperty().addListener((ov,b,b1)->{ if(b1){ svgAvailable.setContent(Utils.AVAILABLE); svgAvailable.setId("status-green"); lblAvailable.setText("You have selected the Available mode at this CoWorking Table Device"); lblTimeAvailable.setText(getDateTime()); switchAvailable(false); } else if(devInterface.checkedInProperty().get()){ svgAvailable.setContent(Utils.NOT_AVAILABLE); svgAvailable.setId("status-red"); lblAvailable.setText("You have selected the Not Available mode at this CoWorking Table Device"); lblTimeAvailable.setText(getDateTime()); switchTable(true); } }); } public void devLogout(){ if(devInterface!=null){ devInterface.logout(); } } public void displayMessage(String message) { if (messageTransition != null) { messageTransition.stop(); } else { messageTransition = new FadeTransition(Duration.millis(2000), lblStatus); messageTransition.setFromValue(1.0); messageTransition.setToValue(0.0); messageTransition.setDelay(Duration.millis(1000)); messageTransition.setOnFinished(e -> lblStatus.setVisible(false)); } lblStatus.setText(message); lblStatus.setVisible(true); lblStatus.setOpacity(1.0); messageTransition.playFromStart(); } } <file_sep>#!/bin/bash java -cp "../lib/*:./bin/" com.lhings.iotchallenge.DLamp > log.txt 2>error.txt <file_sep>IoT Challenge Java One ====================== Repository to host the code and documentation of the project "Connected Table" for the IoT Developer Challenge at Java One 2014.
efc38064086ace7403ad8fbfb9ce0f5641575da5
[ "Markdown", "Java", "Shell" ]
4
Java
lhings/iotchallengejavaone
dad3e39a882e81606eb32308ef6fad3de059aad0
c2bae9c0139e2a97622f2c37b1785e6a0afb683c
refs/heads/master
<file_sep>package com.padc.mahawthadar.adapters; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.padc.mahawthadar.R; import com.padc.mahawthadar.views.holders.FamousBookViewHolder; public class FamousBookAdapter extends RecyclerView.Adapter { public FamousBookAdapter() { } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); return new FamousBookViewHolder(inflater.inflate(R.layout.view_holder_famous_book, viewGroup, false)); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) { } @Override public int getItemCount() { return 10; } } <file_sep>package com.padc.mahawthadar.adapters; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.padc.mahawthadar.R; import com.padc.mahawthadar.views.holders.SliderViewHolder; public class SliderAdapter extends RecyclerView.Adapter<SliderViewHolder> { public SliderAdapter() { } @NonNull @Override public SliderViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); return new SliderViewHolder(inflater.inflate(R.layout.view_holder_slider, viewGroup, false)); } @Override public void onBindViewHolder(@NonNull SliderViewHolder sliderViewHolder, int i) { } @Override public int getItemCount() { return 10; } }
ee56e7e48baf637b6440352cd24a7462cbaa1f22
[ "Java" ]
2
Java
thihaphyo/MaHawThaHtar
420234e90fa5385e68582f856dad7ed9fd3deed5
9347126dd25b5827a77ff4371aad37b156b87f60
refs/heads/master
<repo_name>trtd56/MuscleQA<file_sep>/src/muscle_qa.py import six import pandas as pd import numpy as np from functions import get_logger, to_sep_space, get_sim_index, show_sim_faq from config import LOGDIR, MUSCLE_QA, MUSCLE_CORPUS, MUSCLE_MODEL from net import AutoEncoder from return_corpus import ReutersMuscleCorpus class Infer(): def __init__(self, encoder, corpus): self.encoder = encoder self.corpus = corpus def __call__(self, text): text_sp = to_sep_space(text) ids = self.corpus.doc2ids(text_sp) vec = self.corpus.embed_matrix[ids] vec = np.reshape(vec, (1, vec.shape[0], vec.shape[1])) feat = self.encoder.predict(vec) return feat[0] def main(): logger = get_logger(LOGDIR) logger.info('start') logger.info('1. Load the trained model.') ae = AutoEncoder.load(MUSCLE_MODEL) encoder = ae.get_encoder() logger.info('2. Load the corpus.') corpus = ReutersMuscleCorpus.load(MUSCLE_CORPUS) logger.info('3. Set the infer model.') infer = Infer(encoder, corpus) qa_df = pd.read_csv(MUSCLE_QA) q_txts = qa_df['q_txt'].tolist() vecs = np.array([infer(d) for d in q_txts]) # 超回復とは # 夏までに痩せたい # 睡眠時間はどのくらいが良いですか? while True: text = six.moves.input('>> ') if text == '': break vec = infer(text) sort_i, sim = get_sim_index([vec], vecs) df = qa_df.loc[sort_i] show_sim_faq(df, sim) logger.info('end') if __name__ == '__main__': main() <file_sep>/src/eval_model.py import numpy as np import pandas as pd from keras.callbacks import TensorBoard, ModelCheckpoint from functions import get_logger, load_glove_vectors, load_wikiqa, get_sim_index, trim from config import LOGDIR, WIKIQA_MODEL, GLOVE_MODEL, GLOVE_SIZE, WIKIQA_CORPUS, WIKIQA_DIR from net import AutoEncoder from return_corpus import ReutersMuscleCorpus seq_size = 100 batch_size = 64 n_epoch = 20 latent_size = 512 class Infer(): def __init__(self, encoder, corpus): self.encoder = encoder self.corpus = corpus def __call__(self, text): text_sp = ' '.join([trim(i) for i in text.split()]) ids = self.corpus.doc2ids(text_sp) vec = self.corpus.embed_matrix[ids] vec = np.reshape(vec, (1, vec.shape[0], vec.shape[1])) feat = self.encoder.predict(vec) return feat[0] def main(): logger = get_logger(LOGDIR) logger.info('start') logger.info('1. Load WikiQA text') wikiqa_text = load_wikiqa() min_w = min([len(i.split()) for i in wikiqa_text]) max_w = max([len(i.split()) for i in wikiqa_text]) logger.info('{0} sentence, {1}-{2} words'.format(len(wikiqa_text), min_w, max_w)) logger.info('2. Load GloVe embeddings.') embed_matrix, vocab = load_glove_vectors(GLOVE_MODEL, d=GLOVE_SIZE) logger.info('embedding shape is {}'.format(embed_matrix.shape)) logger.info('3. Prepare the corpus.') corpus = ReutersMuscleCorpus() corpus.build(embed_matrix, vocab, seq_size) corpus.documents = wikiqa_text corpus.save(WIKIQA_CORPUS) logger.info('4. Make autoencoder model.') ae = AutoEncoder(seq_size=seq_size, embed_size=embed_matrix.shape[1], latent_size=latent_size) ae.build() logger.info('5. Train model.') ae.model.compile(optimizer="adam", loss="mse") train_iter = corpus.batch_iter(batch_size) train_step = corpus.get_step_count(batch_size) ae.model.fit_generator( train_iter, train_step, epochs=n_epoch, # validation_data=train_iter, # validation_steps=train_step, callbacks=[ TensorBoard(log_dir=LOGDIR), ModelCheckpoint(filepath=WIKIQA_MODEL, save_best_only=True) ] ) logger.info('6. Load the encoder.') encoder = ae.get_encoder() logger.info('7. Set the infer model.') infer = Infer(encoder, corpus) logger.info('8. Evaluate the model.') qa_df = pd.read_csv(WIKIQA_DIR + '/WikiQA-test.tsv', sep='\t') maps = [] mrrs = [] for q_id in qa_df['QuestionID'].unique(): df = qa_df[qa_df['QuestionID'] == q_id] if 1 not in df['Label'].unique(): logger.debug('{0}: not answer'.format(q_id)) continue q_doc = df['Question'].iloc[0].lower() q_vec = infer(q_doc) a_docs = df['Sentence'].map(lambda x: x.lower()).tolist() a_vecs = [infer(d) for d in a_docs] sort_i, sim = get_sim_index([q_vec], a_vecs) labels = [i for i, v in enumerate(df['Label']) if v == 1] rank = [i + 1 for i, v in enumerate(sort_i) if v in labels] _mrr = 1 / rank[0] _map = sum([1 / i for i in rank]) / len(rank) maps.append(_map) mrrs.append(_mrr) logger.info('{0}: MAP {1}, MRR {2}'.format(q_id, _map, _mrr)) map_avg = sum(maps) / len(maps) mrr_avg = sum(mrrs) / len(mrrs) logger.info('MAP AVG {0} / MRR AVG {1}'.format(map_avg, mrr_avg)) logger.info('end') if __name__ == '__main__': main() <file_sep>/src/scraping_qa.py import re import pandas as pd from bs4 import BeautifulSoup import requests URL = 'http://weighttrainingfaq.org/wiki/index.php' GET_INFO = '%A4%E8%A4%AF%A4%A2%A4%EB%BC%C1%CC%E4' URL += '?' + GET_INFO A_TXT_1 = 'トレーニング用語の場合は、まずはウェイトトレーニング用語辞典を見てみてください。' A_TXT_2 = '\ ・現在9月の場合:来年の夏まで1年弱。頑張れば多少は見栄えがするようになるかもしれません。\n\ ・現在12月の場合:来年の夏まで、約半年。筋量増加による体型改善は難しいので、減量に励みましょう。\n\ ・現在3月の場合:夏まで数ヶ月。まだ減量は間に合うかもしれません。\n\ ・現在6月の場合:夏直前。来年の夏なら……' def get_q_text(elem): txt = elem.text if txt[:2] == 'Q.': return txt[2:-3] return None def get_a_text(elem): txt = elem.text if txt[:2] == 'A.': return txt[2:] return None headers = {"User-Agent": "trtd"} resp = requests.get(URL, timeout=3, headers=headers, verify=False) soup = BeautifulSoup(resp.text, 'html5lib') q_elem = soup.find_all(id=re.compile('content_*')) a_elem = soup.find_all('p', class_='quotation') q_txts = [get_q_text(q) for q in q_elem] a_txts = [get_a_text(a) for a in a_elem] q_txts = [q for q in q_txts if q is not None] a_txts = [a for a in a_txts if a is not None] q_ids = ['Q{0:04d}'.format(i) for i in range(len(q_txts))] a_txts.insert(0, A_TXT_1) a_txts.insert(1, A_TXT_2) qa_df = pd.DataFrame({'q_id': q_ids, 'q_txt': q_txts, 'a_txt': a_txts}) qa_df = qa_df.ix[:, ['q_id', 'q_txt', 'a_txt']] qa_df.to_csv('../data/muscle_qa.csv', index=None) <file_sep>/src/functions.py import os import sys import io import re import MeCab import mojimoji import numpy as np import tensorflow as tf from sklearn.metrics.pairwise import cosine_similarity from nltk.corpus import stopwords from logging import StreamHandler, DEBUG, Formatter, FileHandler, getLogger from config import PAD, UNK, WIKIQA_DIR WAKATI = MeCab.Tagger('-Ochasen') STOPWORDS = stopwords.words("english") def get_logger(outdir): file_name = sys.argv[0] os.makedirs(outdir, exist_ok=True) logger = getLogger(__name__) log_fmt = Formatter('%(asctime)s %(name)s %(lineno)d [%(levelname)s][%(funcName)s] %(message)s ') handler = StreamHandler() handler.setLevel('INFO') handler.setFormatter(log_fmt) logger.addHandler(handler) handler = FileHandler('{0}/{1}.log'.format(outdir, file_name), 'a') handler.setLevel(DEBUG) handler.setFormatter(log_fmt) logger.setLevel(DEBUG) logger.addHandler(handler) return logger def load_vectors(fname): fin = io.open(fname, 'r', encoding='utf-8', newline='\n', errors='ignore') n, d = map(int, fin.readline().split()) embed_matrix = np.zeros((n + 2, d)) # 語彙数はPAD, UNKを足す vocab = [PAD, UNK] i = 2 for line in fin: tokens = line.rstrip().split(' ') # 語彙リストに単語を追加 w = tokens.pop(0) vocab.append(w) # embed_matrixにベクトルを追加 v = np.asarray(tokens, dtype='float32') embed_matrix[i] = v i += 1 return embed_matrix, vocab def to_sep_space(txt): txt = mojimoji.zen_to_han(txt) # 英数字は全て半角 txt = re.sub(r'\d+', '0', txt) # 連続した数字を0で置換 parsed = WAKATI.parse(txt) sep_txt = [i.split('\t')[0] for i in parsed.split('\n') if i not in ['', 'EOS']] return ' '.join(sep_txt) def get_sim_index(vec, vecs): sim = cosine_similarity(vec, vecs) sort_i = np.argsort(sim)[0][::-1] sim = np.sort(sim)[0][::-1] return sort_i, sim def show_sim_faq(df, sim, n_top=3): index = 0 for _, row in df.iterrows(): print('-----------------------------') print('[{0}位] {1}: {2} ({3})'.format(index + 1, row['q_id'], row['q_txt'], sim[index])) print() print('{0}'.format(row['a_txt'])) print('-----------------------------') index += 1 if index >= n_top: break """ WikiQA """ def load_glove_vectors(fname, d): fin = io.open(fname, 'r', encoding='utf-8', newline='\n', errors='ignore') fin = [line for line in fin] n = len(fin) embed_matrix = np.zeros((n + 2, d)) # 語彙数はPAD, UNKを足す vocab = [PAD, UNK] i = 2 for line in fin: tokens = line.rstrip().split(' ') # 語彙リストに単語を追加 w = tokens.pop(0) vocab.append(w) # embed_matrixにベクトルを追加 v = np.asarray(tokens, dtype='float32') embed_matrix[i] = v i += 1 return embed_matrix, vocab def load_text(fname): txt_lst = [] with open(WIKIQA_DIR + '/' + fname, 'r') as f: for line in f.readlines()[1:]: sep_line = line.split('\t') txt_lst.append(sep_line[1]) txt_lst.append(sep_line[5]) return [trim(i) for i in txt_lst] def trim(sentence): sentence = sentence.lower() _ignores = re.compile("[.,-/\"'>()&;:]") sep = ['' if w in STOPWORDS or _ignores.match(w) else w for w in sentence.split()] sep = [i for i in sep if i != ''] return ' '.join(sep) def load_wikiqa(): txt = load_text('WikiQA-train.tsv') # txt += load_text('WikiQA-dev.tsv') # txt += load_text('WikiQA-test.tsv') txt = [i for i in txt if len(i.split()) > 0] txt = list(set(txt)) return txt """ NNLM """ def execute(tensor): with tf.Session() as sess: sess.run(tf.global_variables_initializer()) sess.run(tf.tables_initializer()) return sess.run(tensor) <file_sep>/src/muscle_qa_nnlm.py import six import tensorflow_hub as hub import pandas as pd from functions import get_logger, execute, to_sep_space, get_sim_index, show_sim_faq from config import LOGDIR, JA_NNLM_MODEL, MUSCLE_QA def main(): logger = get_logger(LOGDIR) logger.info('start') logger.info('load faq data') qa_df = pd.read_csv(MUSCLE_QA) q_txt = qa_df['q_txt'].tolist() sep_q_txt = [to_sep_space(i) for i in q_txt] logger.info('load NN Language Model') embed = hub.Module(JA_NNLM_MODEL) embeddings = embed(sep_q_txt) logger.info('to vectors') vecs = execute(embeddings) logger.info('vector shape: {}'.format(vecs.shape)) while True: text = six.moves.input('>> ') if text == '': break sep_input = to_sep_space(text) embeddings = embed([sep_input]) vec = execute(embeddings) sort_i, sim = get_sim_index(vec, vecs) df = qa_df.loc[sort_i] show_sim_faq(df, sim) logger.info('end') if __name__ == '__main__': main() <file_sep>/src/config.py PAD = 'PAD' UNK = 'UNK' LOGDIR = './result' JAWIKI_MODEL = '../data/entity_vector/entity_vector.model.txt' MUSCLE_TEXT = '../data/muscle_text.csv' MUSCLE_MODEL = LOGDIR + '/autoencoder.h5' MUSCLE_CORPUS = LOGDIR + '/muscle_corpus.pkl' MUSCLE_QA = '../data/muscle_qa.csv' GLOVE_MODEL = '../data/glove.6B/glove.6B.300d.txt' GLOVE_SIZE = 300 WIKIQA_DIR = '../data/WikiQACorpus/' WIKIQA_MODEL = LOGDIR + '/wikiqa.h5' WIKIQA_CORPUS = LOGDIR + '/wikiqa_corpus.pkl' EN_NNLM_MODEL = 'https://tfhub.dev/google/nnlm-en-dim128/1' JA_NNLM_MODEL = 'https://tfhub.dev/google/nnlm-ja-dim128/1' <file_sep>/src/return_corpus.py import pickle import numpy as np import pandas as pd from functions import to_sep_space from config import PAD, UNK, MUSCLE_TEXT class ReutersMuscleCorpus(): def __init__(self): self.vocab = [] self.documents = [] self.embed_matrix = None self.pad_id = None self.unk_id = None self.seq_size = None def build(self, embed_matrix, vocab, seq_size): self.vocab = vocab self.pad_id = self.vocab.index(PAD) self.unk_id = self.vocab.index(UNK) self.embed_matrix = embed_matrix self.seq_size = seq_size self.set_documents() def set_documents(self): df = pd.read_csv(MUSCLE_TEXT) self.documents = df['text'].tolist() self.documents = [to_sep_space(doc) for doc in self.documents] def doc2ids(self, sentence): ids = [self.vocab.index(word) if word in self.vocab else self.unk_id for word in sentence.split()][:self.seq_size] if len(ids) < self.seq_size: ids += [self.pad_id] * (self.seq_size - len(ids)) return np.array(ids) def batch_iter(self, batch_size): n_step = self.get_step_count(batch_size) docs_i = np.array([self.doc2ids(doc) for doc in self.documents]) while True: indices = np.random.permutation(np.arange(len(docs_i))) for s in range(n_step): index = s * batch_size x = docs_i[indices[index:(index + batch_size)]] x_vec = self.embed_matrix[x] yield x_vec, x_vec def get_step_count(self, batch_size): n_docs = len(self.documents) return n_docs // batch_size def save(self, path): with open(path, 'wb') as f: pickle.dump(self, f) @classmethod def load(cls, path): with open(path, 'rb') as f: corpus = pickle.load(f) return corpus <file_sep>/src/ae_train.py from keras.callbacks import TensorBoard, ModelCheckpoint from net import AutoEncoder from return_corpus import ReutersMuscleCorpus from functions import get_logger, load_vectors from config import LOGDIR, JAWIKI_MODEL, MUSCLE_CORPUS, MUSCLE_MODEL seq_size = 15 batch_size = 4 n_epoch = 20 latent_size = 512 def main(): logger = get_logger(LOGDIR) logger.info('start') logger.info('1. Load Japanese word2vec embeddings.') embed_matrix, vocab = load_vectors(JAWIKI_MODEL) logger.info('embedding shape is {}'.format(embed_matrix.shape)) logger.info('2. Prepare the corpus.') corpus = ReutersMuscleCorpus() corpus.build(embed_matrix, vocab, seq_size) corpus.save(MUSCLE_CORPUS) logger.info('3. Make autoencoder model.') ae = AutoEncoder(seq_size=seq_size, embed_size=embed_matrix.shape[1], latent_size=latent_size) ae.build() logger.info('4. Train model.') ae.model.compile(optimizer="adam", loss="mse") train_iter = corpus.batch_iter(batch_size) train_step = corpus.get_step_count(batch_size) valid_iter = corpus.batch_iter(batch_size) valid_step = corpus.get_step_count(batch_size) ae.model.fit_generator( train_iter, train_step, epochs=n_epoch, validation_data=valid_iter, validation_steps=valid_step, callbacks=[ TensorBoard(log_dir=LOGDIR), ModelCheckpoint(filepath=MUSCLE_MODEL, save_best_only=True) ] ) logger.info('end') if __name__ == '__main__': main() <file_sep>/src/scraping_text.py import re import pandas as pd from itertools import chain from bs4 import BeautifulSoup import requests URL = 'http://weighttrainingfaq.org/wiki/index.php' GET_INFO_1 = '%A4%E8%A4%AF%A4%A2%A4%EB%BC%C1%CC%E4' GET_INFO_2 = '%A5%A6%A5%A7%A5%A4%A5%C8%A5%C8%A5%EC%A1%BC%A5%CB%A5%F3%A5%B0%CD%D1%B8%EC%BC%AD%C5%B5' GET_INFO_3 = '%B8%BA%CE%CC%A1%A2%A5%C0%A5%A4%A5%A8%A5%C3%A5%C8' GET_INFO_4 = '%B1%C9%CD%DC%A1%A2%A5%B5%A5%D7%A5%EA%A5%E1%A5%F3%A5%C8%2F%A5%D7%A5%ED%A5%C6%A5%A4%A5%F3' GET_INFO_5 = '%A5%C8%A5%EC%A1%BC%A5%CB%A5%F3%A5%B0%CA%FD%CB%A1' GET_INFO_6 = '%BD%C0%C6%F0%A1%A2%A5%B9%A5%C8%A5%EC%A5%C3%A5%C1' GET_INFO_7 = '%A5%A4%A5%F3%A5%CA%A1%BC%A5%DE%A5%C3%A5%B9%A5%EB%A4%CE%A5%C8%A5%EC%A1%BC%A5%CB%A5%F3%A5%B0' GET_INFO_8 = '%B6%BB%A4%CE%A5%C8%A5%EC%A1%BC%A5%CB%A5%F3%A5%B0' STOP_PATTERN = '†|↑|A.|Q.' MIN_LEN = 10 def get_text(get_info): headers = {"User-Agent": "trtd"} url = URL + '?' + get_info resp = requests.get(url, timeout=3, headers=headers, verify=False) soup = BeautifulSoup(resp.text, 'html5lib') elem = soup.find_all(id='body')[0] text = [line for line in elem.text.split('\n')] text = [re.sub(STOP_PATTERN, '', line) for line in text] text = list(chain.from_iterable([line.split('。') for line in text])) text = [line for line in text if len(line) > MIN_LEN] return text texts = get_text(GET_INFO_1) texts += get_text(GET_INFO_2) texts += get_text(GET_INFO_3) texts += get_text(GET_INFO_4) texts += get_text(GET_INFO_5) texts += get_text(GET_INFO_6) texts += get_text(GET_INFO_7) texts += get_text(GET_INFO_8) df = pd.DataFrame({'text': texts}) df.to_csv('../data/muscle_text.csv', index=None) <file_sep>/src/eval_nnlm.py import tensorflow_hub as hub import pandas as pd from functions import get_logger, execute, get_sim_index from config import LOGDIR, WIKIQA_DIR, EN_NNLM_MODEL def main(): logger = get_logger(LOGDIR) logger.info('start') logger.info('load NN Language Model') embed = hub.Module(EN_NNLM_MODEL) qa_df = pd.read_csv(WIKIQA_DIR + '/WikiQA-test.tsv', sep='\t') maps = [] mrrs = [] for q_id in qa_df['QuestionID'].unique(): df = qa_df[qa_df['QuestionID'] == q_id] if 1 not in df['Label'].unique(): logger.debug('{0}: not answer'.format(q_id)) continue q_doc = df['Question'].iloc[0].lower() embeddings = embed([q_doc]) q_vec = execute(embeddings) a_docs = df['Sentence'].map(lambda x: x.lower()).tolist() embeddings = embed(a_docs) a_vecs = execute(embeddings) sort_i, sim = get_sim_index(q_vec, a_vecs) labels = [i for i, v in enumerate(df['Label']) if v == 1] rank = [i + 1 for i, v in enumerate(sort_i) if v in labels] _mrr = 1 / rank[0] _map = sum([1 / i for i in rank]) / len(rank) maps.append(_map) mrrs.append(_mrr) logger.info('{0}: MAP {1}, MRR {2}'.format(q_id, _map, _mrr)) map_avg = sum(maps) / len(maps) mrr_avg = sum(mrrs) / len(mrrs) logger.info('MAP AVG {0} / MRR AVG {1}'.format(map_avg, mrr_avg)) logger.info('end') if __name__ == '__main__': main()
94b9a1fccb5dc82a38beb2e537f3d53d80dcacb5
[ "Python" ]
10
Python
trtd56/MuscleQA
46aa64b944b0d26282028a01e63b88d13e94db9d
307f22a44df79d8ad44cc62cdfcf87596abf2c73
refs/heads/master
<repo_name>arvsander8/reactjsConsumeREST<file_sep>/README.md # reactjsConsumeREST ## API GETWAY Configuration ### API Methods configuration to enabled CORS Headers 1. Go to console menu from AWS 2. Click on API GATEWAY Link 3. Select reourses tab in the left panel 1. Select a method to assigne the headers access ![Alt paso1](imgs/reactjsConsumeREST_2.png) 2. In the right opened panel, choose ***Respuesta de Método*** ![Alt paso2](imgs/reactjsConsumeREST_3.png) * Expand the *200* option from the ***Estado HTTP*** * Click on ***Agregar encabezado*** ![Alt paso2](imgs/reactjsConsumeREST_4.png) * You need to add the next headers now.: * `X-Requested-With` * `Access-Control-Allow-Headers` * `Access-Control-Allow-Origin` * `Access-Control-Allow-Methods` ![Alt paso2](imgs/reactjsConsumeREST_5.png) 3. In the right panel, choose ***Respuestas de Integración*** ![Alt paso2](imgs/reactjsConsumeREST_6.png) * Expand the *row with status 200* * Expand ***Mapeos de encabezado*** ![Alt paso2](imgs/reactjsConsumeREST_7.png) * Add the mapping value (***Valor de mapeo***) to all options like that and save changes: Encabezado de Respuesta | Valor de mapeo -------------------------- |--------------------------- X-Requested-With | '*' Access-Control-Allow-Headers | 'Content-Type,x-requested-with,Access-Control-Allow-Origin,Access-Control-Allow-Headers,Access-Control-Allow-Methods' Access-Control-Allow-Origin | '*' Access-Control-Allow-Methods | 'POST, GET, OPTIONS' ![Alt paso2](imgs/reactjsConsumeREST_8.png) 4. Finally, Deploy again the API ![Alt paso2](imgs/reactjsConsumeREST_9.png) <file_sep>/clientes-app/src/App.js import React, { Component } from 'react'; import { Input, FormGroup, Label, Modal, ModalHeader, ModalBody, ModalFooter, Table, Button } from 'reactstrap'; import axios from 'axios'; class App extends Component { constructor(props){ super(props); this.state = { clients: [], newClientData:{ id: 2, nombre: '', apellido: '' }, editClientData: { id: '', nombre: '', apellido: '' }, deleteClientData: { id: '' }, newClientModal: false, editClientModal: false } } toggleNewClientModal() { this.setState({ newClientModal: ! this.state.newClientModal }); } toggleEditClientModal() { this.setState({ editClientModal: ! this.state.editClientModal }); } updateClient() { //let { nombre, apellido } = this.state.editClientData; axios.put('https://epgk5i5g2h.execute-api.us-east-1.amazonaws.com/desarrollo/leertabla', this.state.editClientData) .then((response) => { this.setState({ editClientModal: false, editClientData: { id: '', nombre: '', apellido: '' } }); this._refreshClients(); }); } editClient(id, nombre, apellido) { this.setState({ editClientData: { id, nombre, apellido }, editClientModal: ! this.state.editClientModal }); } deleteClient(id) { axios.delete('https://epgk5i5g2h.execute-api.us-east-1.amazonaws.com/desarrollo/leertabla' , {data:{"id": id}}).then((response) => { this._refreshClients(); }); } addClient() { axios.post('https://epgk5i5g2h.execute-api.us-east-1.amazonaws.com/desarrollo/leertabla', this.state.newClientData) .then((response) => { let { clients } = this.state; clients.push(response.data); this.setState({ clients, newClientModal: false, newClientData: { id: 2, nombre: '', apellido: '' }}); this._refreshClients(); }); } componentWillMount(){ this._refreshClients(); } _refreshClients(){ /*fetch('https://epgk5i5g2h.execute-api.us-east-1.amazonaws.com/desarrollo/leertabla') .then( res => res.json()) .then( res => { this.setState({ clientes: res, isLoaded: true }); }) .catch( error => { console.log(error); }) */ axios.get('https://epgk5i5g2h.execute-api.us-east-1.amazonaws.com/desarrollo/leertabla') .then((response) => { this.setState({ clients: response.data }) }); } render() { let clients = this.state.clients.map((client) => { return( <tr key={client.id}> <td>{client.id}</td> <td>{client.nombre}</td> <td>{client.apellido}</td> <td> <Button color="success" size='sm' className="mr-2" onClick={this.editClient.bind(this, client.id, client.nombre, client.apellido)}>Edit</Button> <Button color="danger" size='sm' onClick={this.deleteClient.bind(this, client.id)}>Delete</Button> </td> </tr> ); }); return ( <div className="App container"> <h1>Ejemplo de Clientes</h1> <Button className="my-3" color="primary" onClick={this.toggleNewClientModal.bind(this)}>Nuevo Cliente</Button> <Modal isOpen={this.state.newClientModal} toggle={this.toggleNewClientModal.bind(this)}> <ModalHeader toggle={this.toggleNewClientModal.bind(this)}>Agregar Cliente</ModalHeader> <ModalBody> <FormGroup> <Label for="ide">Id</Label> <Input id="ide" value={this.state.newClientData.id} onChange={(e) => { let { newClientData } = this.state; newClientData.id = e.target.value; this.setState({ newClientData }); }} /> </FormGroup> <FormGroup> <Label for="nombre">Nombres</Label> <Input id="nombre" value={this.state.newClientData.nombre} onChange={(e) => { let { newClientData } = this.state; newClientData.nombre = e.target.value; this.setState({ newClientData }); }} /> </FormGroup> <FormGroup> <Label for="apellido">Apellidos</Label> <Input id="apellido" value={this.state.newClientData.apellido} onChange={(e) => { let { newClientData } = this.state; newClientData.apellido = e.target.value; this.setState({ newClientData }); }} /> </FormGroup> </ModalBody> <ModalFooter> <Button color="primary" onClick={this.addClient.bind(this)}>Agregar Cliente</Button>{' '} <Button color="secondary" onClick={this.toggleNewClientModal.bind(this)}>Cancel</Button> </ModalFooter> </Modal> <Modal isOpen={this.state.editClientModal} toggle={this.toggleEditClientModal.bind(this)}> <ModalHeader toggle={this.toggleEditClientModal.bind(this)}>Editar un Cliente</ModalHeader> <ModalBody> <FormGroup> <Label for="nombre">Nombres</Label> <Input id="nombre" value={this.state.editClientData.nombre} onChange={(e) => { let { editClientData } = this.state; editClientData.nombre = e.target.value; this.setState({ editClientData }); }} /> </FormGroup> <FormGroup> <Label for="apellido">Apellidos</Label> <Input id="apellido" value={this.state.editClientData.apellido} onChange={(e) => { let { editClientData } = this.state; editClientData.apellido = e.target.value; this.setState({ editClientData }); }} /> </FormGroup> </ModalBody> <ModalFooter> <Button color="primary" onClick={this.updateClient.bind(this)}>Atualizar Cliente</Button>{' '} <Button color="secondary" onClick={this.toggleEditClientModal.bind(this)}>Cancel</Button> </ModalFooter> </Modal> <Table> <thead> <tr> <th> # --> </th> <th> Nombres </th> <th> Apellidos </th> <th> Acciones</th> </tr> </thead> <tbody> {clients} </tbody> </Table> </div> ); } } export default App; <file_sep>/clientes-app/README.md # Ejemplo de Clientes con REST de AWS
4ffb8951328fd8556e0c27d6189f63a97180c077
[ "Markdown", "JavaScript" ]
3
Markdown
arvsander8/reactjsConsumeREST
aba8842e06101f7a39ed139219e4958d3f4b7bd9
5136fe6e70c6aa412598805d4d617d245b93b1f6
refs/heads/master
<repo_name>skylar04yue/gmsdev<file_sep>/index.php <?php include'mena.php'; $warn = null; $validity = 2; $status = null; $loginstatus = null; //Login if(isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response']){ // var_dump($_POST); $secret = "<KEY>"; $captcha = $_POST['g-recaptcha-response']; $ip = $_SERVER['REMOTE_ADDR']; $rsp =file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remotepip$ip"); var_dump($rsp); $arr = json_decode($rsp,TRUE); if($arr['success']){ $validity = 1; echo 'DOne'; } else { $validity = 2; echo 'spam'; } } if (!isset($_SESSION["attempts"])) $_SESSION["attempts"] = 0; if(isset($_POST['login']) ){ $login_email = $strip->strip($_POST['login_email']); $login_password = md5($strip->strip($_POST['login_password'])); $loginstatus = $_SESSION["attempts"]; if ($_SESSION["attempts"] < 2) { $userl = $func->select_logic('userstbl',array('username','=',$login_email),'AND',array('password','=',$login_password)); if (count($userl)==1){ $_SESSION['userid'] = $userl[0]['userID']; $_SESSION['permission'] = $userl[0]['permission']; $permit = $_SESSION['permission']; if ($permit == 1){ header('location:studlist.php'); } else if ($permit == 2){ header('location:studlist.php'); } else { header('location:index.php'); } } else { $_SESSION["attempts"] = $_SESSION["attempts"] + 1; $loginstatus = $_SESSION["attempts"] . " try(ies)"; } } else { $loginstatus = "You've failed too many times, dude. Try again after 10 secs"; $_SESSION['locked'] = 'locked'; $_SESSION['timeup'] = time(); } } if(isset($_SESSION['timeup'])){ //Figure out how many seconds have passed //since the user was last active. $secondsInactive = time() - $_SESSION['timeup']; //Convert our minutes into seconds. $expireAfterSeconds = 10; //Check to see if they have been inactive for too long. if($secondsInactive >= $expireAfterSeconds){ //User has been inactive for too long. //Kill their session. session_unset(); session_destroy(); } header("Refresh: 10;url='index.php'"); } ?> <!DOCTYPE html> <head> <title>Registration</title> <style> .container .well{ background-color: #0080ff; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } h1{ color:white; } p#warn{ color:red; font-weight:600; } </style> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <script> document.getElementById('signuplog').className = "active"; </script> <br> <br> <br> <div class="container"> <div class="col-lg-4"> </div> <div class="col-lg-4"> <div class="well well-lg"> <?php if(isset($_SESSION['locked']) ) { ?> <H1><?php echo $loginstatus; ?></H1> <?php } else { ?> <form method="POST" action=""> <div class="form-group"> <p><?php echo $loginstatus; ?> </p> <H1>Log In</H1> </div> <div class="form-group"> <input type="text" placeholder="Enter Username Here.." class="form-control" name="login_email"> </div> <div class="form-group"> <input type="password" placeholder="Enter Password Here.." class="form-control" name="login_password"> </div> <button type="submit" class="btn btn-lg btn-info" name="login">Login</button> </form> <?php } ?> </div> </div> <div class="col-lg-4"> </div> </div> </body><file_sep>/vars/Jodell09553846491coursevar.php <?php $studtext = NULL; ?><file_sep>/prereqedit.php <?php include'menu.php'; include'menuside_dash.php'; if (isset($_POST['savesubbut'])){ $selectprereq= $strip->strip($_POST['select_prereq']); $selecttosubj= $strip->strip($_POST['select_tosubj']); //echo '<script>alert('.$selectprereq.');</script>'; //echo '<script>alert('.$selecttosubj.');</script>'; $pid=$_POST['idnya']; $courseUpdate = $func->update('prereqtbl','prereqID',$pid, array( 'prereqSub' => $selectprereq, 'subjID' => $selecttosubj )); if($courseUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING FAILED !!");</script>'; } } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#000; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('main').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs">Course </p> <div id="page-inner"> <div class="row" > <div class="col-lg-12 form-group paper"> <br> <p id="pangs" >Edit Pre-requisite Subjects:</p> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('prereqtbl',array('prereqID','=',$col)); if ($cors){ ?> <strong><a href="prereq.php">Back to List</a></strong> <form method="POST" name="add_subject"> <div id="addnewsubject" > <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-2 control-label" style="text-align: right">Pre-req:</label> <div class="col-md-8"> <select class="form-control" name="select_prereq"> <?php $courselist = $func->selectallorderby('subjtbl','subjCode','ASC'); for($n=0;$n<count($courselist);$n++){ ?> <option value="<?php echo escape($courselist[$n]['subjID']); ?>" <?php if ($cors[0]['prereqSub'] == $courselist[$n]['subjID'] ){?> selected="selected" <?php } ?>> <?php echo escape($courselist[$n]['subjCode']) ." - ". escape($courselist[$n]['subjTitle']); ?></option> <?php } ?> </select> </div> </div> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-2 control-label" style="text-align: right">to Subject :</label> <div class="col-md-8"> <select class="form-control" name="select_tosubj"> <?php $courselist2 = $func->selectallorderby('subjtbl','subjCode','ASC'); for($n=0;$n<count($courselist2);$n++){ ?> <option value="<?php echo escape($courselist2[$n]['subjID']); ?>" <?php if ($cors[0]['subjID'] == $courselist2[$n]['subjID'] ){?> selected="selected" <?php } ?>> <?php echo escape($courselist2[$n]['subjCode']) ." - ". escape($courselist2[$n]['subjTitle']); ?></option> <?php } ?> </select> </div> </div> <div class="col-md-11"> <input type="hidden" name = "idnya" value="<?php echo $cors[0]['prereqID'] ?>"> <?php } ?> <button type="submit" class="btn btn-md btn-info" name="savesubbut" style="float: right" >Submit</button> </div> </div> </div> </form> </div> </div> </div> <file_sep>/vars/majorvar.php <?php $majortext = 'net'; ?><file_sep>/load-jdyn.php <?php include 'menu.php'; $comNewCount = $_POST['comNewCount']; $subjlist1 = $func->select_one('curri_subjtbl',array('currID','=',$comNewCount)); echo '<select class="form-control" name="select_subj" id="mycross">'; for($n=0;$n<count($subjlist1);$n++){ echo '<option value="'. escape($subjlist1[$n]['subjID']) .'">'; $subjtp = $func->select_one_orderby('subjtbl',array('subjID','=',$subjlist1[$n]['subjID']),'subjCode','ASC'); echo escape($subjtp[0]['subjCode']) ." - " . escape($subjtp[0]['subjTitle']); echo '</option>'; } echo "</select>"; ?> <file_sep>/dashboard.php <?php include'menu.php'; include'menuside_dash.php'; include 'vars/'.$usern.'coursevar.php'; //add course if (isset($_POST['addcoursebut'])){ $coursetitle= $strip->strip($_POST['course_title']); $courseacro= $strip->strip($_POST['course_acro']); $coursedept= $strip->strip($_POST['course_dept']); //checking if acronym is still available $selectCourseAcro = $func->select_one('coursetbl',array('courseAcro','=',$courseacro)); if($selectCourseAcro){ echo '<script>alert("ADDING COURSE FAILED: same acronym already exist!!");</script>'; } else { $courseInsert = $func->insert('coursetbl',array( 'courseTitle' => $coursetitle, 'courseAcro' => $courseacro, 'courseDept' => $coursedept )); echo '<script>alert("New Course Added Successfully");</script>'; } } // display table content $y = 1; $sttt = null; if ((isset($_POST['delete']))) { $mid = $_POST['mid']; //echo '<script> alert('.$totalcountrow .');</script>'; $delcourse = $func->delete('coursetbl',array('courseID','=',$mid)); if ($delcourse){ echo '<script> alert("Record Deleted");</script>'; } else { echo '<script> alert("Delete failed");</script>'; } } $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; $perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 10; //Positioning $start = ($page > 1) ? ($page * $perPage) - $perPage : 0; //Pages //check queries with search if ((isset($_POST['Coursebut']))) { $corsname = $_POST['searchcors']; $cours = $func->select_like('coursetbl',array('courseAcro','courseTitle','courseDept',$corsname )); $totalcountrow = count($cours); //echo '<script> alert('.$totalcountrow .');</script>'; //$pages = ceil($totalcountrow/$perPage); $view = $cours; $studtext = $corsname; $var_str = var_export($studtext, true); $var = "<?php\n\n\$studtext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'coursevar.php', $var); }else if ($studtext != null && (isset($_POST['sortAcroDesc'])) ) { $cours = $func->select_like('coursetbl',array('courseAcro','courseTitle','courseDept',$studtext )); $totalcountrow = count($cours); //$pages = ceil($totalcountrow/$perPage); $view = $cours; } else if ($studtext != null && (isset($_POST['sortAcroAsc']))) { $cours = $func->select_like('coursetbl',array('courseAcro','courseTitle','courseDept',$studtext )); $totalcountrow = count($cours); //$pages = ceil($totalcountrow/$perPage); $view = $cours; }else if ((isset($_POST['sortAcroDesc']))) { $cours = $func->selectallorderby('coursetbl','courseAcro','DESC'); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('coursetbl','courseAcro','DESC',$start,$perPage); } else if ((isset($_POST['sortAcroAsc']))) { $cours = $func->selectallorderby('coursetbl','courseAcro','ASC'); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('coursetbl','courseAcro','ASC',$start,$perPage); } else { $cours = $func->selectallorderby('coursetbl','courseAcro','ASC'); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('coursetbl','courseAcro','ASC',$start,$perPage); $totalcountrow = count($cours); $studtext = $corsname; $var_str = var_export($studtext, true); $var = "<?php\n\n\$studtext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'coursevar.php', $var); } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#fff; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('main').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs">Course </p> <div id="page-inner"> <div class="row" > <div class="col-lg-12 form-group"> <button type="button" class="btn btn-success" data-toggle="collapse" data-target="#addnewcourse">Add New Course</button> <br> <form method="POST" name="add_course"> <div id="addnewcourse" class=" collapse"> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label"></label> <label class="col-md-2 control-label">Course Title</label> <div class="col-md-8"> <input type="text" placeholder="Ex: B.S. Information Technology" class="form-control" name="course_title" required> <br> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label"></label> <label class="col-md-2 control-label">Acronym:</label> <div class="col-md-3"> <input type="text" placeholder="Ex: BSIT" class="form-control" name="course_acro" required> </div> <label class="col-md-2 control-label">Department:</label> <div class="col-md-3"> <input type="text" placeholder="Ex: CICT" class="form-control" name="course_dept" required> </div> </div> <button type="submit" class="btn btn-md btn-info" name="addcoursebut" style="float:right">Submit</button> </div> </div> </div> </form> <div class="col-lg-12"> <hr> <h3>Course List: </h3> <div class="row" > <form method="POST"> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Search Name:</label> <div class="col-md-4"> <input type="text" class="form-control" name="searchcors" > </div> <div class="col-md-2"> <input type="submit" name="Coursebut" value="search" class="btn btn-primary"> </div> </div> </form> </div> </div> <div class="col-lg-12"> <div class="row" > <center> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table width:800px class="table table-hover" height:100px; overflow: scroll; > <form method="POST"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No</td> <td>Course Acronym <input type="submit" name="sortAcroAsc" value="<?php echo chr(30)?>" class="btn btn-info"> <input type="submit" name="sortAcroDesc" value="<?php echo chr(31)?>" class="btn btn-info"> </td> <td>Course Title</td> <td>Department</td> <td >Action</td> </tr> </form> <?php if (count($view) == 0) { echo "No Post Available"; } else { //echo '<script> alert('.count($view) .');</script>'; for($x=0;$x<count($view);$x++){ $y = ($y + 1)*$page; //echo '<script> alert('.$x .');</script>'; ?> <tr > <td> <?php if($page>1){ $pagec = (($page *10)-10) + $x +1; echo $pagec; } else { echo $x +1; } ?> </td> <td> <?php echo escape($view[$x]['courseAcro']); ?> </td> <td> <?php echo escape($view[$x]['courseTitle']); ?> </td> <td> <?php echo escape($view[$x]['courseDept']); ?> </td> <form method="POST"> <input type="hidden" name="mid" value="<?php echo escape($view[$x]['courseID']); ?>"> <td> <a href="dashboardedit.php?id=<?php echo escape($view[$x]['courseID']); ?> " id=".<?php echo escape($x) +1; ?>."><button type="button" class="btn btn-success">Edit</button></a> <input type="submit" name="delete" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?')"> </td> </form> </tr> <?php } } ?> </table> </center> <ul class="actions pagination"> <?php for($x = 1; $x <= $pages; $x++): ?> <li><a href="?page=<?php echo $x; ?>"<?php if($page === $x) {echo ' class="button selected"';} ?>><?php echo $x; ?></a></li> <?php endfor; ?> </ul> </div> </div> </div> </div> </div> <file_sep>/account.php <?php include 'menu.php'; if($_COOKIE['registerna'] == 1){ echo '<script> alert("New Registration was Successful");</script>'; setcookie("registerna",""); } else if($_COOKIE['registerna'] == 2){ echo '<script> alert("Registration failed");</script>'; setcookie("registerna",""); } //signup for staff if (isset($_POST['signup'])){ $reg_fname= $strip->strip($_POST['reg_fname']); $reg_lname= $strip->strip($_POST['reg_lname']); $reg_mname= $strip->strip($_POST['reg_midname']); $reg_nname= $strip->strip($_POST['reg_nickname']); $reg_address= $strip->strip($_POST['reg_address']); $reg_bday= $strip->strip($_POST['reg_bday']); $reg_cpno= $strip->strip($_POST['reg_cpno']); $reg_gender= $strip->strip($_POST['reg_gender']); $reg_email= $strip->strip($_POST['reg_email']); $reg_user1= $strip->strip($_POST['reg_user1']); $reg_user2= $strip->strip($_POST['reg_user2']); $reg_password1= $strip->strip($_POST['reg_password1']); $reg_password2= $strip->strip($_POST['reg_password2']); //checking if username is still available $selectUser = $func->select_one('userstbl',array('username','=',$reg_user1)); if($selectUser){ $warn ="Username already Taken"; } else { //set registration info into cookies setcookie("regfname", $reg_fname, time() + 3600); setcookie("reglname", $reg_lname, time() + 3600); setcookie("regmname", $reg_mname, time() + 3600); setcookie("regnname", $reg_nname, time() + 3600); setcookie("regaddress", $reg_address, time() + 3600); setcookie("regbday", $reg_bday, time() + 3600); setcookie("regcpno", $reg_cpno, time() + 3600); setcookie("reggender", $reg_gender, time() + 3600); setcookie("regemail", $reg_email, time() + 3600); setcookie("reguser", $reg_user1, time() + 3600); setcookie("regpassword", md5($reg_password1), time() + 3600); $warn = $_COOKIE['regfname']; //echo '<script>alert("bakit");</script>'; header('location:verify.php'); } } ?> <!DOCTYPE html> <head> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> .container .well{ background-color: #13D8F3; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } .paper { background: #fff; padding: 30px; position: relative; } .paper, .paper::before, .paper::after { /* Styles to distinguish sheets from one another */ box-shadow: 1px 1px 1px rgba(0,0,0,0.25); border: 1px solid #bbb; } .paper::before, .paper::after { content: ""; position: absolute; height: 95%; width: 99%; background-color: #eee; } .paper::before { right: 15px; top: 0; transform: rotate(-1deg); z-index: -1; } .paper::after { top: 5px; right: -5px; transform: rotate(1deg); z-index: -2; } .wrapper { height: 550px; border : 10px double green; border-radius: 5px; overflow-y: auto; background-color:white; } .papel { background: #fff; box-shadow: /* The top layer shadow */ 0 -1px 1px rgba(0,0,0,0.15), /* The second layer */ 0 -10px 0 -5px #eee, /* The second layer shadow */ 0 -10px 1px -4px rgba(0,0,0,0.15), /* The third layer */ 0 -20px 0 -10px #eee, /* The third layer shadow */ 0 -20px 1px -9px rgba(0,0,0,0.15); /* Padding for demo purposes */ padding: 30px; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } img#propix { max-width:150px; } H1,H2, H5#pangs { font-family: 'Sonsie One';font-size: 22px; } .col-lg-2 { background-color:#add8e6; height: 550px; } hr { border: 3px dashed black; } </style> <script> document.getElementById('account').className = "active"; </script> </head> <body> <div class="container-fluid"> <br> <br> <div class="row" > <div class="col-lg-1" > </div> <div class="col-lg-10" > <br> <div class="papel"> <H1>Sign Up</H1> <div class="row"> <form method="POST" name="register" onSubmit="return formValidation();"> <div class="paper"> <p id="warn"><?php echo $warn; ?></p> <div class="col-md-12 form-group"> <H4>PERSONAL INFO</H4> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">First Name</label> <div class="col-md-4"> <input type="text" placeholder="Enter First Name Here.." class="form-control" name="reg_fname" required> </div> <label class="col-md-2 control-label">Middle Name</label> <div class="col-lg-4"> <input type="text" placeholder="Enter Middle Name Here.." class="form-control" name="reg_midname" required> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Last Name</label> <div class="col-md-4"> <input type="text" placeholder="Enter Last Name Here.." class="form-control" name="reg_lname" required> </div> <label class="col-md-2 control-label">Nickname</label> <div class="col-lg-4"> <input type="text" placeholder="Enter Nickname Here.." class="form-control" name="reg_nickname"> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Address</label> <div class="col-lg-10"> <input type="text" placeholder="Enter Address Here.." rows="3" class="form-control" name="reg_address" required> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Birthday</label> <div class="col-md-4"> <input type="date" class="form-control" name="reg_bday" required> </div> <label class="col-md-2 control-label">Gender</label> <div class="col-lg-4"> <input type="radio" name="reg_gender" value="Male" checked="checked">Male <label class="radio-inline"> <input type="radio" name="reg_gender" value="Female"> Female </label> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Email</label> <div class="col-lg-4"> <input type="email" class="form-control" name="reg_email"> </div> <label class="col-md-2 control-label">Cellphone No.</label> <div class="col-lg-4"> <input type="number" placeholder="09XXXXXXXXX" class="form-control" max="99999999999" name="reg_cpno" required> </div> </div> <div class="col-md-12 form-group"> <H4>LOG IN INFO</H4> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Username</label> <div class="col-md-4"> <input type="text" placeholder="Enter Username.." class="form-control" name="reg_user1" required> </div> <label class="col-md-2 control-label">Verify Username</label> <div class="col-lg-4"> <input type="text" placeholder="Verify Username.." class="form-control" name="reg_user2" required> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Password</label> <div class="col-md-4"> <input type="password" placeholder="Minimum of 8 characters, First character must be letter" class="form-control" name="reg_password1" required> </div> <label class="col-md-2 control-label">Verify Password</label> <div class="col-lg-4"> <input type="password" placeholder="Verify Password Here.." class="form-control" name="reg_password2" required> </div> </div> <hr> <div class="g-recaptcha" data-sitekey="<KEY>"></div> <center><button type="submit" class="btn btn-lg btn-info" name="signup" >Sign Up</button> <button type="reset" class="btn btn-lg btn-danger" name="clearfrm" onclick="location.reload();" >Clear form</button> </center> </div> </form> </div> </div> </div> </div> </div> <script> function formValidation() { var user1 = document.register.reg_user1.value; var user2 = document.register.reg_user2.value; var pass1 = document.register.reg_password1; var pass2 = document.register.reg_password2; var passlen = pass1.value.length; var passval = pass1.value; var passval2 = pass2.value; if (user1 == user2){ if (samelike(passval,passval2,'PASSWORD')){ if(passlength(passlen)){ if(alphanumeric(passval)){ return true; } } } } return false; } function samelike(formelem1,formelem2,textvalue){ if(formelem1 == formelem2){ return true; } else { alert(textvalue + " did not match"); return false; } } function passlength(pass){ if(pass < 8){ alert("Password must be minimum of 8 characters"); return false; } else { return true; } } function alphanumeric(uadd) { var letters = new RegExp('^[a-zA-Z]{1}[0-9a-zA-Z]+$'); if(uadd.match(letters)) { return true; } else { alert('Password must start with a letter'); uadd.focus(); return false; } } </script> </body> <file_sep>/majoredit.php <?php include'menu.php'; include'menuside_dash.php'; if (isset($_POST['savemajorbut'])){ $majortitle= $strip->strip($_POST['majortitle']); $selectcourse= $strip->strip($_POST['selectCourse']); $pid=$_POST['idnya']; $courseUpdate = $func->update('majortbl','majorID',$pid, array( 'MajorName' => $majortitle, 'courseID' => $selectcourse )); if($courseUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING MAJOR FAILED !!");</script>'; } } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#000; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('main').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs">Course </p> <div id="page-inner"> <div class="row" > <div class="col-lg-11 form-group paper"> <br> <p id="pangs" >Edit Major</p> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('majortbl',array('majorID','=',$col)); if ($cors){ ?> <strong><a href="major.php">Back to List</a></strong> <form method="POST" name="add_major"> <div id="editmajor"> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label"></label> <label class="col-md-2 control-label">Major Title</label> <div class="col-md-5"> <input type="text" placeholder="Ex: Programming" class="form-control" name="majortitle" value="<?php echo $cors[0]['majorName'] ?>" required> <br> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label"></label> <label class="col-md-2 control-label">Course:</label> <div class="col-md-3"> <select class="form-control" name="selectCourse"> <?php $courselist = $func->selectallorderby('coursetbl','courseAcro','ASC'); for($n=0;$n<count($courselist);$n++){ ?> <option value="<?php echo escape($courselist[$n]['courseID']); ?>" <?php if ($cors[0]['courseID'] == $courselist[$n]['courseID'] ){?> selected="selected" <?php } ?>> <?php echo escape($courselist[$n]['courseAcro']); ?></option> <?php } ?> </select> </div> <div class="col-md-3"> <input type="hidden" name = "idnya" value="<?php echo $cors[0]['majorID'] ?>"> <?php } ?> <button type="submit" class="btn btn-md btn-info" name="savemajorbut" style="float:right">Save</button> </div> </div> </div> </div> </form> </div> </div> </div> <file_sep>/chatchat.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script type="text/javascript" src="chat.js"></script> <style> #chat-wrap { border: 1px solid #eee; margin: 0 0 15px 0; } #chat-area { height: 300px; overflow: auto; border: 1px solid #666; padding: 20px; background: white; } #chat-area span { color: white; background: #333; padding: 4px 8px; -moz-border-radius: 5px; -webkit-border-radius: 8px; margin: 0 5px 0 0; } #chat-area p { padding: 8px 0; border-bottom: 1px solid #ccc; } #name-area { position: absolute; top: 12px; right: 0; color: white; font: bold 12px "Lucida Grande", Sans-Serif; text-align: right; } #name-area span { color: #fa9f00; } #sendie { border: 3px solid #999; padding: 10px; font: 12px "Lucida Grande", Sans-Serif; } </style> <script> // ask user for name with popup prompt var name = "<?php echo $peracc[0]['nickname']; ?>"; // strip tags name = name.replace(/(<([^>]+)>)/ig,""); // display name on page $("#name-area").html("You are: <span>" + name + "</span>"); // kick off chat var chat = new Chat(); $(function() { chat.getState(); // watch textarea for key presses $("#sendie").keydown(function(event) { var key = event.which; //all keys including return. if (key >= 33) { var maxLength = $(this).attr("maxlength"); var length = this.value.length; // don't allow new content if length is maxed out if (length >= maxLength) { event.preventDefault(); } } }); // watch textarea for release of key press $('#sendie').keyup(function(e) { if (e.keyCode == 13) { var text = $(this).val(); var maxLength = $(this).attr("maxlength"); var length = text.length; // send if (length <= maxLength + 1) { chat.send(text, name); $(this).val(""); } else { $(this).val(text.substring(0, maxLength)); } } }); }); </script> </head> <body onload="setInterval('chat.update()', 1000)"> <div id="page-wrap"> <h3>Express Chat</h3> <p id="name-area"></p> <div id="chat-wrap" ><div id="chat-area" ></div></div> <div class="form-group"> <form id="send-message-area"> <p>Your message: </p> <textarea id="sendie" maxlength = '100' class="form-control"></textarea> </form> </div> </div> </body> </html><file_sep>/reportstud.php <?php include 'menu.php'; //include'menuside_stud.php'; //delete enrolled course if ((isset($_POST['delete']))) { $mid = $_POST['mid']; $delregs = $func->delete('registrationtbl',array('regID','=',$mid)); if ($delregs){ echo '<script> alert("Record Deleted");</script>'; } else { echo '<script> alert("Delete failed");</script>'; } } //add major if (isset($_POST['regibut'])){ $sidnya = $strip->strip($_POST['idnya']); $select_maj = $strip->strip($_POST['select_maj']); $select_year = $strip->strip($_POST['select_year']); $select_sem = $strip->strip($_POST['select_sem']); $acad_year = $strip->strip($_POST['acad_year']); $cursection = $strip->strip($_POST['cursection']); $selectresidency = $strip->strip($_POST['select_residency']); $regInsert = $func->insert('registrationtbl',array( 'studID' => $sidnya, 'regMajor' => $select_maj, 'regYrlevel' => $select_year, 'regSem' => $select_sem, 'regAcadYr' => $acad_year, 'regSection' => $cursection, 'regResidency' => $selectresidency )); if($regInsert){ $regiId = mysqli_insert_id($con); $bagong= $strip->strip($_POST['tago']); for($nsan=1;$nsan<=$bagong;$nsan++){ $bagin = "bago". $nsan; $bags= $strip->strip($_POST[$bagin]); $gradeInsert = $func->insert('gradetbl',array( 'regID' => $regiId, 'subjID' => $bags )); } } $studyUpdate = $func->update('studtbl','studID',$sidnya, array( 'curMajor' => $select_maj, 'curYrlevel' => $select_year, 'curSem' => $select_sem, 'curSection' => $cursection )); if($studyUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING COURSE FAILED !!");</script>'; } } ?> <!DOCTYPE html> <head> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> .container .well{ background-color: #13D8F3; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } .paper { background: #fff; padding: 30px; position: relative; } .paper, .paper::before, .paper::after { /* Styles to distinguish sheets from one another */ box-shadow: 1px 1px 1px rgba(0,0,0,0.25); border: 1px solid #bbb; } .paper::before, .paper::after { content: ""; position: absolute; height: 95%; width: 99%; background-color: #eee; } .paper::before { right: 15px; top: 0; transform: rotate(-1deg); z-index: -1; } .paper::after { top: 5px; right: -5px; transform: rotate(1deg); z-index: -2; } .wrapper { height: 550px; border : 10px double green; border-radius: 5px; overflow-y: auto; background-color:white; } .papel { background: #fff; box-shadow: /* The top layer shadow */ 0 -1px 1px rgba(0,0,0,0.15), /* The second layer */ 0 -10px 0 -5px #eee, /* The second layer shadow */ 0 -10px 1px -4px rgba(0,0,0,0.15), /* The third layer */ 0 -20px 0 -10px #eee, /* The third layer shadow */ 0 -20px 1px -9px rgba(0,0,0,0.15); /* Padding for demo purposes */ padding: 30px; } a:hover { background-color: yellow; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } img#propix { max-width:100px; } H1,H2, H5#pangs { font-family: 'Sonsie One';font-size: 25px; } .col-lg-2 { background-color:#add8e6; height: 550px; } hr { border: 2px solid black; } </style> <script> document.getElementById('studlist').className = "active"; </script> </head> <body> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('studtbl',array('studID','=',$col)); if ($cors){ ?> <div class="container-fluid"> <br> <br> <div class="row" > <div class="col-lg-1" > </div> <div class="col-lg-10" > <br> <div class="papel"> <div class="col-md-12 form-group"> <div class="col-md-4"> <a href="studlist.php" > <img src ="img/showicon.png" class="img-responsive" id="propix" name="showpropix"></img> </a> </div> <div class="col-md-6"> <H1>Collection of Records</H1> </div> </div> <hr> <div class="paper"> <p id="warn"><?php echo $warn; ?></p> <div class="col-md-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Student No: </label> <label class="col-md-2 control-label"><u> <?php echo escape($cors[0]['studNum']) ?></u> </label> <label class="col-md-3 control-label" style="text-align: right">Student Name:</label> <label class="col-md-5 control-label"><u><?php echo escape($cors[0]['lName']).", ". escape($cors[0]['fName']) ." ". escape($cors[0]['mName']); ?></u> </label> <br> <label class="col-md-2 control-label" style="text-align: right">Address: </label> <label class="col-md-9 control-label"><u><?php echo escape($cors[0]['brgy']) .", ". escape($cors[0]['city']) .", ". escape($cors[0]['prov']); ?></u> </label> <br> <label class="col-md-2 control-label" style="text-align: right">Birthday: </label> <label class="col-md-2 control-label"><u> <?php echo escape($cors[0]['DOB']); ?></u> </label> <label class="col-md-3 control-label" style="text-align: right">Gender:</label> <label class="col-md-5 control-label"><u><?php if($cors[0]['gender'] == 1){ echo "male";} else {echo "female";} ?></u> </label> <br> <label class="col-md-2 control-label" style="text-align: right">Email: </label> <label class="col-md-2 control-label"><u> <?php echo escape($cors[0]['email']); ?></u> </label> <label class="col-md-3 control-label" style="text-align: right">Cellphone #:</label> <label class="col-md-5 control-label"><u> <?php echo escape($cors[0]['cpnum']); ?></u> </label> </div> <input type="hidden" name = "idnya" value="<?php echo $cors[0]['studID'] ?>">. </div> <div class="row" > <div class="col-lg-12" > <div class="paper"> <h3>Academic Status</h3> <hr> <!-- registration list --> <?php $selectrgstry = $func->select_logic('registrationtbl',array('studID','=',$col),'AND',array('regResidency','=',0)); ?> <h4>Certificate of Grades:</h4> <center> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table width:800px class="table table-hover" height:100px; overflow: scroll; id="myTable"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No.</td> <td>Course & Major</td> <td> Academic Year </td> <td> Year Level </td> <td> Sem </td> <td> Section </td> </tr> <?php if (count($selectrgstry) == 0) {echo "No Post Available"; } else { //echo '<script> alert('.$col .');</script>'; for($t=0;$t<count($selectrgstry);$t++){ ?> <tr onclick="getElementById('.<?php echo escape($t) +1; ?>.').click()" style="cursor: pointer"> <td> <?php echo $t + 1; ?> </td> <td> <?php $currinem = $func->select_one('curriculum',array('currID','=',$selectrgstry[$t]['currID'])); echo escape($currinem[0]['curriName']); ?> </td> <td> <?php echo escape($selectrgstry[$t]['regAcadYr']); ?> </td> <td> <?php if(escape($selectrgstry[$t]['regYrlevel'])== 1){ echo "1st year"; } else if(escape($selectrgstry[$t]['regYrlevel'])== 2){ echo "2nd year"; }else if(escape($selectrgstry[$t]['regYrlevel'])== 3){ echo "3rd year"; }else if(escape($selectrgstry[$t]['regYrlevel'])== 4){ echo "4th year"; }else if(escape($selectrgstry[$t]['regYrlevel'])== 5){ echo "5th year"; } ?> </td> <td> <?php if(escape($selectrgstry[$t]['regSem'])== 1){ echo "1st sem"; } else if(escape($selectrgstry[$t]['regSem'])== 2){ echo "2nd sem"; }else if(escape($selectrgstry[$t]['regSem'])== 3){ echo "Summer"; }else if(escape($selectrgstry[$t]['regSem'])== 4){ echo "Midyear"; } ?> </td> <td> <?php echo escape($selectrgstry[$t]['regSection']); ?> </td> <form method="POST"> <input type="hidden" name="mid" value="<?php echo escape($selectrgstry[$t]['regID']); ?>"> <a href="certofgrade.php?id=<?php echo escape($selectrgstry[$t]['regID']); ?> " id=".<?php echo escape($t) +1; ?>."></a> </form> </tr> <?php } } ?> </table> </div> </center> <hr> <!-- registration list --> <?php $selectpros = $func->select_distinctwhere('registrationtbl','regID','ASC',array('currID'),array('studID','=',$col)); ?> <h4>Evaluation Forms:</h4> <center> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table width:800px class="table table-hover" height:100px; overflow: scroll; id="myTable"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No.</td> <td>Course & Major</td> </tr> <?php if (count($selectpros) == 0) {echo "No Post Available"; } else { //echo '<script> alert('.$col .');</script>'; for($i=0;$i<count($selectpros);$i++){ ?> <tr onclick="getElementById('.<?php echo $rom . escape($i) +200; ?>.').click()" style="cursor: pointer"> <td><?php echo $i + 1; ?></td> <td> <?php $currinem = $func->select_one('curriculum',array('currID','=',$selectpros[$i]['currID'])); //echo '<script> alert('.$col .');</script>'; echo escape($currinem[0]['curriName']) ." ver. ". escape($currinem[0]['version']); ?> </td> <form method="POST"> <input type="hidden" name="pid" value="<?php echo escape($selectpros[$i]['currID']); ?>"> <a href="evaluation.php?id=<?php echo $selectpros[$i]['currID'];?>&studid=<?php echo $col;?>" id=".<?php echo $rom . escape($i) +200; ?>."></a> </form> </tr> <?php } } ?> </table> </div> </center> <hr> <a href="spr.php?id=<?php echo $col;?>" id=".<?php echo $rom . escape($i) +300; ?>."><h4>Student's Permanent Record</h4></a> <?php } ?><!-- end of col --> </div> </div> </div> </div> </div> </div> </div> <br> <br> <br> <script> function myFunction() { //totalRowBlgin += 1; var table = document.getElementById("myTable"); var cross = document.getElementById("mycross"); var xcross = cross.options[cross.selectedIndex].text; var unglaman = cross.value; var pang = "bago"; var pang2 = "tago"; var row = table.insertRow(-1); var cell1 = row.insertCell(0); var cell2 = row.insertCell(1); var cell3 = row.insertCell(2); //var cell4 = row.insertCell(3); // var cell5 = row.insertCell(4); var totalRowBlg = table.rows.length; totalRowBlg = table.rows.length; // totalRowBlg = totalRowBlg -1; pang = pang +totalRowBlg; cell1.innerHTML = totalRowBlg; cell2.innerHTML = xcross ; //cell2.innerHTML = "NEW CELL2"; //cell3.innerHTML = "NEW CELL3"; cell3.innerHTML = "<input type='hidden' value='"+ unglaman +"' name='"+ pang + "'> <input type='hidden' value='"+ totalRowBlg +"' name='"+ pang2 + "'>"; // cell4.innerHTML = unglaman; // cell5.innerHTML = "NEW CELL3"; // alert("totalRowBlg"); } </script> </body> <file_sep>/menuside_dash.php <head> <title>Simple Responsive Admin</title> <!-- BOOTSTRAP STYLES--> <link href="lib/assets/css/bootstrap.css" rel="stylesheet" /> <!-- FONTAWESOME STYLES--> <link href="lib/assets/css/font-awesome.css" rel="stylesheet" /> <!-- CUSTOM STYLES--> <link href="lib/assets/css/custom.css" rel="stylesheet" /> <!-- JQUERY--> <script src="lib/bootstrap/js/jquery-3.2.1.js"></script> <!-- GOOGLE FONTS--> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> <!--css style--> <style type="text/css"> #mapid { height:100%; width:100%; background:#888888; } .navbar { color: #FFFFFF; background-color: #0080ff; } </style> <?php $x =2; ?> </head> <body> <div id="mydiv"> <script> document.getElementById('dash').className = "active"; var but = document.createElement('button'); var spn1 = document.createElement('span'); var spn2 = document.createElement('span'); var spn3 = document.createElement('span'); //creates set elements attribute but.setAttribute('class','navbar-toggle'); but.setAttribute('data-toggle','collapse'); but.setAttribute('data-target','.sidebar-collapse'); spn1.setAttribute('class','icon-bar'); spn2.setAttribute('class','icon-bar'); spn3.setAttribute('class','icon-bar'); but.appendChild(spn1); but.appendChild(spn2); but.appendChild(spn3); document.getElementById('bub').appendChild(but); </script> <div id="wrapper"> <!-- /. NAV TOP --> <nav class="navbar-default navbar-side" role="navigation"> <div class="sidebar-collapse"> <ul class="nav" id="main-menu"> <h3>&nbsp;ADMIN DASHBOARD</h3> <li class="act" id="main"> <a href="dashboard.php"><i class="fa fa-university " id="lintek"></i>Course</a> </li> <li class="act" id="major"> <a href="major.php"><i class="fa fa-graduation-cap "></i>Major</a> </li > <li class="act" id="subject"> <a href="#showsubs" data-toggle="collapse" ><i class="fa fa-book " ></i>Subjects</a> </li> <div id="showsubs" class="collapse"> <ul class="nav" id="sidebar-collapse"> <li class="act" id="major"> <a href="subject.php"><i class="fa fa-list "></i>All Subjects</a> </li > <li class="act" id="major"> <a href="prereq.php"><i class="fa fa-asterisk"></i>Pre Requisite Subjects</a> </li > </ul> </div> <li class="act" id="prospectus"> <a href="#showsubspros" data-toggle="collapse"><i class="fa fa-table " ></i>Prospectus</a> </li> <div id="showsubspros" class="collapse"> <ul class="nav" id="sidebar-collapse"> <li class="act" id="major"> <a href="prospectus.php"><i class="fa fa-list "></i>Basic Info</a> </li > <li class="act" id="major"> <a href="curriculum.php"><i class="fa fa-asterisk"></i>Format</a> </li > </ul> </div> <!-- <li class="act" id="userlist"> <a href="userlist.php"><i class="fa fa-users " ></i>Users</a> </li> --> </ul> </div> </nav> </div> </div> </body><file_sep>/updategrade.php <?php include 'menu.php'; //include'menuside_stud.php'; //delete enrolled course if ((isset($_POST['updategrades']))) { $mid = $_POST['mid']; $inputratings= $strip->strip($_POST['inputratings']); $inputrexam= $strip->strip($_POST['inputrexam']); $remarks = 0; if($inputratings <= $inputrexam){ if($inputratings >= 6){ $remarks = 2; } else{ $remarks = 0; } } else { if($inputrexam <= 3){ $remarks = 1; } else{ $remarks = 0; } } //echo '<script>alert('.$mid.');</script>'; //echo '<script>alert('.$inputratings.');</script>'; $studUpdate = $func->update('gradetbl','gradeID',$mid, array( 'rating' => $inputratings, 'rexam' => $inputrexam, 'remarks' => $remarks )); if(!$studUpdate){ echo '<script>alert("EDITING GRADE FAILED !!");</script>'; } } //test if (isset($_POST['regibutton'])){ $select_maj = $strip->strip($_POST['select_maj']); $select_year = $strip->strip($_POST['select_year']); $select_sem = $strip->strip($_POST['select_sem']); $acad_year = $strip->strip($_POST['acad_year']); $cursection = $strip->strip($_POST['cursection']); $selectresidency = $strip->strip($_POST['select_residency']); $idreg= $strip->strip($_POST['idreg']); $bagong= $strip->strip($_POST['tago']); $blgna= $strip->strip($_POST['blgna']); $blgna= $blgna + 1; $regstrUpdate = $func->update('registrationtbl','regID',$idreg, array( 'regMajor' => $select_maj, 'regYrlevel' => $select_year, 'regSem' => $select_sem, 'regAcadYr' => $acad_year, 'regSection' => $cursection, 'regResidency' => $selectresidency )); if($regstrUpdate){ for($nsan= $blgna ;$nsan<=$bagong;$nsan++){ $bagin = "bago". $nsan; $bags= $strip->strip($_POST[$bagin]); $gradeInsert = $func->insert('gradetbl',array( 'regID' => $idreg, 'subjID' => $bags )); } } if($regstrUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING COURSE FAILED !!");</script>'; } } ?> <!DOCTYPE html> <head> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> .container .well{ background-color: #13D8F3; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } .paper { background: #fff; padding: 30px; position: relative; } .paper, .paper::before, .paper::after { /* Styles to distinguish sheets from one another */ box-shadow: 1px 1px 1px rgba(0,0,0,0.25); border: 1px solid #bbb; } .paper::before, .paper::after { content: ""; position: absolute; height: 95%; width: 99%; background-color: #eee; } .paper::before { right: 15px; top: 0; transform: rotate(-1deg); z-index: -1; } .paper::after { top: 5px; right: -5px; transform: rotate(1deg); z-index: -2; } .wrapper { height: 550px; border : 10px double green; border-radius: 5px; overflow-y: auto; background-color:white; } .papel { background: #fff; box-shadow: /* The top layer shadow */ 0 -1px 1px rgba(0,0,0,0.15), /* The second layer */ 0 -10px 0 -5px #eee, /* The second layer shadow */ 0 -10px 1px -4px rgba(0,0,0,0.15), /* The third layer */ 0 -20px 0 -10px #eee, /* The third layer shadow */ 0 -20px 1px -9px rgba(0,0,0,0.15); /* Padding for demo purposes */ padding: 30px; } a:hover { background-color: yellow; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } img#propix { max-width:100px; } H1, H5#pangs { font-family: 'Sonsie One';font-size: 25px; } H2 { font-family: 'Sonsie One';font-size: 17px; } #desss{ font-family: 'Sonsie One';font-size: 15px; } .col-lg-2 { background-color:#add8e6; height: 550px; } hr { border: 2px solid black; } </style> </head> <body> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('registrationtbl',array('regID','=',$col)); if ($cors){ ?> <div class="container-fluid"> <br> <br> <div class="row" > <div class="col-lg-1" > </div> <div class="col-lg-10" > <br> <div class="papel"> <div class="col-md-12 form-group"> <div class="col-md-1"> <a href="studlist.php" > <img src ="img/showicon.png" class="img-responsive" id="propix" name="showpropix"></img> </a> </div> <div class="col-md-3"> <a href="reportstud.php?id=<?php echo escape($cors[0]['studID']); ?>" ><img src ="img/reporticon.png" class="img-responsive" id="propix" name="addpropix"></img></a> </div> <div class="col-md-6"> <H1>Student Record</H1> <H2>(Grade per Registration)</H2> </div> </div> <hr> <a href="viewstud.php?id=<?php echo escape($cors[0]['studID']); ?>">Back</a> <form method="POST" name="add_student"> <div class="paper"> <?php $studinfo = $func->select_one('studtbl',array('studID','=',$cors[0]['studID'])); ?> <div class="col-md-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Student No: </label> <label class="col-md-2 control-label"><u id="desss"> <?php echo escape($studinfo[0]['studNum']) ?></u> </label> <label class="col-md-3 control-label" style="text-align: right">Student Name:</label> <label class="col-md-5 control-label"><u id="desss"><?php echo escape($studinfo[0]['lName']).", ". escape($studinfo[0]['fName']) ." ". escape($studinfo[0]['mName']); ?></u> </label> </div> </div> <div class="row" > <div class="col-lg-12" > <h3>Academic Status</h3> <div class="col-lg-12 form-group"> <div id="addnewcourse" > <div class="col-lg-12 form-group"> <!-- function selectjoin_where($table,$table2,$ref,$ref2,$table3,$where = array()){ --> <?php $majorc1 = $func->select_one('curriculum',array('currID','=',$cors[0]['currID'])); ?> <label class="col-md-2 control-label" style="text-align: right">Course & Major:</label> <label class="col-md-5 control-label" ><?php echo escape($majorc1[0]['curriName']); ?></label> <label class="col-md-2 control-label" style="text-align: right">Acad Year:</label> <label class="col-md-3 control-label" ><?php echo escape($cors[0]['regAcadYr']);?></label> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Year Level:</label> <label class="col-md-5 control-label"> <?php if($cors[0]['regYrlevel'] == '1'){ echo "1st Year"; } else if($cors[0]['regYrlevel'] == '2'){ echo "2nd Year"; } else if($cors[0]['regYrlevel'] == '3'){ echo "3rd Year"; } else if($cors[0]['regYrlevel'] == '4'){ echo "4th Year"; } else if($cors[0]['regYrlevel'] == '5'){ echo "5th Year"; } ?></label> <label class="col-md-2 control-label" style="text-align: right">Semester:</label> <label class="col-md-2 control-label"> <?php if($cors[0]['regSem'] == '1'){ echo "1st sem"; } else if($cors[0]['regSem'] == '2'){ echo "2nd sem"; } else if($cors[0]['regSem'] == '3'){echo "Summer"; } else if($cors[0]['regSem'] == '4'){ echo "Midyear"; } ?> </label> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Section:</label> <label class="col-md-5 control-label"> <?php echo escape($cors[0]['regSection']);?> </label> <label class="col-md-2 control-label" style="text-align: right">Residency :</label> <label class="col-md-3 control-label"> <?php if($cors[0]['regResidency'] == '0'){ echo "In-house"; } else if($cors[0]['regResidency'] == '1'){ echo "Transferee"; } ?> </label> </div> <div class="col-lg-12 form-group"> <div class="row" > <center> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <?php $selectenrollsub = $func->select_one('gradetbl',array('regID','=',$cors[0]['regID'])); ?> <table width:800px class="table table-hover" height:100px; overflow: scroll; id="myTable"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No.</td> <td>Subject</td> <td>Ratings</td> <td>Re-Exam</td> <td>Action</td> </tr> <?php if (count($selectenrollsub) == 0) {echo "No Post Available"; } else { //echo '<script> alert('.$col .');</script>'; for($t=0;$t<count($selectenrollsub);$t++){ ?> <tr> <td> <?php echo $t + 1; ?> </td> <form method="POST"> <td> <?php $subjlist41 = $func->select_one('subjtbl',array('subjID','=',$selectenrollsub[$t]['subjID'])); echo escape($subjlist41[0]['subjCode']) ."--". escape($subjlist41[0]['subjTitle']); ?> <input type="hidden" class="form-control" name=<?php echo "subj".$t ?> value="<?php echo escape($selectenrollsub[$t]['subjID']); ?>" ></td> <td><input type="text" class="form-control" name="inputratings" value="<?php if ($selectenrollsub[$t]['rating'] == 0){ echo null;} else {echo escape($selectenrollsub[$t]['rating']); } ?>" ></td> <td><input type="text" class="form-control" name="inputrexam" value="<?php if ($selectenrollsub[$t]['rexam'] == 0){ echo null;} else {echo escape($selectenrollsub[$t]['rexam']); } ?>" ></td> <td> <input type="hidden" name="mid" value="<?php echo escape($selectenrollsub[$t]['gradeID']); ?>"> <input type="submit" name="updategrades" value="Update" class="btn btn-success" > </td> </form> </tr> <?php } ?> <input type="hidden" class="form-control" name="blgna" value="<?php echo count($selectenrollsub); ?>"> <input type="hidden" class="form-control" name="idreg" value="<?php echo escape($cors[0]['regID']); ?>"> <?php } ?> </table> </div> </center> </div> </form> </div> <hr> <!-- registration list --> <?php } ?> </div> </div> </div> </div> </div> </div> </div> <br> <br> <br> </body> <file_sep>/database/gmsdb.sql -- phpMyAdmin SQL Dump -- version 4.8.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 08, 2020 at 04:13 PM -- Server version: 10.1.33-MariaDB -- PHP Version: 7.2.6 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: `gmsdb` -- -- -------------------------------------------------------- -- -- Table structure for table `coursetbl` -- CREATE TABLE `coursetbl` ( `courseID` int(11) NOT NULL, `courseDept` varchar(50) NOT NULL, `courseTitle` varchar(200) NOT NULL, `courseAcro` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `coursetbl` -- INSERT INTO `coursetbl` (`courseID`, `courseDept`, `courseTitle`, `courseAcro`) VALUES (1, 'CICT', 'B.S. Information Technology', 'BSIT'), (2, 'COED', 'Bachelor of Secondary Education', 'BSE'), (4, 'COED', 'Bachelor of Elementary Education', 'BEED'), (5, 'CMBT', 'B.S. Business Administration', 'BSBA'), (6, 'CICT', 'asdfasfas', 'GHDFDSA'), (7, 'BAS', 'baka', 'ASFASF'); -- -------------------------------------------------------- -- -- Table structure for table `curriculum` -- CREATE TABLE `curriculum` ( `currID` int(11) NOT NULL, `curriName` varchar(200) NOT NULL, `majorID` int(11) NOT NULL, `version` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `curriculum` -- INSERT INTO `curriculum` (`currID`, `curriName`, `majorID`, `version`) VALUES (1, 'BSIT -- Web System Technology ', 1, '1'), (2, 'BSBA -- Marketing Management ', 2, 'new'), (3, 'BSIT -- Web System Technology ', 1, 'new'), (4, 'BSE -- Filipino ', 9, 'new'), (5, 'BSIT -- Database ', 7, 'new'); -- -------------------------------------------------------- -- -- Table structure for table `curri_subjtbl` -- CREATE TABLE `curri_subjtbl` ( `cursubjID` int(11) NOT NULL, `subjID` int(11) NOT NULL, `year` int(11) NOT NULL, `sem` int(11) NOT NULL, `currID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `curri_subjtbl` -- INSERT INTO `curri_subjtbl` (`cursubjID`, `subjID`, `year`, `sem`, `currID`) VALUES (1, 4, 1, 1, 3), (2, 5, 1, 1, 3), (3, 12, 1, 2, 3), (4, 6, 1, 1, 3), (5, 13, 1, 2, 3), (6, 9, 1, 1, 4), (7, 15, 1, 1, 4), (8, 16, 1, 2, 4), (9, 17, 2, 1, 3), (10, 18, 1, 1, 2), (11, 19, 1, 1, 2), (12, 20, 1, 1, 2), (13, 7, 1, 1, 2), (14, 8, 1, 1, 2), (15, 22, 1, 1, 2), (16, 11, 1, 1, 2), (17, 23, 1, 1, 2), (18, 24, 1, 2, 2), (19, 31, 1, 2, 2), (20, 10, 1, 2, 2), (21, 25, 1, 2, 2), (22, 26, 1, 2, 2), (23, 27, 1, 2, 2), (27, 28, 1, 2, 2), (28, 29, 1, 2, 2), (29, 30, 1, 2, 2); -- -------------------------------------------------------- -- -- Table structure for table `gradetbl` -- CREATE TABLE `gradetbl` ( `gradeID` int(11) NOT NULL, `regID` int(11) NOT NULL, `studID` int(11) NOT NULL, `subjID` int(11) NOT NULL, `rating` decimal(3,2) NOT NULL, `rexam` decimal(3,2) NOT NULL, `remarks` int(2) DEFAULT NULL, `faculty` int(11) NOT NULL, `staff` int(11) NOT NULL, `last_access` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `gradetbl` -- INSERT INTO `gradetbl` (`gradeID`, `regID`, `studID`, `subjID`, `rating`, `rexam`, `remarks`, `faculty`, `staff`, `last_access`) VALUES (1, 1, 0, 4, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (2, 1, 0, 11, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (3, 1, 0, 5, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (4, 1, 0, 12, '1.00', '1.00', NULL, 0, 0, '2020-07-04 11:43:23'), (5, 2, 0, 5, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (6, 2, 0, 7, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (7, 3, 0, 12, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (8, 3, 0, 7, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (9, 3, 0, 15, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (10, 4, 0, 9, '0.00', '0.00', 1, 0, 0, '2020-07-04 11:43:23'), (11, 4, 0, 16, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (13, 4, 0, 8, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (17, 6, 0, 4, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (18, 6, 0, 9, '0.00', '0.00', NULL, 0, 0, '2020-07-04 11:43:23'), (19, 4, 0, 4, '5.00', '3.00', 1, 0, 0, '2020-07-04 11:43:23'), (20, 4, 0, 5, '0.00', '0.00', 1, 0, 0, '2020-07-04 11:43:23'), (22, 7, 0, 24, '1.75', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (23, 7, 0, 31, '2.00', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (24, 7, 0, 10, '2.50', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (25, 7, 0, 25, '2.00', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (26, 7, 0, 26, '2.25', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (27, 7, 0, 27, '2.00', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (28, 7, 0, 28, '2.25', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (29, 7, 0, 29, '1.50', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (30, 7, 0, 23, '1.50', '0.00', 1, 0, 0, '2020-07-05 09:19:06'), (31, 8, 17, 24, '1.75', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (32, 8, 17, 31, '1.75', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (33, 8, 17, 10, '2.50', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (34, 8, 17, 25, '1.75', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (35, 8, 17, 26, '2.00', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (36, 8, 17, 27, '2.75', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (37, 8, 17, 28, '2.25', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (38, 8, 17, 29, '2.00', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (39, 8, 17, 30, '1.50', '0.00', 1, 0, 0, '2020-07-07 11:15:52'), (40, 9, 17, 18, '1.75', '0.00', 1, 0, 0, '2020-07-08 13:38:10'), (41, 9, 17, 19, '2.00', '0.00', 1, 0, 0, '2020-07-08 13:38:10'), (42, 9, 17, 20, '2.50', '0.00', 1, 0, 0, '2020-07-08 13:38:10'), (43, 9, 17, 7, '2.00', '0.00', 1, 0, 0, '2020-07-08 13:38:10'), (44, 9, 17, 8, '2.25', '0.00', 1, 0, 0, '2020-07-08 13:38:10'), (45, 9, 17, 22, '2.00', '0.00', 1, 0, 0, '2020-07-08 13:38:10'), (46, 9, 17, 23, '1.50', '0.00', 1, 0, 0, '2020-07-08 13:38:10'), (47, 9, 17, 11, '1.50', '0.00', 1, 0, 0, '2020-07-08 13:38:10'); -- -------------------------------------------------------- -- -- Table structure for table `majortbl` -- CREATE TABLE `majortbl` ( `majorID` int(11) NOT NULL, `majorName` varchar(50) NOT NULL, `courseID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `majortbl` -- INSERT INTO `majortbl` (`majorID`, `majorName`, `courseID`) VALUES (1, 'Web System Technology', 1), (2, 'Marketing Management', 5), (3, 'Entrepreneurship', 5), (5, 'Networking', 1), (7, 'Database', 1), (8, 'Networking', 7), (9, 'Filipino', 2); -- -------------------------------------------------------- -- -- Table structure for table `mngt_memberslist` -- CREATE TABLE `mngt_memberslist` ( `mem_id` int(11) NOT NULL, `pid` int(11) NOT NULL, `houseno` int(11) NOT NULL, `memberdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `mngt_memberslist` -- INSERT INTO `mngt_memberslist` (`mem_id`, `pid`, `houseno`, `memberdate`) VALUES (6, 22, 12902, '2017-09-22 13:32:27'), (7, 23, 12905, '2017-09-23 14:16:38'), (8, 24, 14219, '2017-09-23 14:20:29'), (9, 25, 12421, '2017-09-26 08:35:08'), (10, 26, 12421, '2017-09-26 08:35:18'), (11, 27, 12421, '2017-09-26 08:40:04'), (12, 28, 11117, '2017-09-26 08:46:58'), (13, 29, 12811, '2017-09-26 08:52:26'), (14, 30, 14816, '2017-09-26 08:58:10'), (15, 31, 13122, '2017-09-26 09:03:30'), (16, 32, 11321, '2017-09-26 09:08:48'), (17, 33, 11211, '2017-09-26 09:12:14'), (18, 34, 14002, '2017-09-26 09:18:27'), (19, 35, 13904, '2017-09-26 09:25:37'), (20, 36, 8601, '2017-09-26 09:32:56'), (21, 37, 8406, '2017-09-26 09:41:21'); -- -------------------------------------------------------- -- -- Table structure for table `person` -- CREATE TABLE `person` ( `person_id` int(11) NOT NULL, `firstname` varchar(50) NOT NULL, `nickname` varchar(50) NOT NULL, `midname` varchar(50) NOT NULL, `lastname` varchar(50) NOT NULL, `cpnum` varchar(11) NOT NULL, `bday` varchar(50) NOT NULL, `address` varchar(255) NOT NULL, `gender` char(6) NOT NULL, `email` varchar(100) NOT NULL, `profilepix` varchar(200) NOT NULL, `privacy` int(1) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `person` -- INSERT INTO `person` (`person_id`, `firstname`, `nickname`, `midname`, `lastname`, `cpnum`, `bday`, `address`, `gender`, `email`, `profilepix`, `privacy`) VALUES (1, 'Jodell', '', '', 'Bulaclac', '09059654520', 'August 15 1986', '<NAME>', 'Male', '<EMAIL>', '', 0), (2, 'Jabi', '', '', 'Bulaclac', '09284567761', 'Jan 4, 2014', 'Brgy. Bago', 'Female', '<EMAIL>', '', 0), (3, 'sfasfsadf', '', '', 'sadfsdf', 'sdfsdf', '2017-08-09', '09284567761', '', '<EMAIL>', '', 0), (4, 'ssss', '', '', 'sss', 'ss', '2017-08-09', '09284567761', '', '<EMAIL>', '', 0), (5, 'JC', '', '', 'Rico', 'Brgy. Bago', '2017-05-10', '09284567761', 'Male', '<EMAIL>', '', 0), (6, 'lance', '', '', 'Rico', 'Brgy. Bago', '2017-02-15', '09059654520', 'Male', '<EMAIL>', '', 0), (7, 'lance ', ' lancer ', '', 'Rico', '09284567761', '2016-09-06', 'Brgy. Bago ', 'Male', '<EMAIL>', 'img/profilepix/IMG20170205202539.jpg', 0), (8, 'Jociel ', 'ganda ', '', 'Bulaclac', '09123456789', '2017-09-05', 'Brgy. B<NAME>', 'Female', '<EMAIL>', 'img/profilepix/IMG20170205202353.jpg', 0), (9, 'janjan', '', '', 'Bulaclac', '<NAME>', '2017-05-11', '09284567761', 'Male', '<EMAIL>', '', 0), (10, 'asfdsfd', '', '', 'asfasdf', 'asfdsadf', '2017-08-09', '09284567761', 'Female', '<EMAIL>', '', 0), (12, 'fgdsagsdfg', '', '', 'dasgadgsd', 'sdfgsdg', '2017-08-09', '09284567761', 'Male', '<EMAIL>', '', 0), (13, 'irenea', '', '', 'development', '00000', '2013-06-06', '09059654520', 'Male', '<EMAIL>', '', 0), (14, 'mark', '', '', 'ladignon', '09097122110', '1990-07-29', 'any', 'Male', '<EMAIL>', '', 0), (22, 'Simeon', 'Simeon', 'Reyes', 'Acosta', '0912354468', '2010-06-22', 'Bago', 'Male', '<EMAIL>', '', 0), (23, 'Jenuel', 'Jenuel', 'Brasi', 'Barlis', '09123456789', '2017-09-10', 'Bago', 'Male', '<EMAIL>', '', 0), (24, 'Cyreen', 'Cyreen', 'Czar', 'Mendoza', '0945455', '2015-06-23', 'Penaranda', 'Male', '<EMAIL>', '', 0), (27, 'Jillaine', 'Jillaine', 'Lanuza', 'Pajarillaga', '09978823297', '1997-09-18', 'Brgy. Padolina General Tinio N. E', 'Female', '<EMAIL>', 'img/profilepix/ganda.jpg', 0), (28, 'Paulo', 'Paulo', 'Catalino', 'Manabat', '09124678542', '1999-09-12', 'Brgy. San Pedro General Tinio Nueva Ecija', 'Male', '<EMAIL>', 'img/profilepix/timaa.jpg', 0), (29, '<NAME>', '<NAME>', 'Yangao', 'Jaculbe', '09876789133', '1991-09-09', 'Nazareth Gen. Tinio Nueva Ecija', 'Female', '<EMAIL>', '', 0), (30, '<NAME> ', '<NAME> ', 'Reyes', 'Ladignon', '09501556244', '1990-07-24', 'Brgy. Padolina General Tinio N. E', 'Female', '<EMAIL>', '', 0), (31, '<NAME>', '<NAME>', 'Pajarillaga', 'Dayupay', '09122244556', '1990-12-03', 'Brgy. Rio Chico N.E', 'Female', '<EMAIL>', '', 0), (32, 'Jessie ', 'wAFU', 'Francisco', 'Pajarillaga', '09107607656', '1970-12-07', 'Brgy. Padolina General Tinio N. E', 'Male', '<EMAIL>', '', 0), (33, 'Jennyvieve', 'Jennyvieve', 'Maducdoc', 'Manabat', '09105634511', '1991-01-08', 'Brgy. Conception N.E', 'Female', '<EMAIL>', '', 0), (34, 'Patrick', 'Patrick', 'Rodriquez', 'Lanuza', '09508876540', '1992-12-13', 'Brgy. Rio Chico Nueva Ecija', 'Male', '<EMAIL>', '', 0), (35, 'Fatima', 'Fatima', 'Francisco', 'Madrid', '099913564', '1997-08-24', 'Santo Thomas Penaranda N.E', 'Female', '<EMAIL>', '', 0), (36, 'Reign', 'Reign', 'Bautista', 'Cruz', '09197790321', '1977-02-05', 'Brgy. 2 Penaranda N.e', 'Female', '<EMAIL>', 'img/profilepix/tima.jpg', 0), (37, 'Roberto ', 'berting', 'Manalo', 'Santiago', '09654671323', '1983-11-23', 'Callos Penaranda N.E', 'Male', '<EMAIL>', '', 0), (38, 'arjay ', ' ', '', 'abdon', '0987654321', '1998-02-03', 'Brgy. Padolina General Tinio N. E', 'Male', '<EMAIL>', 'img/profilepix/nano.jpg', 0); -- -------------------------------------------------------- -- -- Table structure for table `prereqtbl` -- CREATE TABLE `prereqtbl` ( `prereqID` int(11) NOT NULL, `prereqSub` int(11) NOT NULL, `subjID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `prereqtbl` -- INSERT INTO `prereqtbl` (`prereqID`, `prereqSub`, `subjID`) VALUES (1, 4, 12), (2, 5, 12), (5, 6, 14), (10, 12, 17), (11, 14, 17), (12, 21, 26); -- -------------------------------------------------------- -- -- Table structure for table `registrationtbl` -- CREATE TABLE `registrationtbl` ( `regID` int(11) NOT NULL, `studID` int(11) NOT NULL, `regMajor` int(11) NOT NULL, `regYrlevel` int(11) NOT NULL, `regSem` int(11) NOT NULL, `regAcadYr` varchar(50) NOT NULL, `regSection` varchar(50) NOT NULL, `regResidency` int(11) NOT NULL DEFAULT '0', `currID` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `registrationtbl` -- INSERT INTO `registrationtbl` (`regID`, `studID`, `regMajor`, `regYrlevel`, `regSem`, `regAcadYr`, `regSection`, `regResidency`, `currID`) VALUES (1, 15, 1, 2, 2, '2019-2020', '2-gilas', 0, 0), (2, 1, 1, 1, 1, '2017-2018', '1-B', 0, 0), (3, 1, 1, 1, 2, '2017-2018', '1-A', 0, 0), (4, 4, 1, 5, 4, '2020-2022', '6-A', 1, 0), (6, 4, 7, 5, 3, '2021-2021', '1-B', 0, 0), (7, 8, 2, 1, 2, '2019-2020', 'Mark 1', 0, 0), (8, 17, 0, 1, 2, '2018-2019', '1-A', 0, 2), (9, 17, 0, 1, 1, '2018-2019', '1-A', 0, 2); -- -------------------------------------------------------- -- -- Table structure for table `stafftbl` -- CREATE TABLE `stafftbl` ( `staffID` int(11) NOT NULL, `firstName` varchar(100) NOT NULL, `nickName` varchar(50) DEFAULT NULL, `midName` varchar(100) DEFAULT NULL, `lastName` varchar(100) NOT NULL, `cpnum` varchar(50) DEFAULT NULL, `address` varchar(255) NOT NULL, `bday` date NOT NULL, `gender` varchar(6) NOT NULL, `email` varchar(100) DEFAULT NULL, `profilepix` varchar(200) DEFAULT NULL, `refnote` int(2) NOT NULL DEFAULT '1' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `stafftbl` -- INSERT INTO `stafftbl` (`staffID`, `firstName`, `nickName`, `midName`, `lastName`, `cpnum`, `address`, `bday`, `gender`, `email`, `profilepix`, `refnote`) VALUES (1, 'lance', 'lans', 'rico', 'bulaclac', '09553846491', 'brgy.bago, gen. Tinio,N.E.', '0000-00-00', 'male', '<EMAIL>', NULL, 1), (2, 'baba', 'sdfsdf', 'sdfsaf', 'sdfdsfs', '09153554456', 'baba', '2020-06-24', 'Male', '<EMAIL>', NULL, 1); -- -------------------------------------------------------- -- -- Table structure for table `studtbl` -- CREATE TABLE `studtbl` ( `studID` int(11) NOT NULL, `studNum` varchar(50) NOT NULL, `fName` varchar(50) NOT NULL, `mName` varchar(50) NOT NULL, `lName` varchar(50) NOT NULL, `gender` int(2) NOT NULL, `DOB` date NOT NULL, `email` varchar(50) NOT NULL, `cpnum` varchar(20) NOT NULL, `elem` varchar(200) NOT NULL, `highSchool` varchar(200) NOT NULL, `prk` varchar(50) NOT NULL, `brgy` varchar(50) NOT NULL, `city` varchar(50) NOT NULL, `prov` varchar(50) NOT NULL, `studregdate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `curMajor` int(2) NOT NULL, `curYrlevel` int(2) NOT NULL, `curSem` int(2) NOT NULL, `curSection` varchar(50) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `studtbl` -- INSERT INTO `studtbl` (`studID`, `studNum`, `fName`, `mName`, `lName`, `gender`, `DOB`, `email`, `cpnum`, `elem`, `highSchool`, `prk`, `brgy`, `city`, `prov`, `studregdate`, `curMajor`, `curYrlevel`, `curSem`, `curSection`) VALUES (1, 'GT17-110', 'Emerson', 'Marquez', 'Oller', 0, '1900-05-05', '<EMAIL>', '09991234567', '', '', 'Ilang ilang', 'Sampaguita', '<NAME>', '<NAME>', '2020-06-26 08:29:37', 1, 1, 2, '1-A'), (2, 'GT17-5214', 'fasfa', 'asdfasdf', 'nasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:33:21', 0, 0, 0, ''), (3, 'GT17-5214', 'fasfa', 'asdfasdf', 'gasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:34:25', 0, 0, 0, ''), (4, 'GT17-5214', 'fasfa', 'asdfasdf', 'asfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:34:33', 7, 5, 3, '1-B'), (5, 'GT17-110', 'asfasdf', 'asfasf', 'xasf', 1, '2020-06-01', '<EMAIL>', '1123154545', '', '', 'sdfasdf', 'dsfdsf', 'asfdasdf', 'asfasf', '2020-06-26 08:39:13', 0, 0, 0, ''), (6, 'GT17-5214', 'fasfa', 'asdfasdf', 'nasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:33:21', 0, 0, 0, ''), (7, 'GT17-5214', 'fasfa', 'asdfasdf', 'gasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:34:25', 0, 0, 0, ''), (8, 'GT17-5214', 'Angeline', 'Lejano', 'Enriquez', 0, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:34:33', 2, 1, 2, 'Mark 1'), (9, 'GT17-110', 'asfasdf', 'asfasf', 'xa', 1, '2020-06-01', '<EMAIL>', '1123154545', '', '', 'sdfasdf', 'dsfdsf', 'asfdasdf', 'asfasf', '2020-06-26 08:39:13', 0, 0, 0, ''), (10, 'GT17-5214', 'fasfa', 'asdfasdf', 'nasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:33:21', 0, 0, 0, ''), (11, 'GT17-5214', 'fasfa', 'asdfasdf', 'gasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:34:25', 0, 0, 0, ''), (12, 'GT17-110', 'asfasdf', 'asfasf', 'xab', 1, '2020-06-01', '<EMAIL>', '1123154545', '', '', 'sdfasdf', 'dsfdsf', 'asfdasdf', 'asfasf', '2020-06-26 08:39:13', 0, 0, 0, ''), (13, 'GT17-5214', 'fasfa', 'asdfasdf', 'nasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:33:21', 0, 0, 0, ''), (14, 'GT17-5214', 'fasfa', 'asdfasdf', 'gasfdadsf', 1, '2008-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'asfdasdf', 'asfdasdf', 'asfasf', '2020-06-26 08:34:25', 0, 0, 0, ''), (15, 'GT17-105', 'Reymart', 'Bautista', 'Limbo', 1, '2000-02-15', '<EMAIL>', '09123459874', '', '', 'sdfasdf', 'Concepcion', 'Gen. Tinio', 'Nueva Ecija', '2020-06-26 08:34:33', 1, 2, 2, '2-gilas'), (16, 'GT17-110', 'asfasdf', 'asfasf', 'xasfasfd', 1, '2020-06-01', '<EMAIL>', '1123154545', '', '', 'sdfasdf', 'dsfdsf', 'asfdasdf', 'asfasf', '2020-06-26 08:39:13', 0, 0, 0, ''), (17, 'GT17-268', '<NAME>', 'Ramos', 'Diaz', 0, '2000-05-02', '<EMAIL>', '09191234569', 'Gen. Tinio Central Elem. School', 'Gen. Tinio National High School', '', 'Concepcion', 'Gen. Tinio', 'Nueva Ecija', '2020-07-07 11:14:35', 2, 1, 1, '1-A'); -- -------------------------------------------------------- -- -- Table structure for table `subjtbl` -- CREATE TABLE `subjtbl` ( `subjID` int(11) NOT NULL, `subjCode` varchar(10) NOT NULL, `subjTitle` varchar(100) NOT NULL, `subjUnit` int(2) NOT NULL, `subjLec` int(2) DEFAULT NULL, `subjLab` int(2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `subjtbl` -- INSERT INTO `subjtbl` (`subjID`, `subjCode`, `subjTitle`, `subjUnit`, `subjLec`, `subjLab`) VALUES (1, 'ITP 06', 'Web Development', 3, 3, 1), (2, 'NSTP 11', 'National Service Training Program 1', 3, -2, -3), (3, 'PE 4', 'Advance Team Sports', 2, 0, 3), (4, 'CC-100', 'Introduction to Computing', 3, 3, 0), (5, 'CC-101', 'Computer Programming 1, Fundamentals', 3, 2, 3), (6, 'IT-NET01', 'Networking 1, Fundamentals', 3, 2, 3), (7, 'GE 4', 'Mathematics in the Modern World', 3, 3, 0), (8, 'GE 5', 'Purposive Communication', 3, 3, 0), (9, 'FIL 1', 'Kontekswalisadong Komunikasyon sa Filipino (KOMFIL)', 3, 3, 0), (10, 'GE 7', 'Science, Technology and Society', 3, 3, 0), (11, 'PE 1', 'Advanced Gymnastics', 2, 2, 0), (12, 'CC-102', 'Computer Programming 2, Intermediate', 3, 2, 3), (13, 'IT-NET02', 'Networking 2, Advanced', 3, 2, 3), (14, 'IT-WS01', 'Web Systems and Technologies 1', 3, 2, 3), (15, 'NSTP 1', 'National Service Training Program', -3, 3, 0), (16, 'FIL 2', '<NAME> Iba\'t Ibang Disiplina (FILDIS)', 3, 3, 0), (17, 'CC-103', 'Data Structure and Algorithm', 3, 2, 3), (18, 'GE 1', 'Understanding the Self', 3, 3, 0), (19, 'GE 2', 'Readings in the Philippine History', 3, 3, 0), (20, 'GE 3', 'The Contemporary World', 3, 3, 0), (21, 'GE Fil 1', 'Kontekstwalisadong Komunikasyon sa Filipino (KOMFIL)', 3, 3, 0), (22, 'BA CORE 1', 'Basic Microeconomics', 3, 3, 0), (23, 'NSTP 1', 'ROTC/CWTS/LTS', -3, -3, 0), (24, 'BA CORE 2', 'Good Governance and Social Responsibility', 3, 3, 0), (25, 'GE 8', 'Ethics', 3, 3, 0), (26, 'GE Fil 2', 'Filipino sa Iba\'t Ibang Disiplina (FILDIS)', 3, 3, 0), (27, 'Elective 1', 'Entrepreneurial Management', 3, 3, 0), (28, 'Elective 2', 'Personal Finance', 3, 3, 0), (29, 'PE 2', 'Rythmic Activities Folk Dance/Social Dances', 2, 2, 0), (30, 'NSTP 2', 'ROTC/CWTS/LTS', -3, -3, 0), (31, 'GE 6', 'Art Appreciation', 3, 3, 0); -- -------------------------------------------------------- -- -- Table structure for table `userstbl` -- CREATE TABLE `userstbl` ( `userID` int(11) NOT NULL, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `staffID` int(11) DEFAULT NULL, `permission` int(2) NOT NULL, `date_registerd` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `userstbl` -- INSERT INTO `userstbl` (`userID`, `username`, `password`, `staffID`, `permission`, `date_registerd`) VALUES (1, 'lancer', '<PASSWORD>', 1, 1, '2020-06-25 05:04:38'), (2, 'babadubadu', '<PASSWORD>', 2, 1, '2020-06-28 10:50:00'); -- -- Indexes for dumped tables -- -- -- Indexes for table `coursetbl` -- ALTER TABLE `coursetbl` ADD PRIMARY KEY (`courseID`); -- -- Indexes for table `curriculum` -- ALTER TABLE `curriculum` ADD PRIMARY KEY (`currID`); -- -- Indexes for table `curri_subjtbl` -- ALTER TABLE `curri_subjtbl` ADD PRIMARY KEY (`cursubjID`); -- -- Indexes for table `gradetbl` -- ALTER TABLE `gradetbl` ADD PRIMARY KEY (`gradeID`), ADD KEY `regID` (`regID`); -- -- Indexes for table `majortbl` -- ALTER TABLE `majortbl` ADD PRIMARY KEY (`majorID`), ADD KEY `courseID` (`courseID`); -- -- Indexes for table `mngt_memberslist` -- ALTER TABLE `mngt_memberslist` ADD PRIMARY KEY (`mem_id`), ADD UNIQUE KEY `pid` (`pid`); -- -- Indexes for table `person` -- ALTER TABLE `person` ADD PRIMARY KEY (`person_id`); -- -- Indexes for table `prereqtbl` -- ALTER TABLE `prereqtbl` ADD PRIMARY KEY (`prereqID`); -- -- Indexes for table `registrationtbl` -- ALTER TABLE `registrationtbl` ADD PRIMARY KEY (`regID`); -- -- Indexes for table `stafftbl` -- ALTER TABLE `stafftbl` ADD PRIMARY KEY (`staffID`); -- -- Indexes for table `studtbl` -- ALTER TABLE `studtbl` ADD PRIMARY KEY (`studID`); -- -- Indexes for table `subjtbl` -- ALTER TABLE `subjtbl` ADD PRIMARY KEY (`subjID`); -- -- Indexes for table `userstbl` -- ALTER TABLE `userstbl` ADD PRIMARY KEY (`userID`), ADD KEY `staffID` (`staffID`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `coursetbl` -- ALTER TABLE `coursetbl` MODIFY `courseID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `curriculum` -- ALTER TABLE `curriculum` MODIFY `currID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `curri_subjtbl` -- ALTER TABLE `curri_subjtbl` MODIFY `cursubjID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=30; -- -- AUTO_INCREMENT for table `gradetbl` -- ALTER TABLE `gradetbl` MODIFY `gradeID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48; -- -- AUTO_INCREMENT for table `majortbl` -- ALTER TABLE `majortbl` MODIFY `majorID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `mngt_memberslist` -- ALTER TABLE `mngt_memberslist` MODIFY `mem_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22; -- -- AUTO_INCREMENT for table `person` -- ALTER TABLE `person` MODIFY `person_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=39; -- -- AUTO_INCREMENT for table `prereqtbl` -- ALTER TABLE `prereqtbl` MODIFY `prereqID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- AUTO_INCREMENT for table `registrationtbl` -- ALTER TABLE `registrationtbl` MODIFY `regID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `stafftbl` -- ALTER TABLE `stafftbl` MODIFY `staffID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `studtbl` -- ALTER TABLE `studtbl` MODIFY `studID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT for table `subjtbl` -- ALTER TABLE `subjtbl` MODIFY `subjID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=32; -- -- AUTO_INCREMENT for table `userstbl` -- ALTER TABLE `userstbl` MODIFY `userID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- Constraints for dumped tables -- -- -- Constraints for table `gradetbl` -- ALTER TABLE `gradetbl` ADD CONSTRAINT `gradetbl_ibfk_1` FOREIGN KEY (`regID`) REFERENCES `registrationtbl` (`regID`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `majortbl` -- ALTER TABLE `majortbl` ADD CONSTRAINT `majortbl_ibfk_1` FOREIGN KEY (`courseID`) REFERENCES `coursetbl` (`courseID`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `userstbl` -- ALTER TABLE `userstbl` ADD CONSTRAINT `userstbl_ibfk_1` FOREIGN KEY (`staffID`) REFERENCES `stafftbl` (`staffID`) ON DELETE CASCADE ON UPDATE CASCADE; 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/res.php <?php require_once("src/db.php"); class res{ private $class_var; function __construct(){ global $con; $this->class_var=$con; } //select join function selectjoin($table,$table2,$ref,$ref2){ global $con; $list = array(); $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2}"; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } //select join sample /* $samm = $func->selectjoin('users','person','person_id','person_id'); //print_r($samm); //echo count($samm); for($x=0;$x<count($samm);$x++){ $m = $samm[$x]['permission']; if ($m ==3){ echo $samm[$x]['permission'] .'<br>'; echo $samm[$x]['username'] .'<br>'; } } */ //select joinlike function selectjoin_like($table,$table2,$ref,$ref2,$tblorder,$byfield,$likestr,$where = array()){ global $con; $list = array(); $likeval = '%' . $likestr . '%'; if(count($where) === 2) { $tbl1 = $where[0]; $field1 = $where[1]; $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} WHERE {$tbl1}.{$field1} LIKE '{$likeval}' ORDER BY {$tblorder}.{$byfield}"; } else if (count($where) === 4){ $tbl1 = $where[0]; $field1 = $where[1]; $tbl2 = $where[3]; $field2 = $where[4]; $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} WHERE {$tbl1}.{$field1} LIKE '{$likeval}' OR {$tbl2}.{$field2} LIKE '{$likeval}' ORDER BY {$tblorder}.{$byfield}"; } $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } //select join sample /* $samm = $func->selectjoin('users','person','person_id','person_id'); //print_r($samm); //echo count($samm); for($x=0;$x<count($samm);$x++){ $m = $samm[$x]['permission']; if ($m ==3){ echo $samm[$x]['permission'] .'<br>'; echo $samm[$x]['username'] .'<br>'; } } */ //select joinlike function selectjoin_likelimit($table,$table2,$ref,$ref2,$tblorder,$byfield,$likestr,$sortorder,$start,$perPage,$where = array()){ global $con; $list = array(); $likeval = '%' . $likestr . '%'; if(count($where) === 2) { $tbl1 = $where[0]; $field1 = $where[1]; $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} WHERE {$tbl1}.{$field1} LIKE '{$likeval}' ORDER BY {$tblorder}.{$byfield} {$sortorder} LIMIT {$start}, {$perPage}"; } else if (count($where) === 4){ $tbl1 = $where[0]; $field1 = $where[1]; $tbl2 = $where[2]; $field2 = $where[3]; $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} WHERE {$tbl1}.{$field1} LIKE '{$likeval}' OR {$tbl2}.{$field2} LIKE '{$likeval}' ORDER BY {$tblorder}.{$byfield} {$sortorder} LIMIT {$start}, {$perPage}"; } $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } //select join sample /* $samm = $func->selectjoin('users','person','person_id','person_id'); //print_r($samm); //echo count($samm); for($x=0;$x<count($samm);$x++){ $m = $samm[$x]['permission']; if ($m ==3){ echo $samm[$x]['permission'] .'<br>'; echo $samm[$x]['username'] .'<br>'; } } */ function selectjoinorderby($table,$table2,$ref,$ref2,$tableref,$col,$sortorder,$start,$perPage){ global $con; $list = array(); $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} ORDER BY {$tableref}.{$col} {$sortorder} LIMIT {$start}, {$perPage}"; //echo $sql; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } /* sample procedure selectall $cemail = $func->selectjoinorderby('person',mngt_memberslist,'person','pid','person','lastname','start','perpage'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //select join order no limit function selectjoinorderby_nolimit($table,$table2,$ref,$ref2,$tableref,$col,$sortorder){ global $con; $list = array(); $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} ORDER BY {$tableref}.{$col} {$sortorder}"; //echo $sql; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } /* sample procedure selectall $cemail = $func->selectjoinorderby('person',mngt_memberslist,'person','pid','person','lastname','start','perpage'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //select join with orderby function selectjoinorderby2($table,$table2,$ref,$ref2){ global $con; $list = array(); $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2}"; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } //select join sample /* $samm = $func->selectjoin('users','person','person_id','person_id'); //print_r($samm); //echo count($samm); for($x=0;$x<count($samm);$x++){ $m = $samm[$x]['permission']; if ($m ==3){ echo $samm[$x]['permission'] .'<br>'; echo $samm[$x]['username'] .'<br>'; } } */ function selectjoin_where($table,$table2,$ref,$ref2,$table3,$where = array()){ global $con; $list = array(); if(count($where) === 3) { $operators = array('=', '>', '<', '>=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} WHERE {$table3}.{$field} {$operator} '{$value}'"; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } } } function selectjoin3_where($table,$table2,$table3,$ref,$ref2,$ref3,$ref4,$tableref,$where = array()){ global $con; $list = array(); if(count($where) === 3) { $operators = array('=', '>', '<', '>=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { $sql = "SELECT * FROM {$table} JOIN {$table2} ON {$table}.{$ref}={$table2}.{$ref2} JOIN {$table3} ON {$table2}.{$ref3}={$table3}.{$ref4} WHERE {$tableref}.{$field} {$operator} '{$value}'"; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } } } //selecting * with 2 logical operator function select_logics2($table,$where1 = array(),$logic,$where2 = array(),$logic2,$where3 = array()){ global $con; $list = array(); if(count($where1) === 3 AND count($where2) === 3){ $operators = array('=', '>', '<', '>=', '<='); $field1 = $where1[0]; $operator1 = $where1[1]; $value1 = $where1[2]; $field2 = $where2[0]; $operator2 = $where2[1]; $value2 = $where2[2]; $field3 = $where3[0]; $operator3 = $where3[1]; $value3 = $where3[2]; if(in_array($operator1, $operators) AND in_array($operator2, $operators)) { $sql = "SELECT * FROM {$table} WHERE {$field1} {$operator1} '{$value1}' {$logic} {$field2} {$operator2} '{$value2}' {$logic2} {$field3} {$operator3} '{$value3}' "; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); //echo '<script>alert("'.rowcount.'");</script>'; if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); //print_r($row); $list[] = $row; } return $list; } return null; } } } //selecting * with logical operator function select_logic($table,$where1 = array(),$logic,$where2 = array()){ global $con; $list = array(); if(count($where1) === 3 AND count($where2) === 3){ $operators = array('=', '>', '<', '>=', '<='); $field1 = $where1[0]; $operator1 = $where1[1]; $value1 = $where1[2]; $field2 = $where2[0]; $operator2 = $where2[1]; $value2 = $where2[2]; if(in_array($operator1, $operators) AND in_array($operator2, $operators)) { $sql = "SELECT * FROM {$table} WHERE {$field1} {$operator1} '{$value1}' {$logic} {$field2} {$operator2} '{$value2}' "; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); //echo '<script>alert("'.rowcount.'");</script>'; if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); //print_r($row); $list[] = $row; } return $list; } return null; } } } /*sample procedure select_logic row $cemail = $func->select_logic('users',array('username','=','alex'),'AND',array('name','=','alex')); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['name'] .'<br>'; } */ //selecting * with where parameters function select_one($table,$where = array()){ global $con; $list = array(); if(count($where) === 3) { $operators = array('=', '>', '<', '>=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { $sql = "SELECT * FROM {$table} WHERE {$field} {$operator} '{$value}'"; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } } } /*sample procedure select_one row $cemail = $func->select_one('users',array('username','=','alex')); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['name'] .'<br>'; } */ //selecting * with where parameters function select_one_orderby($table,$where = array(),$orderfield,$sortorder){ global $con; $list = array(); if(count($where) === 3) { $operators = array('=', '>', '<', '>=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { $sql = "SELECT * FROM {$table} WHERE {$field} {$operator} '{$value}' ORDER BY {$orderfield} {$sortorder} "; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } } } /*sample procedure select_one row $cemail = $func->select_one('users',array('username','=','alex')); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['name'] .'<br>'; } */ //selecting * with where Like parameters function select_like($table,$where = array()){ global $con; $list = array(); if(count($where) === 3) { $field = $where[0]; $field2 = $where[1]; $value = $where[2]; $valued = '%' . $value . '%'; $sql = "SELECT * FROM {$table} WHERE {$field} LIKE '%{$valued}%' OR {$field2} LIKE '%{$valued}%'"; }else if(count($where) === 4) { $field = $where[0]; $field2 = $where[1]; $field3 = $where[2]; $value = $where[3]; $valued = '%' . $value . '%'; $sql = "SELECT * FROM {$table} WHERE {$field} LIKE '%{$valued}%' OR {$field2} LIKE '%{$valued}%' OR {$field3} LIKE '%{$valued}%'"; } else if(count($where) === 5) { $field = $where[0]; $field2 = $where[1]; $field3 = $where[2]; $value = $where[3]; $sortorder = $where[4]; $valued = '%' . $value . '%'; $sql = "SELECT * FROM {$table} WHERE {$field} LIKE '%{$valued}%' OR {$field2} LIKE '%{$valued}%' OR {$field3} LIKE '%{$value}%' ORDER BY {$field} {$sortorder} "; } $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } /*sample procedure select_like row $cemail = $func->select_one('users',array('fname','lname','mname','alex')); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['name'] .'<br>'; } */ //selecting * with where Like parameters function select_likelimit($table,$orderfield,$sortorder,$start, $perPage, $where = array()){ global $con; $list = array(); if(count($where) === 3) { $field = $where[0]; $field2 = $where[1]; $value = $where[2]; $valued = '%' . $value . '%'; $sql = "SELECT * FROM {$table} WHERE {$field} LIKE '%{$valued}%' OR {$field2} LIKE '%{$valued}%' ORDER BY {$orderfield} {$sortorder} LIMIT {$start}, {$perPage}"; } else if(count($where) === 4) { $field = $where[0]; $field2 = $where[1]; $field3 = $where[2]; $value = $where[3]; $valued = '%' . $value . '%'; $sql = "SELECT * FROM {$table} WHERE {$field} LIKE '%{$valued}%' OR {$field2} LIKE '%{$valued}%' OR {$field3} LIKE '%{$value}%' ORDER BY {$orderfield} {$sortorder} LIMIT {$start}, {$perPage}"; } $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } /*sample procedure select_like row $cemail = $func->select_one('users',array('fname','lname','mname','alex')); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['name'] .'<br>'; } */ //generic select * function function selectall($table){ global $con; $list = array(); $sql = "SELECT * FROM {$table}"; $qry = $con->query($sql); while($row = mysqli_fetch_assoc($qry)){ $list[] = $row; } return $list; } /* sample procedure selectall $cemail = $func->selectall('users'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //generic select * function function selectall_where($table,$where = array()){ global $con; $list = array(); if(count($where) === 3) { $field = $where[0]; $operator = $where[1]; $value = $where[2]; } $sql = "SELECT * FROM {$table} WHERE {$field} {$operator} {$value}"; $qry = $con->query($sql); while($row = mysqli_fetch_assoc($qry)){ $list[] = $row; } return $list; } /* sample procedure selectall $cemail = $func->selectall('users'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //select distinct function select_distinct($table,$col_arr = array()){ global $con; $list = array(); if(count($col_arr) === 1) { $field = $col_arr[0]; $sql = "SELECT DISTINCT {$field} FROM {$table} "; } $qry = $con->query($sql); while($row = mysqli_fetch_assoc($qry)){ $list[] = $row; } return $list; } /* sample procedure selectall $cemail = $func->selectall('users'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //select distinct where function select_distinctwhere($table,$byfield,$sortorder,$col_arr = array(),$saan = array()){ global $con; $list = array(); if(count($col_arr) === 1) { $field = $col_arr[0]; $sql = "SELECT DISTINCT {$field} FROM {$table} WHERE {$saan[0]} {$saan[1]} {$saan[2]} ORDER BY {$byfield} {$sortorder}"; } $qry = $con->query($sql); while($row = mysqli_fetch_assoc($qry)){ $list[] = $row; } return $list; } /* sample procedure selectall $cemail = $func->selectall('users'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //select distinct function select_distinctlimit($table,$start,$perPage,$col_arr = array()){ global $con; $list = array(); if(count($col_arr) === 1) { $field = $col_arr[0]; $sql = "SELECT DISTINCT {$field} FROM {$table} "; } $qry = $con->query($sql); while($row = mysqli_fetch_assoc($qry)){ $list[] = $row; } return $list; } /* sample procedure selectall $cemail = $func->selectall('users'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //generic select * function with sorting function selectallorderby($table,$col,$sortorder){ global $con; $list = array(); $sql = "SELECT * FROM {$table} ORDER BY {$col} {$sortorder}"; $qry = $con->query($sql); while($row = mysqli_fetch_assoc($qry)){ $list[] = $row; } return $list; } /* sample procedure selectall $cemail = $func->selectall('users'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ //generic select * function with sorting function selectallorderbylimit($table,$col,$sortorder,$start,$perPage){ global $con; $list = array(); $sql = "SELECT * FROM {$table} ORDER BY {$col} {$sortorder} LIMIT {$start}, {$perPage}"; $qry = $con->query($sql); while($row = mysqli_fetch_assoc($qry)){ $list[] = $row; } return $list; } /* sample procedure selectall $cemail = $func->selectall('users'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ function selectorderby($table,$col,$col2,$start,$perPage,$sortorder,$where = array()){ global $con; $list = array(); if(count($where) === 3) { $operators = array('=', '>', '<', '>=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { $sql = "SELECT * FROM {$table} WHERE {$field} {$operator} '{$value}' ORDER BY {$col} {$sortorder}, {$col2} {$sortorder} LIMIT {$start}, {$perPage}"; $qry = $con->query($sql); $rowcount = mysqli_num_rows($qry); if ($rowcount!=0){ for($x=1;$x<=$rowcount;$x++){ $row = mysqli_fetch_assoc($qry); $list[] = $row; } return $list; } return null; } } } /* sample procedure selectall $cemail = $func->selectall('users','col','start','perpage'); print_r($cemail); for($x=0;$x<count($cemail);$x++){ echo $cemail[$x]['password'] .'<br>'; } */ function delete($table,$where = array()){ global $con; $list = array(); if(count($where) === 3) { $operators = array('=', '>', '<', '>=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { $sql = "DELETE FROM {$table} WHERE {$field} {$operator} '{$value}'"; $qry = $con->query($sql); return true; } } return false; } /* delete procedure $cemail = $func->delete('users',array('username','=','Dale')); if ($cemail){ echo "record Deleted"; } else { echo "failed"; } */ //generic insert function // parameter table and fields function insert($table, $fields = array()) { global $con; $keys = array_keys($fields); $values = ''; $x = 1; foreach($fields as $field) { $values .= "'".$field."'"; if($x < count($fields)) { $values .= ', '; } $x++; } $sql = "INSERT INTO {$table} (`" . implode('`, `', $keys) . "`) VALUES ({$values})"; $qry = $con->query($sql); if($qry){ return true; } else { return false; } } /* sample procedure for page $userInsert = $func->insert('users',array( 'name' => 'Dale', 'username' => 'Dale', 'password' => '<PASSWORD>' )); */ function update($table,$param, $param_value, $fields) { global $con; $set = ''; $x = 1; foreach($fields as $name => $value) { $set .= "{$name} = '{$value}'"; if($x < count($fields)) { $set .= ', '; } $x++; } $sql = "UPDATE {$table} SET {$set} WHERE {$param} = {$param_value}"; //echo $sql; $qry = $con->query($sql); if($qry){ return true; } else { return false; } } /* sample update procedure $userUpdate = $func->update('users','userid',3, array( 'password' => '<PASSWORD>', 'name' => '<NAME>' )); if ($userUpdate){ echo "record updated"; } else { echo "failed"; } */ function uploadfiles($filetoupload,$dir){ $error=''; //make the allowed extensions $goodExtensions = array( '.jpg', '.png','.jpeg',); //set the current directory where you wanna upload the doc/docx or pdf files $uploaddir = $dir; //get the names of the file that will be uploaded $fname = $_FILES[$filetoupload]['name']; $min_filesize=10;//set up a minimum file size(a doc/docx can't be lower then 10 bytes) $stem=substr($fname,0,strpos($fname,'.')); //take the file extension $extension = substr($fname, strpos($fname,'.'), strlen($fname)-1); //verify if the file extension is jpeg or png or jpg if(!in_array($extension,$goodExtensions) ) $error.='Extension not allowed<br>'; echo "<span> </span>"; //verify if the file size of the file being uploaded is greater then 1 if(filesize($_FILES[$filetoupload]['tmp_name']) < $min_filesize ) $error.='File size too small<br>'."\n"; $uploadfile = $uploaddir . $stem.$extension; $filename=$stem.$extension; //upload the file to if (move_uploaded_file($_FILES[$filetoupload]['tmp_name'], $uploadfile)) { echo $fname .' has been uploaded... ' ; } return $uploadfile; } //end of upload // End of functions } $func = new res(); ?> <file_sep>/editpermission.php <?php include'menu.php'; if(empty($_SESSION['userid'])){ header('location: register.php'); } $status =null; $permitlevel = null; $useremail = null; if (isset($_POST['update'])){ $reglevel=$_POST['reglevel']; $regid=$_POST['regid']; $permissonUpdate = $func->update('users','user_id',$regid, array( 'permission' => $reglevel )); if($permissonUpdate){ $status= "Data Has Been Updated!"; } else { $status= "Update Failed!"; } } ?> <style> .well{ background-color: #C8F7C5; /*border-bottom : 2px groove black; height: 100px;*/ } div#corner{ background-color: white; border:10px; /*border-bottom : 5px groove black; height: 100px;*/ } h1{ color:black; } </style> <!-- /. NAV SIDE --> <div id="page-wrapper"; > <div id="page-inner"> <div class="col-lg-12"> <br> <div class="row"> <?php $sttt = null; if ((isset($_POST['searchuser']))) { $useremail = $_POST['useremail']; $searchUser = $func->select_one('users',array('username','=',$useremail)); if($searchUser){ $permitlevel = $searchUser[0]['permission']; } } ?> <form method="POST"> <div class="paper" id="corner"> <p><?php echo $status; ?></p> <div id="printarea"> <H3>Edit Account Level</H3> <div class="row"> <H3>Search</H3> <div class="col-sm-2 form-group"> <label class="col-sm-2 control-label">Username</label> </div> <div class="col-sm-6 form-group"> <input type="email" class="form-control" name="useremail" value="<?php echo $useremail ?>"> </div> <div class="col-sm-4 form-group"> <button type="submit" class="btn btn-info"name="searchuser">Search</button> </div> </div> </div> <hr> <H3>RESULT:</H3> <p class="alert-danger"> <strong>LEGEND:</strong> 1 - member, 2 - admin </p> <div class="row"> <div class="col-sm-2 form-group"> <label>Account Level</label> </div> <div class="col-sm-2 form-group"> <input type="text" class="form-control" name="reglevel" value="<?php echo $permitlevel ?>"> </div> <div class="col-sm-2 form-group"> <input type="hidden" class="form-control" name="regid" value="<?php echo $searchUser[0]['user_id'] ?>"> <button type="submit" class="btn btn-info"name="update">Update</button> </div> </div> </form> </div> </div> <!-- /. PAGE INNER --> </div> <script> document.getElementById('editpermit').className = "active"; $("link[rel*='icon']").attr("href", "img/logo.png"); function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script><file_sep>/verify.php <?php include'menu.php'; $regfname = $_COOKIE['regfname']; $reglname = $_COOKIE['reglname']; $regmname = $_COOKIE['regmname']; $regnname = $_COOKIE['regnname']; $regaddress = $_COOKIE['regaddress']; $regbday = $_COOKIE['regbday']; $regcpno = $_COOKIE['regcpno']; $reggender = $_COOKIE['reggender']; $regemail = $_COOKIE['regemail']; $reguser = $_COOKIE['reguser']; $regpassword = $_COOKIE['regpassword']; $warn1 = $_COOKIE['regfname']; $warn2 = $_COOKIE['reglname']; $personInsert = $func->insert('stafftbl',array( 'firstName' => $regfname, 'lastName' => $reglname, 'nickName' => $regnname, 'midName' => $regmname, 'cpnum' => $regcpno, 'address' => $regaddress, 'bday' => $regbday, 'gender' => $reggender, 'email' => $regemail )); if($personInsert){ $lastindex = mysqli_insert_id($con); $userInsert = $func->insert('userstbl',array( 'username' => $reguser, 'password' => $<PASSWORD>, 'staffID' => $lastindex, 'permission' => '1' )); if($personInsert){ setcookie("fullname",""); setcookie("regfname",""); setcookie("reglname",""); setcookie("regmname",""); setcookie("regnname",""); setcookie("regaddress",""); setcookie("regbday",""); setcookie("regcpno",""); setcookie("reggender", ""); setcookie("regemail", ""); setcookie("reguser", ""); setcookie("regpassword",""); setcookie("registerna",1,time() + 3600); } } else { setcookie("registerna",2,time() + 3600); } header('location:account.php'); ?> <file_sep>/studlist.php <?php include 'menu.php'; include 'vars/'.$usern.'studlistvar.php'; setcookie("regfn", $fullname , time() + 60); $sttt = null; if ((isset($_POST['delete']))) { $mid = $_POST['mid']; $delstud = $func->delete('studtbl',array('studID','=',$mid)); if ($delstud){ echo '<script> alert("Record Deleted");</script>'; } else { echo '<script> alert("Delete failed");</script>'; } } $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; $perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 10; //Positioning $start = ($page > 1) ? ($page * $perPage) - $perPage : 0; //Pages //check queries with search if ((isset($_POST['searchnamebut']))) { $fullname = $_POST['searchname']; $studs = $func->select_like('studtbl',array('lName','fName','mName',$fullname )); $totalcountrow = count($studs); //$pages = ceil($totalcountrow/$perPage); $view = $studs; $studtext = $fullname; $var_str = var_export($studtext, true); $var = "<?php\n\n\$studtext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'studlistvar.php', $var); } //check queries with search else if ((isset($_POST['yrsearchnamebut']))) { $yr_select = $_POST['select_yr']; //$studs = $func->select_like('studtbl',array('lName','fName','mName',$fullname )); $studs = $func->select_one('studtbl',array('curYrlevel','=',$yr_select)); $arr_section = $func->select_distinctwhere('studtbl','curSection','ASC',array('curSection'),array('curYrlevel','=',$yr_select)); //["3","5","8"]; $yr_selected = $yr_select; $totalcountrow = count($studs); //$pages = ceil($totalcountrow/$perPage); $view = $studs; $studtext = $fullname; $var_str = var_export($studtext, true); $var = "<?php\n\n\$studtext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'studlistvar.php', $var); } else if ($studtext != null && (isset($_POST['sortNameDesc'])) ) { $studs = $func->select_like('studtbl',array('lName','fName','mName',$studtext )); $totalcountrow = count($studs); //$pages = ceil($totalcountrow/$perPage); $view = $studs; } else if ($studtext != null && (isset($_POST['sortNameAsc']))) { $studs = $func->select_like('studtbl',array('lName','fName','mName',$studtext )); $totalcountrow = count($studs); //$pages = ceil($totalcountrow/$perPage); $view = $studs; }else if ((isset($_POST['sortNameDesc']))) { $studs = $func->selectallorderby('studtbl','lName','DESC'); $totalcountrow = count($studs); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('studtbl','lName','DESC',$start,$perPage); } else if ((isset($_POST['sortNameAsc']))) { $studs = $func->selectallorderby('studtbl','lName','ASC'); $totalcountrow = count($studs); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('studtbl','lName','ASC',$start,$perPage); }else { $studs = $func->selectallorderby('studtbl','lName','ASC'); $totalcountrow = count($studs); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('studtbl','lName','ASC',$start,$perPage); $studtext = $fullname; $var_str = var_export($studtext, true); $var = "<?php\n\n\$studtext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'studlistvar.php', $var); } ?> <!DOCTYPE html> <head> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> .container .well{ background-color: #13D8F3; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } .paper { background: #fff; padding: 30px; position: relative; } .paper, .paper::before, .paper::after { /* Styles to distinguish sheets from one another */ box-shadow: 1px 1px 1px rgba(0,0,0,0.25); border: 1px solid #bbb; } .paper::before, .paper::after { content: ""; position: absolute; height: 95%; width: 99%; background-color: #eee; } .paper::before { right: 15px; top: 0; transform: rotate(-1deg); z-index: -1; } .paper::after { top: 5px; right: -5px; transform: rotate(1deg); z-index: -2; } .wrapper { height: 550px; border : 10px double green; border-radius: 5px; overflow-y: auto; background-color:white; } .papel { background: #fff; box-shadow: /* The top layer shadow */ 0 -1px 1px rgba(0,0,0,0.15), /* The second layer */ 0 -10px 0 -5px #eee, /* The second layer shadow */ 0 -10px 1px -4px rgba(0,0,0,0.15), /* The third layer */ 0 -20px 0 -10px #eee, /* The third layer shadow */ 0 -20px 1px -9px rgba(0,0,0,0.15); /* Padding for demo purposes */ padding: 30px; } a:hover { background-color: yellow; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } img#propix { max-width:100px; } H1,H2, H5#pangs { font-family: 'Sonsie One'; font-size: 30px; color: blue; } .col-lg-2 { background-color:#add8e6; height: 550px; } hr { border: 2px solid blue; } </style> <script> document.getElementById('studlist').className = "active"; </script> </head> <body> <div class="container-fluid"> <br><br> <div class="row" > <div class="col-lg-1" > </div> <div class="col-lg-10" > <br> <div class="papel"> <div class="col-md-12 form-group"> <div class="col-md-1"> <a href="studlist.php" > <img src ="img/showicon.png" class="img-responsive" id="propix" name="showpropix"></img></a> </div> <div class="col-md-3"> <a href="addstud.php" ><img src ="img/addnewicon.png" class="img-responsive" id="propix" name="addpropix"></img></a> </div> <div class="col-md-6"> <H1>Student List</H1> </div> </div> <hr> <form method="post"> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Search Name:</label> <div class="col-md-4"> <input type="text" placeholder="Enter Name Here.." class="form-control" name="searchname" > </div> <div class="col-md-2"> <input type="submit" name="searchnamebut" value="search" class="btn btn-primary"> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Select by Year</label> <div class="col-md-4"> <select class="form-control" name="select_yr"> <option value="1" <?php if($yr_selected == 1) echo "selected"?>>1st year</option> <option value="2" <?php if($yr_selected == 2) echo "selected"?>>2nd year</option> <option value="3" <?php if($yr_selected == 3) echo "selected"?>>3rd year</option> <option value="4" <?php if($yr_selected == 4) echo "selected"?>>4th year</option> <option value="5" <?php if($yr_selected == 5) echo "selected"?>>5th year</option> </select> </div> <div class="col-md-2"> <input type="submit" name="yrsearchnamebut" value="search" class="btn btn-primary"> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Select by Section</label> <div class="col-md-4"> <select class="form-control" name="select_yr"> <?php for($n=0;$n<count($arr_section);$n++){ ?> <option value="<?php echo escape($arr_section[$n]['curSection']); ?>"> <?php echo escape($arr_section[$n]['curSection']); ?> </option> <?php } ?> </select> </div> <div class="col-md-2"> <input type="submit" name="secsearchbut" value="search" class="btn btn-primary"> </div> </div> </form> <!--table --> <!-- /. NAV SIDE --> <div class="row" > <div class="col-lg-12"> <div class="container-fluid"><br> <div class="row"> <center> <div class="table-responsive"> <table width:800px class="table table-hover" height:100px; overflow: scroll; > <form method="post"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No</td> <td>Name <input type="submit" name="sortNameAsc" value="<?php echo chr(30)?>" class="btn btn-info"> <input type="submit" name="sortNameDesc" value="<?php echo chr(31)?>" class="btn btn-info"> </td> <td>Local Address </td> <td>Cellphone #</td> <td>Email</td> <td >Action</td> </strong> </tr> </form> <?php $y = 1;?> <?php if (count($view) == 0) { echo "No Post Available"; } else { for($x=0;$x<count($view);$x++){ $y = ($y + 1)*$page; ?> <tr onclick="getElementById('.<?php echo escape($x) +1; ?>.').click()" style="cursor: pointer"> <td> <?php if($page>1){ $pagec = (($page *10)-10) + $x +1; echo $pagec; } else { echo $x +1; } ?> </td> <td> <?php echo escape($view[$x]['lName']).", ". escape($view[$x]['fName']) ." ". escape($view[$x]['mName']); ?> </td> <td> <?php echo escape($view[$x]['brgy']) .", ". escape($view[$x]['city']) .", ". escape($view[$x]['prov']); ?> </td> <td> <?php echo escape($view[$x]['cpnum']); ?> </td> <td> <?php echo escape($view[$x]['email']); ?> </td> <form method="post"> <input type="hidden" name="mid" value="<?php echo escape($view[$x]['studID']); ?>"> <input type="hidden" name="pid" value="<?php echo escape($view[$x]['pid']); ?>"> <td> <a href="viewstud.php?id=<?php echo escape($view[$x]['studID']); ?> " id=".<?php echo escape($x) +1; ?>."></a> <a href="editstud.php?id=<?php echo escape($view[$x]['studID']); ?> " id=".<?php echo escape($x) +1; ?>."><button type="button" class="btn btn-success">Edit</button></a> <a href="studlist.php?mid=<?php echo escape($view[$x]['studID']); ?>"> <input type="submit" name="delete" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?')"> </a> </td> </form> </tr> <?php } } ?> </table> </center> <ul class="actions pagination"> <?php for($x = 1; $x <= $pages; $x++): ?> <li><a href="?page=<?php echo $x; ?>"<?php if($page === $x) {echo ' class="button selected"';} ?>><?php echo $x; ?></a></li> <?php endfor; ?> </ul> </div> </div> </div> </div> </div> <!-- /. PAGE INNER --> <!--end table--> </div> </div> </div> <br> <br> <br> </body> <file_sep>/menuside_stud.php <head> <title>Simple Responsive Admin</title> <!-- BOOTSTRAP STYLES--> <link href="lib/assets/css/bootstrap.css" rel="stylesheet" /> <!-- FONTAWESOME STYLES--> <link href="lib/assets/css/font-awesome.css" rel="stylesheet" /> <!-- CUSTOM STYLES--> <link href="lib/assets/css/custom.css" rel="stylesheet" /> <!-- JQUERY--> <script src="lib/bootstrap/js/jquery-3.2.1.js"></script> <!-- GOOGLE FONTS--> <link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css' /> <?php $x =2; ?> </head> <body> <div id="mydiv"> <script> document.getElementById('dash').className = "active"; var but = document.createElement('button'); var spn1 = document.createElement('span'); var spn2 = document.createElement('span'); var spn3 = document.createElement('span'); //creates set elements attribute but.setAttribute('class','navbar-toggle'); but.setAttribute('data-toggle','collapse'); but.setAttribute('data-target','.sidebar-collapse'); spn1.setAttribute('class','icon-bar'); spn2.setAttribute('class','icon-bar'); spn3.setAttribute('class','icon-bar'); but.appendChild(spn1); but.appendChild(spn2); but.appendChild(spn3); document.getElementById('bub').appendChild(but); </script> <div id="wrapper"> <!-- /. NAV TOP --> <nav class="navbar-default navbar-side" role="navigation"> <div class="sidebar-collapse"> <ul class="nav" id="main-menu"> <h3>&nbsp;OPERATIONS</h3> <li class="act" id="main"> <a href="studlist.php" ><i class="fa fa-address-book "></i>Show List<span class="badge" id="include"></span></a> </li > <li class="act" id="msglist"> <a href="addstud.php"><i class="fa fa-user-plus"></i>Add Student<span class="badge" id="show" style="background-color:red"></span></a> </li> </ul> </div> </nav> </div> </div> </body><file_sep>/curriculumview.php <?php include'menu.php'; include'menuside_dash.php'; if ((isset($_POST['delete']))) { $mid = $_POST['mid']; //echo '<script> alert('.$totalcountrow .');</script>'; $delcourse = $func->delete('curri_subjtbl',array('cursubjID','=',$mid)); if ($delcourse){ echo '<script> alert("Record Deleted");</script>'; } else { echo '<script> alert("Delete failed");</script>'; } } if (isset($_POST['savemajorbut'])){ $curiversion= $strip->strip($_POST['curiversion']); $selectprereq= $strip->strip($_POST['select_prereq']); $etopadin = $selectprereq; $strending = (explode(" ",$selectprereq)); $bagongmajornum = end($strending); $bagongmajortext = str_replace($bagongmajornum, " ", $etopadin); $majortitle= $strip->strip($_POST['majortitle']); $selectcourse= $strip->strip($_POST['selectCourse']); $pid=$_POST['idnya']; $courseUpdate = $func->update('curriculum','currID',$pid, array( 'curriName' => $bagongmajortext, 'majorID' => $bagongmajornum, 'version' => $curiversion )); if($courseUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING FAILED !!");</script>'; } } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#000; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('prospectus').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs">Prospectus</p> <div id="page-inner"> <div class="row" > <div class="col-lg-11 form-group paper"> <br> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('curriculum',array('currID','=',$col)); if ($cors){ //function select_distinctwhere($table,$byfield,$sortorder,$col_arr = array(),$saan = array()){ $angyear =$func->select_distinctwhere('curri_subjtbl','year','ASC',array('year'),array('currID','=',$col)); $angsem =$func->select_distinctwhere('curri_subjtbl','year','ASC',array('sem'),array('currID','=',$col)); //echo '<script> alert(' .count($angsem). ');</script>'; ?> <p id="pangs" ><?php echo escape($cors[0]['curriName']);?></p> <strong><a href="curriculum.php">Back to List</a></strong> <center> <?php for($sx=1;$sx<=count($angyear);$sx++){ for($ssx=1;$ssx<=count($angsem);$ssx++){ ?> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table width:1000px class="table table-hover" height:100px; overflow: scroll; > <tr style=" color:#ffffff; background-color:#0080ff; font-weight: bolder;"> <td><?php $yrarr = array('1st', '2nd', '3rd', '4th', '5'); echo $yrarr[$sx-1]; ?> Year </td> <td colspan="6"><?php $semarr = array('1st Semester', '2nd Semester', 'summer'); echo $semarr[$ssx-1];?></td> </tr> <tr style=" color:#ffffff; background-color:#4863A0;"> <td>Code </td> <td>Description</td> <td >Credit</td> <td >Lec</td> <td >Lab</td> <td >Pre-req</td> <td >Action</td> </tr> <?php // echo '<script> alert(' .$col. ');</script>'; $view = $func->select_logics2('curri_subjtbl',array('year','=',$sx),'AND',array('sem','=',$ssx),'AND',array('currID','=',$col)); //echo '<script> alert(' .count($view). ');</script>'; for($m=0;$m<count($view);$m++){ $selcsubj = $func->select_one('subjtbl',array('subjID','=',$view[$m]['subjID'])); ?> <tr> <td><?php echo escape($selcsubj[0]['subjCode']); ?> </td> <td ><?php echo escape($selcsubj[0]['subjTitle']); ?></td> <td> <?php if(escape($selcsubj[0]['subjUnit']) == 0){ echo ""; } else if(escape($selcsubj[0]['subjUnit']) <= 0) { $subl = escape($selcsubj[0]['subjUnit']) * -1; echo '('.$subl.')'; } else{ echo escape($selcsubj[0]['subjUnit']); } ?> </td> <td > <?php if(escape($selcsubj[0]['subjLec']) == 0){ echo ""; } else if(escape($selcsubj[0]['subjLec']) <= 0) { $subl = escape($selcsubj[0]['subjLec']) * -1; echo '('.$subl.')'; } else{ echo escape($selcsubj[0]['subjLec']); } ?> </td> <td > <?php if(escape($selcsubj[0]['subjLab']) == 0){ echo ""; } else if(escape($selcsubj[0]['subjLab']) <= 0) { $subl = escape($selcsubj[0]['subjLab']) * -1; echo '('.$subl.')'; } else{ echo escape($selcsubj[0]['subjLab']); } ?> </td> <td > <?php $subjl4 = $func->selectall_where('prereqtbl',array('subjID','=',$selcsubj[0]['subjID'])); //$ar=array(); for($nw=0;$nw<count($subjl4);$nw++){ //echo escape($subjlist4[$n]['prereqSub']); $subjl5 = $func->selectall_where('subjtbl',array('subjID','=',$subjl4[$nw]['prereqSub'])); echo escape($subjl5[0]['subjCode']) . ", "; //array_push($ar,$subjlist4[$n]['prereqSub']); } //print_r($ar); ?> </td> <form method="POST"> <input type="hidden" name="mid" value="<?php echo escape($view[$m]['cursubjID']); ?>"> <td> <a href="curriculumedit.php?id=<?php echo escape($view[$m]['cursubjID']); ?> " id=".<?php echo escape($view[$m]['cursubjID']); ?>.">Edit</a> <input type="submit" name="delete" value="Del" class="btn btn-link" onclick="return confirm('Are you sure you want to delete?')"> </td> </form> </tr> <?php } ?> </table> </div> <?php } } ?> </center> <?php } ?> <button type="submit" class="btn btn-md btn-info" name="savemajorbut" style="float:right">Save</button> </div> </div> </div> </div> </div> </div> <file_sep>/certofgrade.php <?php include 'menu.php'; //include'menuside_stud.php'; //delete enrolled course if ((isset($_POST['updategrades']))) { $mid = $_POST['mid']; $inputratings= $strip->strip($_POST['inputratings']); $inputrexam= $strip->strip($_POST['inputrexam']); $remarks = 0; if($inputratings <= $inputrexam){ if($inputratings >= 6){ $remarks = 2; } else{ $remarks = 0; } } else { if($inputrexam <= 3){ $remarks = 1; } else{ $remarks = 0; } } echo '<script>alert('.$mid.');</script>'; echo '<script>alert('.$inputratings.');</script>'; $studUpdate = $func->update('gradetbl','gradeID',$mid, array( 'rating' => $inputratings, 'rexam' => $inputrexam, 'remarks' => $remarks )); if($studUpdate){ echo '<script>alert("panalo");</script>'; } else { echo '<script>alert("EDITING STUDENT FAILED !!");</script>'; } } //test if (isset($_POST['regibutton'])){ $select_maj = $strip->strip($_POST['select_maj']); $select_year = $strip->strip($_POST['select_year']); $select_sem = $strip->strip($_POST['select_sem']); $acad_year = $strip->strip($_POST['acad_year']); $cursection = $strip->strip($_POST['cursection']); $selectresidency = $strip->strip($_POST['select_residency']); $idreg= $strip->strip($_POST['idreg']); $bagong= $strip->strip($_POST['tago']); $blgna= $strip->strip($_POST['blgna']); $blgna= $blgna + 1; $regstrUpdate = $func->update('registrationtbl','regID',$idreg, array( 'regMajor' => $select_maj, 'regYrlevel' => $select_year, 'regSem' => $select_sem, 'regAcadYr' => $acad_year, 'regSection' => $cursection, 'regResidency' => $selectresidency )); if($regstrUpdate){ for($nsan= $blgna ;$nsan<=$bagong;$nsan++){ $bagin = "bago". $nsan; $bags= $strip->strip($_POST[$bagin]); $gradeInsert = $func->insert('gradetbl',array( 'regID' => $idreg, 'subjID' => $bags )); } } if($regstrUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING COURSE FAILED !!");</script>'; } } ?> <!DOCTYPE html> <head> <script src="FileSaver.js"></script> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> .container .well{ background-color: #13D8F3; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } @media print { @page {margin: 0;} body {margin: 1.6cm;} img { max-height: 50px !important; max-width:50px !important; } } .paper { background: #fff; padding: 30px; position: relative; } .paper, .paper::before, .paper::after { /* Styles to distinguish sheets from one another */ box-shadow: 1px 1px 1px rgba(0,0,0,0.25); border: 1px solid #bbb; } .paper::before, .paper::after { content: ""; position: absolute; height: 95%; width: 99%; background-color: #eee; } .paper::before { right: 15px; top: 0; transform: rotate(-1deg); z-index: -1; } .paper::after { top: 5px; right: -5px; transform: rotate(1deg); z-index: -2; } .wrapper { height: 550px; border : 10px double green; border-radius: 5px; overflow-y: auto; background-color:white; } .papel { background: #fff; box-shadow: /* The top layer shadow */ 0 -1px 1px rgba(0,0,0,0.15), /* The second layer */ 0 -10px 0 -5px #eee, /* The second layer shadow */ 0 -10px 1px -4px rgba(0,0,0,0.15), /* The third layer */ 0 -20px 0 -10px #eee, /* The third layer shadow */ 0 -20px 1px -9px rgba(0,0,0,0.15); /* Padding for demo purposes */ padding: 30px; } a:hover { background-color: yellow; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } img#propix { max-width:100px; } H1, H5#pangs { font-family: 'Sonsie One';font-size: 25px; } H2 { font-family: 'Sonsie One';font-size: 17px; } #desss{ font-family: 'Sonsie One';font-size: 15px; } .col-lg-2 { background-color:#add8e6; height: 550px; } hr { border: 2px solid black; } .table-bordered th, .table-bordered td { padding: 15px !important; text-align: center !important; border: 1px solid #000 !important; } </style> </head> <body> <div class="container-fluid"> <br> <br> <div class="row" > <div class="col-lg-1" > </div> <div class="col-lg-10" > <br> <div class="papel"> <div class="col-md-12 form-group"> <div class="col-md-1"> <a href="studlist.php" > <img src ="img/showicon.png" class="img-responsive" id="propix" name="showpropix"></img> </a> </div> <div class="col-md-3"> </div> <div class="col-md-6"> <H1>Student Record</H1> <H2>(Grade per Registration)</H2> </div> </div> <hr> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('registrationtbl',array('regID','=',$col)); if ($cors){ ?> <a href="reportstud.php?id=<?php echo escape($cors[0]['studID']); ?>">Back</a> <form method="POST" name="add_student"> <div class="paper"> <?php $studinfo = $func->select_one('studtbl',array('studID','=',$cors[0]['studID'])); ?> <div class="col-md-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Student No: </label> <label class="col-md-2 control-label"><u id="desss"> <?php echo escape($studinfo[0]['studNum']) ?></u> </label> <label class="col-md-3 control-label" style="text-align: right">Student Name:</label> <label class="col-md-5 control-label"><u id="desss"><?php echo escape($studinfo[0]['lName']).", ". escape($studinfo[0]['fName']) ." ". escape($studinfo[0]['mName']); ?></u> </label> </div> </div> <div class="row" > <div class="col-lg-12" > <h3>Academic Status</h3> <div class="col-lg-12 form-group"> <div id="addnewcourse" > <div class="col-lg-12 form-group"> <!-- function selectjoin_where($table,$table2,$ref,$ref2,$table3,$where = array()){ --> <?php $majorc1 = $func->select_one('curriculum',array('currID','=',$cors[0]['currID'])); ?> <label class="col-md-2 control-label" style="text-align: right">Course & Major:</label> <label class="col-md-5 control-label" ><?php echo escape($majorc1[0]['curriName']); ?></label> <label class="col-md-2 control-label" style="text-align: right">Acad Year:</label> <label class="col-md-3 control-label" ><?php echo escape($cors[0]['regAcadYr']);?></label> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Year Level:</label> <label class="col-md-5 control-label"> <?php if($cors[0]['regYrlevel'] == '1'){ echo "1st Year"; } else if($cors[0]['regYrlevel'] == '2'){ echo "2nd Year"; } else if($cors[0]['regYrlevel'] == '3'){ echo "3rd Year"; } else if($cors[0]['regYrlevel'] == '4'){ echo "4th Year"; } else if($cors[0]['regYrlevel'] == '5'){ echo "5th Year"; } ?></label> <label class="col-md-2 control-label" style="text-align: right">Semester:</label> <label class="col-md-2 control-label"> <?php if($cors[0]['regSem'] == '1'){ echo "1st sem"; } else if($cors[0]['regSem'] == '2'){ echo "2nd sem"; } else if($cors[0]['regSem'] == '3'){echo "Summer"; } else if($cors[0]['regSem'] == '4'){ echo "Midyear"; } ?> </label> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Section:</label> <label class="col-md-5 control-label"> <?php echo escape($cors[0]['regSection']);?> </label> <label class="col-md-2 control-label" style="text-align: right">Residency :</label> <label class="col-md-3 control-label"> <?php if($cors[0]['regResidency'] == '0'){ echo "In-house"; } else if($cors[0]['regResidency'] == '1'){ echo "Transferee"; } ?> </label> </div> <div class="col-lg-12 form-group"> <div class="row" > <div id="printarea"> <br><br><br> <?php $pangalannya = $func->select_one('studtbl',array('studID','=',$cors[0]['studID'])); ?> <?php $angang = $func->select_one('curriculum',array('currID','=',$cors[0]['currID'])); ?> <?php $angcoursemajor = $func->selectjoin_where('coursetbl','majortbl','courseID','courseID','majortbl',array('majorID','=',$angang[0]['majorID'])); //echo '<script> alert('.count($angcoursemajor).');</script>'; ?> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is to certifies that according to the records in this university,<strong> <?php if($pangalannya[0]['gender'] == 1){echo "MR. ";}else{echo "MS. ";} echo strtoupper(escape($pangalannya[0]['fName']))." "; echo strtoupper(escape($pangalannya[0]['mName']))." "; echo strtoupper(escape($pangalannya[0]['lName']))." ";?> </strong> was officically enrolled under the program <strong><?php echo escape($angcoursemajor[0]['courseTitle'])." (". escape($angcoursemajor[0]['majorName']) .") ";?> </strong> and has obtained the following grades for: </p> <center> <p><strong><?php if ($cors[0]['regYrlevel'] == 1){ echo "1st Year ";} else if ($cors[0]['regYrlevel'] == 2){ echo "2nd Year ";} else if ($cors[0]['regYrlevel'] == 3){ echo "3rd Year ";} else if ($cors[0]['regYrlevel'] == 4){ echo "4th Year ";} else if ($cors[0]['regYrlevel'] == 5){ echo "5th Year ";} if ($cors[0]['regSem'] == 1){ echo "1st Semester ";} else if ($cors[0]['regSem'] == 2){ echo "2nd Semester ";} else if ($cors[0]['regSem'] == 3){ echo "Summer ";} else if ($cors[0]['regSem'] == 4){ echo "Midyear ";} ?> A.Y. <?php echo " ". escape($cors[0]['regAcadYr']);?> </strong></p> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <?php $selectenrollsub = $func->select_one('gradetbl',array('regID','=',$cors[0]['regID'])); ?> <table width:800px class="table table-bordered" height:100px; overflow: scroll; id="myTable"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>Subj. Code</td> <td>Descriptive Title</td> <td>Units</td> <td>Grades</td> <td>Remarks</td> </tr> <?php if (count($selectenrollsub) == 0) {echo "No Post Available"; } else { //echo '<script> alert('.$col .');</script>'; $totalnun = 0; $totalgrade = 0; $unitgrade = 0; for($t=0;$t<count($selectenrollsub);$t++){ ?> <tr> <?php $subjlist41 = $func->select_one('subjtbl',array('subjID','=',$selectenrollsub[$t]['subjID'])); ?> <td><?php echo escape($subjlist41[0]['subjCode']); ?> </td> <td><?php echo escape($subjlist41[0]['subjTitle']);?> </td> <td> <?php if(escape($subjlist41[0]['subjUnit']) == 0){ echo ""; } else if(escape($subjlist41[0]['subjUnit']) <= 0) { $subl = escape($subjlist41[0]['subjUnit']) * -1; echo '('.$subl.')'; } else{ echo escape($subjlist41[0]['subjUnit']); } ?> </td> <td><?php if ($selectenrollsub[$t]['rating'] == 0){ echo null;} else {echo escape($selectenrollsub[$t]['rating']); } ?> </td> <?php if($subjlist41[0]['subjUnit'] < 0){ $nun = 0; } else { $nun = $subjlist41[0]['subjUnit']; } $totalnun = $totalnun + $nun; $unitgrade = $selectenrollsub[$t]['rating'] * $nun; $totalgrade = $totalgrade + $unitgrade; ?> <td><?php if($selectenrollsub[$t]['remarks'] == 1){ echo "Passed"; }else if($selectenrollsub[$t]['remarks'] == 0){ echo "Failed"; }?></td> </tr> <?php } ?> <tr> <td></td> <td> <center>X----------------------------------------------X</center></td> <td> <?php echo $totalnun; ?></td> <td> </td> <td></td> </tr> <tr> <td></td> <td style="text-align: right;"><strong> GENERAL AVERAGE<strong></td> <td> </td> <td > <p style="font-weight: bolder; font-size: 25px"><?php $avegrade = $totalgrade / $totalnun; echo round($avegrade,2); ?> </p></td> <td></td> </tr> <input type="hidden" class="form-control" name="blgna" value="<?php echo count($selectenrollsub); ?>"> <input type="hidden" class="form-control" name="idreg" value="<?php echo escape($cors[0]['regID']); ?>"> <?php } ?> </table> </div> </center> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;This is certification is issued this <?php $currentDay = date('d'); if($currentDay == 1){echo "1st ";} else if($currentDay == 2){echo "2nd ";} else if($currentDay == 3){echo "3rd ";} else{ echo $currentDay ."th "; } ?>day of <?php echo " ".date('F Y')?> upon the request of the above-named person for references purposes.</p> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Prepared by:</p> <?php $staffko = $func->select_one('stafftbl',array('staffID','=',$staffid)); ?> <p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong><?php echo strtoupper(escape($staffko[0]['firstName'])." ". substr(escape($staffko[0]['midName']),0,1) .". ".escape($staffko[0]['lastName'])) ; ?></strong><br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Clerk &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Checked and Verified by:</p> <p >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong><NAME></strong></p> <p >&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Campus Registrar</p> </div> </div> <a href="cor_print.php?id=<?php echo $col; ?>&stf=<?php echo $staffid; ?>"><button type="button" class="btn btn-success">Print COG</button></a> <!-- <button type="submit" class="btn btn-success" name="printdata" onclick="printDiv('printarea')">Print Form</button> --> </div> </div> </form> </div> <hr> <!-- registration list --> <div> <a class="word-export" href="javascript:void(0)" onclick="ExportToDoc()">Export to Doc</a> </div> <?php } ?> </div> </div> </div> </div> </div> </div> </div> <br> <br> <br> <script> document.getElementById('ownerlist').className = "active-link"; $("link[rel*='icon']").attr("href", "img/logo.png"); function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <script type="text/javascript"> function ExportToDoc(filename = ''){ var HtmlHead = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' ><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>"; var EndHtml = "</body></html>"; //complete html var html = HtmlHead +document.getElementById("printarea").innerHTML+EndHtml; //specify the types var blob = new Blob(['\ufeff', html], { type: 'application/msword' }); // Specify link url var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html); // Specify file name filename = filename?filename+'.doc':'document.doc'; // Create download link element var downloadLink = document.createElement("a"); document.body.appendChild(downloadLink); if(navigator.msSaveOrOpenBlob ){ navigator.msSaveOrOpenBlob(blob, filename); }else{ // Create a link to the file downloadLink.href = url; // Setting the file name downloadLink.download = filename; //triggering the function downloadLink.click(); } document.body.removeChild(downloadLink); } </script> </body> <file_sep>/vars/lance09553846491subjvar.php <?php $majortext = NULL; ?><file_sep>/addstud.php <?php include 'menu.php'; //include'menuside_stud.php'; //add students if (isset($_POST['addstudent'])){ $studnum= $strip->strip($_POST['studnum']); $stud_fname= $strip->strip($_POST['stud_fname']); $stud_midname= $strip->strip($_POST['stud_midname']); $stud_lname= $strip->strip($_POST['stud_lname']); $stud_bday= $strip->strip($_POST['stud_bday']); $stud_cpno= $strip->strip($_POST['stud_cpno']); $stud_gender= $strip->strip($_POST['stud_gender']); $stud_email= $strip->strip($_POST['stud_email']); $stud_prk= $strip->strip($_POST['stud_prk']); $stud_brgy= $strip->strip($_POST['stud_brgy']); $stud_city= $strip->strip($_POST['stud_city']); $stud_prov= $strip->strip($_POST['stud_prov']); $stud_elem= $strip->strip($_POST['stud_elem']); $stud_hs= $strip->strip($_POST['stud_hs']); //checking if username is still available $selectUser = $func->select_one('studtbl',array('studnum','=',$studnum)); if($selectUser){ echo '<script>alert("REGISTRATION FAILED: student number already exist!!");</script>'; } else { $studentInsert = $func->insert('studtbl',array( 'studnum' => $studnum, 'fName' => $stud_fname, 'mName' => $stud_midname, 'lname' => $stud_lname, 'gender' => $stud_gender, 'DOB' => $stud_bday, 'email' => $stud_email, 'cpnum' => $stud_cpno, 'prk' => $stud_prk, 'brgy' => $stud_brgy, 'city' => $stud_city, 'prov' => $stud_prov, 'elem' => $stud_elem, 'highSchool' => $stud_hs )); echo '<script>alert("Added Successfully");</script>'; } } ?> <!DOCTYPE html> <head> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> .container .well{ background-color: #13D8F3; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } .paper { background: #fff; padding: 30px; position: relative; } .paper, .paper::before, .paper::after { /* Styles to distinguish sheets from one another */ box-shadow: 1px 1px 1px rgba(0,0,0,0.25); border: 1px solid #bbb; } .paper::before, .paper::after { content: ""; position: absolute; height: 95%; width: 99%; background-color: #eee; } .paper::before { right: 15px; top: 0; transform: rotate(-1deg); z-index: -1; } .paper::after { top: 5px; right: -5px; transform: rotate(1deg); z-index: -2; } .wrapper { height: 550px; border : 10px double green; border-radius: 5px; overflow-y: auto; background-color:white; } .papel { background: #fff; box-shadow: /* The top layer shadow */ 0 -1px 1px rgba(0,0,0,0.15), /* The second layer */ 0 -10px 0 -5px #eee, /* The second layer shadow */ 0 -10px 1px -4px rgba(0,0,0,0.15), /* The third layer */ 0 -20px 0 -10px #eee, /* The third layer shadow */ 0 -20px 1px -9px rgba(0,0,0,0.15); /* Padding for demo purposes */ padding: 30px; } a:hover { background-color: yellow; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } img#propix { max-width:100px; } H1,H2, H5#pangs { font-family: 'Sonsie One';font-size: 25px; } .col-lg-2 { background-color:#add8e6; height: 550px; } hr { border: 2px solid black; } </style> <script> document.getElementById('studlist').className = "active"; </script> </head> <body> <div class="container-fluid"> <br> <br> <div class="row" > <div class="col-lg-1" > </div> <div class="col-lg-10" > <br> <div class="papel"> <div class="col-md-12 form-group"> <div class="col-md-1"> <a href="studlist.php" > <img src ="img/showicon.png" class="img-responsive" id="propix" name="showpropix"></img> </a> </div> <div class="col-md-3"> <a href="addstud.php" ><img src ="img/addnewicon.png" class="img-responsive" id="propix" name="addpropix"></img></a> </div> <div class="col-md-6"> <H1>Add New Student</H1> </div> </div> <hr> <form method="POST" name="add_student"> <div class="paper"> <p id="warn"><?php echo $warn; ?></p> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Student No: </label> <div class="col-md-4"> <input type="text" placeholder="Enter Student Number" class="form-control" name="studnum" required> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-3 control-label">Name (First, Middle, Last)</label> <div class="col-md-3"> <input type="text" placeholder="Enter First Name Here.." class="form-control" name="stud_fname" required> </div> <div class="col-md-3"> <input type="text" placeholder="Enter Middle Name Here.." class="form-control" name="stud_midname" required> </div> <div class="col-md-3"> <input type="text" placeholder="Enter Last Name Here.." class="form-control" name="stud_lname" required> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Birthday</label> <div class="col-md-4"> <input type="date" class="form-control" name="stud_bday" required> </div> <label class="col-md-2 control-label">Gender</label> <div class="col-lg-4"> <input type="radio" name="stud_gender" value="1" checked="checked">Male <label class="radio-inline"> <input type="radio" name="stud_gender" value="0"> Female </label> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Email</label> <div class="col-lg-4"> <input type="email" placeholder="Enter Email" class="form-control" name="stud_email"> </div> <label class="col-md-2 control-label">Cellphone No.</label> <div class="col-lg-4"> <input type="number" placeholder="09XXXXXXXXX" class="form-control" max="99999999999" name="stud_cpno" required> </div> </div> <div class="col-md-12 form-group"> <label class="col-md-2 control-label">Elementary</label> <div class="col-lg-4"> <input type="text" placeholder="Ex: Rio Chico Elem. School" class="form-control" name="stud_elem"> </div> <label class="col-md-2 control-label">High School</label> <div class="col-lg-4"> <input type="text" placeholder="Ex: Rio Chico National High School" class="form-control" name="stud_hs" > </div> </div> <div class="col-md-12 form-group"> <label class="col-md-12 control-label">Address ( Prk or Street, Brgy, City or Municipality, Province)</label> <div class="col-lg-3"> <input type="text" placeholder="House No / Prk / Street" class="form-control" name="stud_prk"> </div> <div class="col-lg-3"> <input type="text" placeholder="Barangay" class="form-control" name="stud_brgy"> </div> <div class="col-lg-3"> <input type="text" placeholder="City / Municipality" class="form-control" name="stud_city"> </div> <div class="col-lg-3"> <input type="text" placeholder="Province" class="form-control" name="stud_prov"> </div> </div> <div class="g-recaptcha" data-sitekey="<KEY>"></div> <center><button type="submit" class="btn btn-lg btn-info" name="addstudent" >Add New</button> <button type="reset" class="btn btn-lg btn-danger" name="clearfrm">Clear form</button> </center> </div> </form> </div> </div> </div> </div> <br> <br> <br> </body> <file_sep>/src/db.php <?php date_default_timezone_set('Asia/Manila'); $con = new mysqli("localhost","root","","gmsdb"); if (mysqli_connect_errno()) { printf("Connect failed: %s\n", mysqli_connect_error()); exit(); } // error_reporting(0); ?> <file_sep>/prereq.php <?php include'menu.php'; include'menuside_dash.php'; include 'vars/'.$usern.'subjvar.php'; $nnn = null; //add major if (isset($_POST['addsubbut'])){ $selectprereq= $strip->strip($_POST['select_prereq']); $selecttosubj= $strip->strip($_POST['select_tosubj']); $preInsert = $func->insert('prereqtbl',array( 'prereqSub' => $selectprereq, 'subjID' => $selecttosubj )); if($preInsert){ // echo '<script>alert("New Subject Added Successfully");</script>'; } else { echo '<script>alert("Adding Failed");</script>'; } } // display table content $y = 1; $sttt = null; if ((isset($_POST['delete']))) { $mid = $_POST['mid']; //echo '<script> alert('.$totalcountrow .');</script>'; $delcourse = $func->delete('prereqtbl',array('prereqID','=',$mid)); if ($delcourse){ echo '<script> alert("Record Deleted");</script>'; } else { echo '<script> alert("Delete failed");</script>'; } } $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; $perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 50; //Positioning $start = ($page > 1) ? ($page * $perPage) - $perPage : 0; //Pages //check queries with search $majorunit = $func->selectall('prereqtbl'); $totalcountrow = count($majorunit); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('prereqtbl','prereqID','ASC',$start,$perPage); ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#fff; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('subject').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs">Pre-requisites Subjects </p> <div id="page-inner"> <div class="row" > <div class="col-lg-12 form-group"> <button type="button" class="btn btn-success" data-toggle="collapse" data-target="#addnewsubject">Add Pre-req Subject</button> <br> <form method="POST" name="add_subject"> <div id="addnewsubject" class=" collapse"> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-2 control-label" style="text-align: right">Pre-req:</label> <div class="col-md-8"> <select class="form-control" name="select_prereq"> <?php $subjlist1 = $func->selectallorderby('subjtbl','subjCode','ASC'); //echo '<script> alert(' .count($subjlist1). ');</script>'; for($n=0;$n<count($subjlist1);$n++){ ?> <option value="<?php echo escape($subjlist1[$n]['subjID']); ?>"> <?php echo escape($subjlist1[$n]['subjCode']) . " -- " . escape($subjlist1[$n]['subjTitle']); ?></option> <?php } ?> </select> </div> </div> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-2 control-label" style="text-align: right">to Subject :</label> <div class="col-md-8"> <select class="form-control" name="select_tosubj"> <?php $subjlist2 = $func->selectallorderby('subjtbl','subjCode','ASC'); for($n=0;$n<count($subjlist2);$n++){ ?> <option value="<?php echo escape($subjlist2[$n]['subjID']); ?>"> <?php echo escape($subjlist2[$n]['subjCode']) . " -- " . escape($subjlist2[$n]['subjTitle']); ?></option> <?php } ?> </select> </div> </div> <div class="col-md-11"> <button type="submit" class="btn btn-md btn-info" name="addsubbut" style="float: right" >Submit</button> </div> </div> </div> </form> <!-- list --> <div class="col-lg-12"> <hr> <h3>Pre-requisite Subject List: </h3> </div> <div class="col-lg-12"> <div class="row" > <center> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table width:1000px class="table table-hover" height:100px; overflow: scroll; > <form method="POST"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No <br><span class="badge badge-success"><?php echo $totalcountrow; ?></span></td> <td>Pre-requisite Subject (Code - Title)</td> <td>of Subject (Code - Title)</td> <td >Action</td> </tr> </form> <?php if (count($view) == 0) { echo "No Post to Show"; } else { //echo '<script> alert('.count($view) .');</script>'; for($x=0;$x<count($view);$x++){ $y = ($y + 1)*$page; //echo '<script> alert('.$x .');</script>'; ?> <tr > <td> <?php if($page>1){ $pagec = (($page *10)-10) + $x +1; echo $pagec; } else { echo $x +1; } ?> </td> <td> <?php $subjlist3 = $func->selectall('subjtbl'); for($n=0;$n<count($subjlist3);$n++){ if($subjlist3[$n]['subjID'] == $view[$x]['prereqSub']){ ?> <strong> <?php echo escape($subjlist3[$n]['subjCode']) ?> </strong>&nbsp; - &nbsp; <?php echo escape($subjlist3[$n]['subjTitle']); } } ?> </td> <td> <?php $subjlist4 = $func->selectall('subjtbl'); for($n=0;$n<count($subjlist4);$n++){ if($subjlist4[$n]['subjID'] == $view[$x]['subjID']){ ?> <strong> <?php echo escape($subjlist4[$n]['subjCode']) ?> </strong>&nbsp; - &nbsp; <?php echo escape($subjlist4[$n]['subjTitle']); } } ?> </td> <form method="POST"> <input type="hidden" name="mid" value="<?php echo escape($view[$x]['prereqID']); ?>"> <td> <a href="prereqedit.php?id=<?php echo escape($view[$x]['prereqID']); ?> " id=".<?php echo escape($x) +1; ?>."><button type="button" class="btn btn-success"> &nbsp;&nbsp;Edit&nbsp;&nbsp;&nbsp; </button></a> <input type="submit" name="delete" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?')"> </td> </form> </tr> <?php } } ?> </table> </center> <ul class="actions pagination"> <?php for($x = 1; $x <= $pages; $x++): ?> <li><a href="?page=<?php echo $x; ?>"<?php if($page === $x) {echo ' class="button selected"';} ?>><?php echo $x; ?></a></li> <?php endfor; ?> </ul> </div> </div> </div> </div> </div> <file_sep>/vars/subjvar.php <?php $majortext = 'dfs'; ?><file_sep>/core/init.php <?php require_once("src/db.php"); require_once("src/res.php"); require_once("src/strip.php"); require_once("src/escapeoutput.php"); <file_sep>/major.php <?php include'menu.php'; include'menuside_dash.php'; //include 'vars/'.$usern.'majorvar.php'; include 'vars/'.$usern.'majorvar.php'; $nnn = null; //add major if (isset($_POST['addmajorbut'])){ $majortitle= $strip->strip($_POST['majortitle']); $selectcourse= $strip->strip($_POST['selectCourse']); //checking if acronym is still available $cmajor = $func->select_logic('majortbl',array('majorName','=',$majortitle),'AND',array('courseID','=',$selectcourse)); //print_r($cmajor); if($cmajor){ echo '<script>alert("Major in the same course already exist!!");</script>'; } else { $majorInsert = $func->insert('majortbl',array( 'majorName' => $majortitle, 'courseID' => $selectcourse )); if($majorInsert){ echo '<script>alert("New Major Added Successfully");</script>'; } else { echo '<script>alert("Adding Failed");</script>'; } } } // display table content $y = 1; $sttt = null; if ((isset($_POST['delete']))) { $mid = $_POST['mid']; //echo '<script> alert('.$totalcountrow .');</script>'; $delcourse = $func->delete('majortbl',array('majorID','=',$mid)); if ($delcourse){ echo '<script> alert("Record Deleted");</script>'; } else { echo '<script> alert("Delete failed");</script>'; } } $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; $perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 20; //Positioning $start = ($page > 1) ? ($page * $perPage) - $perPage : 0; //Pages //check queries with search if ((isset($_POST['majorbut']))) { $majorname = $_POST['searchmajor']; $cours = $func->selectjoin_like('majortbl','coursetbl','courseID','courseID','majortbl','majorName',$majorname,array('majortbl','majorName','coursetbl','courseTitle')); $totalcountrow = count($cours); //echo '<script> alert('.$totalcountrow .');</script>'; $pages = ceil($totalcountrow/$perPage); $view = $func->selectjoin_likelimit('majortbl','coursetbl','courseID','courseID','majortbl','majorName',$majorname,'ASC',$start,$perPage,array('majortbl','majorName','coursetbl','courseTitle')); $majortext = $majorname; $var_str = var_export($majortext, true); $var = "<?php\n\n\$majortext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'majorvar.php', $var); }else if ($majortext != null && (isset($_POST['sortAcroDesc'])) ) { $cours = $func->selectjoin_like('majortbl','coursetbl','courseID','courseID','majortbl','majorName',$majortext,array('majortbl','majorName','coursetbl','courseTitle')); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectjoin_likelimit('majortbl','coursetbl','courseID','courseID','majortbl','majorName',$majortext,'DESC',$start,$perPage,array('majortbl','majorName','coursetbl','courseTitle')); } else if ($majortext != null && (isset($_POST['sortAcroAsc']))) { $cours = $func->selectjoin_like('majortbl','coursetbl','courseID','courseID','majortbl','majorName',$majortext,array('majortbl','majorName','coursetbl','courseTitle')); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectjoin_likelimit('majortbl','coursetbl','courseID','courseID','majortbl','majorName',$majortext,'ASC',$start,$perPage,array('majortbl','majorName','coursetbl','courseTitle')); }else if ((isset($_POST['sortAcroDesc']))) { $cours = $func->selectjoin('majortbl','coursetbl','courseID','courseID'); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectjoinorderby('majortbl','coursetbl','courseID','courseID','majortbl','majorName','DESC',$start,$perPage); } else if ((isset($_POST['sortAcroAsc']))) { $cours = $func->selectjoin('majortbl','coursetbl','courseID','courseID'); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectjoinorderby('majortbl','coursetbl','courseID','courseID','majortbl','majorName','ASC',$start,$perPage); } else { $majorunit = $func->selectjoin('majortbl','coursetbl','courseID','courseID'); $totalcountrow = count($majorunit); $pages = ceil($totalcountrow/$perPage); $view = $func->selectjoinorderby('majortbl','coursetbl','courseID','courseID','majortbl','majorName','ASC',$start,$perPage); $majortext = $majorname; $var_str = var_export($majortext, true); $var = "<?php\n\n\$majortext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'majorvar.php', $var); } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#fff; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('major').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs"> Major </p> <div id="page-inner"> <div class="row" > <div class="col-lg-12 form-group"> <button type="button" class="btn btn-success" data-toggle="collapse" data-target="#addnewmajor">Add New Major</button> <br> <form method="POST" name="add_course"> <div id="addnewmajor" class=" collapse"> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label"></label> <label class="col-md-2 control-label">Major Title</label> <div class="col-md-5"> <input type="text" placeholder="Ex: Programming" class="form-control" name="majortitle" required> <br> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label"></label> <label class="col-md-2 control-label">Course:</label> <div class="col-md-3"> <select class="form-control" name="selectCourse"> <?php $courselist = $func->selectallorderby('coursetbl','courseAcro','ASC'); for($n=0;$n<count($courselist);$n++){ ?> <option value="<?php echo escape($courselist[$n]['courseID']); ?>"> <?php echo escape($courselist[$n]['courseAcro']); ?></option> <?php } ?> </select> </div> <div class="col-md-3"> <button type="submit" class="btn btn-md btn-info" name="addmajorbut" >Submit</button> </div> </div> </div> </div> </form> <div class="col-lg-12"> <hr> <h3>Major List: </h3> <div class="row" > <form method="POST"> <div class="col-md-12 form-group"> <label class="col-md-3 control-label" style="text-align: right">Search Major/Course:</label> <div class="col-md-4"> <input type="text" class="form-control" placeholder="Ex: Networking" name="searchmajor" > </div> <div class="col-md-2"> <input type="submit" name="majorbut" value="search" class="btn btn-primary"> </div> </div> </form> </div> </div> <div class="col-lg-12"> <div class="row" > <center> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table width:800px class="table table-hover" height:100px; overflow: scroll; > <form method="POST"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No</td> <td>Major Name <input type="submit" name="sortAcroAsc" value="<?php echo chr(30)?>" class="btn btn-info"> <input type="submit" name="sortAcroDesc" value="<?php echo chr(31)?>" class="btn btn-info"> </td> <td>Course:</td> <td >Action</td> </tr> </form> <?php if (count($view) == 0) { echo "No Post to Show"; } else { //echo '<script> alert('.count($view) .');</script>'; for($x=0;$x<count($view);$x++){ $y = ($y + 1)*$page; //echo '<script> alert('.$x .');</script>'; ?> <tr > <td> <?php if($page>1){ $pagec = (($page *10)-10) + $x +1; echo $pagec; } else { echo $x +1; } ?> </td> <td> <?php echo escape($view[$x]['majorName']); ?> </td> <td> <?php echo escape($view[$x]['courseTitle']); ?> </td> <form method="POST"> <input type="hidden" name="mid" value="<?php echo escape($view[$x]['majorID']); ?>"> <td> <a href="majoredit.php?id=<?php echo escape($view[$x]['majorID']); ?> " id=".<?php echo escape($x) +1; ?>."><button type="button" class="btn btn-success">Edit</button></a> <input type="submit" name="delete" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?')"> </td> </form> </tr> <?php } } ?> </table> </center> <ul class="actions pagination"> <?php for($x = 1; $x <= $pages; $x++): ?> <li><a href="?page=<?php echo $x; ?>"<?php if($page === $x) {echo ' class="button selected"';} ?>><?php echo $x; ?></a></li> <?php endfor; ?> </ul> </div> </div> </div> </div> </div> <file_sep>/homeownerlist.php <?php include'menu.php'; include'menuside.php'; ?> <!-- /. NAV SIDE --> <div id="page-wrapper"; > <div id="page-inner"> <div class="row" > <div class="col-lg-12"> <h2>UNIT OWNERS <small><a href="addowner.php">Add</a></small></h2> <div class="container-fluid"><br> <div class="row"> <center> <div class="table-responsive"> <table width:800px class="table table-hover" height:100px; overflow: scroll; > <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No</td> <td>Name</td> <td>Cellphone #</td> <td>Local Address</td> <td>Email</td> <td >Unit No</td> <td >Action</td> </strong> </tr> <?php $y = 1;?> <?php $sttt = null; if ((isset($_POST['delete']))) { $mid = $_POST['mid']; $delete = $func->update('messagebox','msgId',$mid, array( 'msgstatus' => 3 )); } $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; $perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 10; //Positioning $start = ($page > 1) ? ($page * $perPage) - $perPage : 0; //Pages $unitowner = $func->selectjoin('mngt_memberslist','person','pid','person_id'); $totalcountrow = count($unitowner); $pages = ceil($totalcountrow/$perPage); $view = $func->selectjoinorderby('person','mngt_memberslist','person_id','pid','person','lastname',$start,$perPage); echo '<script> alert('.count($view) .');</script>'; if (count($view) == 0) { echo "No Post Available"; } else { for($x=0;$x<count($view);$x++){ $y = ($y + 1)*$page; ?> <tr onclick="getElementById('.<?php echo escape($x) +1; ?>.').click()" style="cursor: pointer"> <td> <?php if($page>1){ $pagec = $page *10 + $x +1; echo $pagec; } else { echo $x +1; } ?> </td> <td> <?php echo escape($view[$x]['lastname']).", ". escape($view[$x]['firstname']); ?> </td> <td> <?php echo escape($view[$x]['cpnum']); ?> </td> <td> <?php echo escape($view[$x]['address']); ?> </td> <td> <?php echo escape($view[$x]['email']); ?> </td> <td> <?php echo escape($view[$x]['houseno']); ?> </td> <form method="post"> <input type="hidden" name="mid" value="<?php echo escape($view[$x]['mem_id']); ?>"> <input type="hidden" name="pid" value="<?php echo escape($view[$x]['pid']); ?>"> <td> <a href="owner.php?id=<?php echo escape($view[$x]['mem_id']); ?> " id=".<?php echo escape($x) +1; ?>.">View Details</a> <a href="homeownerlist.php?mid=<?php echo escape($view[$x]['msgId']); ?>"> <input type="submit" name="delete" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?')"> </a> </td> </form> </tr> <?php } } ?> </table> </center> <ul class="actions pagination"> <?php for($x = 1; $x <= $pages; $x++): ?> <li><a href="?page=<?php echo $x; ?>"<?php if($page === $x) {echo ' class="button selected"';} ?>><?php echo $x; ?></a></li> <?php endfor; ?> </ul> </div> </div> </div> </div> </div> <!-- /. PAGE INNER --> </div> <script> document.getElementById('ownerlist').className = "active-link"; $("link[rel*='icon']").attr("href", "img/logo.png"); </script><file_sep>/src/escapeoutput.php <?php //anti XSS function escape($string ){ return htmlspecialchars($string, ENT_QUOTES,'UTF-8'); } ?><file_sep>/curriculum.php <?php include'menu.php'; include'menuside_dash.php'; //include 'vars/'.$usern.'subjvar.php'; $nnn = null; //add major if (isset($_POST['addsubbut'])){ $selectprospectname= $strip->strip($_POST['select_prospectname']); $selectyear= $strip->strip($_POST['select_year']); $selectsem= $strip->strip($_POST['select_sem']); $selecttosubj= $strip->strip($_POST['select_tosubj']); echo '<script>alert('.selectprospectname.');</script>'; $cursubInsert = $func->insert('curri_subjtbl',array( 'currID' => $selectprospectname, 'year' => $selectyear, 'sem' => $selectsem, 'subjID' => $selecttosubj )); if(!$cursubInsert){ echo '<script>alert("Adding Failed");</script>'; } } // display table content $y = 1; $sttt = null; if ((isset($_POST['delete']))) { $mid = $_POST['mid']; //echo '<script> alert('.$totalcountrow .');</script>'; $delcourse = $func->delete('prereqtbl',array('majorID','=',$mid)); if ($delcourse){ echo '<script> alert("Record Deleted");</script>'; } else { echo '<script> alert("Delete failed");</script>'; } } $page = isset($_GET['page']) ? (int)$_GET['page'] : 1; $perPage = isset($_GET['per-page']) && $_GET['per-page'] <= 50 ? (int)$_GET['per-page'] : 10; //Positioning $start = ($page > 1) ? ($page * $perPage) - $perPage : 0; //Pages //check queries with search if ((isset($_POST['majorbut']))) { $corsname = $_POST['searchmajor']; $cours = $func->select_like('subjtbl',array('subjCode','subjTitle',$corsname)); $totalcountrow = count($cours); //echo '<script> alert('.$totalcountrow .');</script>'; $pages = ceil($totalcountrow/$perPage); $view =$func->select_likelimit('subjtbl','subjCode','ASC',$start,$perPage,array('subjCode','subjTitle',$corsname)); $majortext = $corsname; $var_str = var_export($majortext, true); $var = "<?php\n\n\$majortext = $var_str;\n\n?>"; file_put_contents('vars/'.$usern.'subjvar.php', $var); }else if ($majortext != null && (isset($_POST['sortAcroDesc'])) ) { $cours = $func->select_like('subjtbl',array('subjCode','subjTitle',$majortext)); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->select_likelimit('subjtbl','subjCode','DESC',$start,$perPage,array('subjCode','subjTitle',$majortext)); } else if ($majortext != null && (isset($_POST['sortAcroAsc']))) { $cours = $func->select_like('subjtbl',array('subjCode','subjTitle',$majortext)); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->select_likelimit('subjtbl','subjCode','ASC',$start,$perPage,array('subjCode','subjTitle',$majortext)); }else if ((isset($_POST['sortAcroDesc']))) { $cours = $func->selectallorderby('subjtbl','subjCode','DESC'); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view =$func->selectallorderbylimit('subjtbl','subjCode','DESC',$start,$perPage); } else if ((isset($_POST['sortAcroAsc']))) { $cours = $func->selectallorderby('subjtbl','subjCode','ASC'); $totalcountrow = count($cours); $pages = ceil($totalcountrow/$perPage); $view = $func->selectallorderbylimit('subjtbl','subjCode','ASC',$start,$perPage); } else { $majorunit = $func->select_distinct('curri_subjtbl',array('currID')); $totalcountrow = count($majorunit); $pages = ceil($totalcountrow/$perPage); $view = $func->select_distinctlimit('curri_subjtbl',$start,$perPage,array('currID')); } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#fff; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('prospectus').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs"> Prospectus </p> <div id="page-inner"> <div class="row" > <div class="col-lg-12 form-group"> <button type="button" class="btn btn-success" data-toggle="collapse" data-target="#addnewsubject">Add Subject to Prospectus</button> <br> <form method="POST" name="add_subject"> <div id="addnewsubject" class=" collapse"> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-3 control-label" style="text-align: right">Subject :</label> <div class="col-md-7"> <select class="form-control" name="select_tosubj"> <?php $subjlist2 = $func->selectallorderby('subjtbl','subjCode','ASC'); for($n=0;$n<count($subjlist2);$n++){ ?> <option value="<?php echo escape($subjlist2[$n]['subjID']); ?>"> <?php echo escape($subjlist2[$n]['subjCode']) . " -- " . escape($subjlist2[$n]['subjTitle']); ?></option> <?php } ?> </select> </div> </div> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-3 control-label" style="text-align: right">Prospectus Name:</label> <div class="col-md-7"> <select class="form-control" name="select_prospectname"> <?php $subjlist1 = $func->selectallorderby('curriculum','curriName','ASC'); //echo '<script> alert(' .count($subjlist1). ');</script>'; for($n=0;$n<count($subjlist1);$n++){ ?> <option value="<?php echo escape($subjlist1[$n]['currID']); ?>"> <?php echo escape($subjlist1[$n]['curriName']) ." ver. ".escape($subjlist1[$n]['version']) ; ?></option> <?php } ?> </select> </div> </div> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-3 control-label" style="text-align: right">Year Level:</label> <div class="col-md-2"> <select class="form-control" name="select_year"> <option value = "1">1st Year</option> <option value = "2">2nd Year</option> <option value = "3">3rd Year</option> <option value = "4">4th Year</option> <option value = "5">5th Year</option> </select> </div> <label class="col-md-3 control-label" style="text-align: right">Semester:</label> <div class="col-md-2"> <select class="form-control" name="select_sem"> <option value = "1">1st sem</option> <option value = "2">2nd sem</option> <!-- <option value = "3">Summer</option> --> </select> </div> </div> <div class="col-md-11"> <button type="submit" class="btn btn-md btn-info" name="addsubbut" style="float: right" >Submit</button> </div> </div> </div> </form> <!-- list --> <div class="col-lg-12"> <hr> <h3>Subject List: </h3> <div class="row" > <form method="POST"> <div class="col-md-12 form-group"> <label class="col-md-3 control-label">Search Subject Code/Title:</label> <div class="col-md-4"> <input type="text" class="form-control" placeholder="Ex: ITP 06" name="searchmajor" > </div> <div class="col-md-2"> <input type="submit" name="majorbut" value="search" class="btn btn-primary"> </div> </div> </form> </div> </div> <div class="col-lg-12"> <div class="row" > <center> <div class="table-wrapper-scroll-y my-custom-scrollbar"> <table width:1000px class="table table-hover" height:100px; overflow: scroll; > <form method="POST"> <tr style=" color:#ffffff; background-color:#0080ff;"> <td>No <br><span class="badge badge-success"><?php echo $totalcountrow; ?></span> </td> <td>Prospectus Name</td> <td >Action</td> </tr> </form> <?php if (count($view) == 0) { echo "No Post to Show"; } else { //echo '<script> alert('.count($view) .');</script>'; for($x=0;$x<count($view);$x++){ $y = ($y + 1)*$page; //echo '<script> alert('.$x .');</script>'; ?> <tr > <td> <?php if($page>1){ $pagec = (($page *10)-10) + $x +1; echo $pagec; } else { echo $x +1; } ?> </td> <td> <?php $prosp = $func->selectallorderby('curriculum','curriName','ASC'); //echo '<script> alert(' .count($subjlist1). ');</script>'; for($n=0;$n<count($prosp);$n++){ if($view[$x]['currID'] == $prosp[$n]['currID'] ){ echo escape($prosp[$n]['curriName']) ." ver. ".escape($prosp[$n]['version']) ; } } ?> </td> <form method="POST"> <input type="hidden" name="mid" value="<?php echo escape($view[$x]['prereqID']); ?>"> <td> <a href="curriculumview.php?id=<?php echo escape($view[$x]['currID']); ?> " id=".<?php echo escape($x) +1; ?>.">View details</a> <input type="submit" name="delete" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete?')"> </td> </form> </tr> <?php } } ?> </table> </center> <ul class="actions pagination"> <?php for($x = 1; $x <= $pages; $x++): ?> <li><a href="?page=<?php echo $x; ?>"<?php if($page === $x) {echo ' class="button selected"';} ?>><?php echo $x; ?></a></li> <?php endfor; ?> </ul> </div> </div> </div> </div> </div> <file_sep>/jdyn.php <?php include 'menu.php'; ?> <!DOCTYPE html> <html> <head> <script> $(document).ready(function(){ var comCount = 0 ; $("#kuhanan").change(function(){ comCount = document.getElementById("kuhanan").value; $("#comments").load("load-jdyn.php", { comNewCount: comCount }); }); }); </script> </head> <body> <div class="container-fluid"> <br> <br> <div class="row" > <?php $subjlis = $func->selectall('curriculum'); ?> <select name="kuhanan" id="kuhanan"> <?php for($n=0;$n<count($subjlis);$n++){ ?> <option value="<?php echo escape($subjlis[$n]['currID']); ?>"> <?php echo escape($subjlis[$n]['curriName']) ."ver. ".escape($subjlis[$n]['version']) ; ?></option> <?php } ?> </select> <div id="comments"> <?php $subjlist1 = $func->select_one('curri_subjtbl',array('currID','=',1)); echo "<select>"; for($n=0;$n<count($subjlist1);$n++){ echo "<option>"; echo escape($subjlist1[$n]['subjID']); echo "<option>"; } echo "</select>"; ?> </div> <button id="butbut">Show more comments</button> </div> </div> </body> </html> <file_sep>/action.js var hr = new XMLHttpRequest(); hr.open("POST", "coordwriter.php", true); // Set content type header information for sending url encoded variables in the request hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); hr.send(); // Actually execute the request<file_sep>/subjectedit.php <?php include'menu.php'; include'menuside_dash.php'; if (isset($_POST['savesubbut'])){ $subjcode= $strip->strip($_POST['subj_code']); $subjtitle= $strip->strip($_POST['subj_title']); $creditunit= $strip->strip($_POST['credit_unit']); $lecunit= $strip->strip($_POST['lec_unit']); $labunit= $strip->strip($_POST['lab_unit']); $pid=$_POST['idnya']; $courseUpdate = $func->update('subjtbl','subjID',$pid, array( 'subjCode' => $subjcode, 'subjTitle' => $subjtitle, 'subjUnit' => $creditunit, 'subjLec' => $lecunit, 'subjLab' => $labunit )); if($courseUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING MAJOR FAILED !!");</script>'; } } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#000; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('main').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs">Course </p> <div id="page-inner"> <div class="row" > <div class="col-lg-12 form-group paper"> <br> <p id="pangs" >Edit Course</p> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('subjtbl',array('subjID','=',$col)); if ($cors){ ?> <strong><a href="subject.php">Back to List</a></strong> <form method="POST" name="add_subject"> <div id="editnewsubject"> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-2 control-label" style="text-align: right">Subject Code:</label> <div class="col-md-2"> <input type="text" placeholder="Ex: ITP 06" class="form-control" name="subj_code" value="<?php echo $cors[0]['subjCode'] ?>" required> </div> <label class="col-md-2 control-label" style="text-align: right">Subject Title:</label> <div class="col-md-5"> <input type="text" placeholder="Ex: Web Development" class="form-control" name="subj_title" value="<?php echo $cors[0]['subjTitle'] ?>" required> </div> </div> <div class="col-lg-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">UNIT:</label> <label class="col-md-1 control-label" style="text-align: right">Credit:</label> <div class="col-md-2"> <input type="text" placeholder="Ex: 3" class="form-control" name="credit_unit" value="<?php echo $cors[0]['subjUnit'] ?>" required> </div> <label class="col-md-1 control-label" style="text-align: right">Lec:</label> <div class="col-md-2"> <input type="text" placeholder="Ex: 3" class="form-control" name="lec_unit" value="<?php echo $cors[0]['subjLec'] ?>" > </div> <label class="col-md-2 control-label" style="text-align: right">Lab:</label> <div class="col-md-2"> <input type="text" placeholder="Ex: 3" class="form-control" name="lab_unit" value="<?php echo $cors[0]['subjLab'] ?>"> </div> </div> <div class="col-md-11"> <input type="hidden" name = "idnya" value="<?php echo $cors[0]['subjID'] ?>"> <?php } ?> <button type="submit" class="btn btn-md btn-info" name="savesubbut" style="float: right" >Submit</button> </div> </div> </div> </form> </div> </div> </div> <file_sep>/spr.php <?php include 'menu.php'; ?> <!DOCTYPE html> <head> <script src="FileSaver.js"></script> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> .container .well{ background-color: #13D8F3; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } @media print { @page {margin: 0;} body {margin: 1.6cm;} img { max-height: 50px !important; max-width:50px !important; } } .paper { background: #fff; padding: 30px; position: relative; } .paper, .paper::before, .paper::after { /* Styles to distinguish sheets from one another */ box-shadow: 1px 1px 1px rgba(0,0,0,0.25); border: 1px solid #bbb; } .paper::before, .paper::after { content: ""; position: absolute; height: 95%; width: 99%; background-color: #eee; } .paper::before { right: 15px; top: 0; transform: rotate(-1deg); z-index: -1; } .paper::after { top: 5px; right: -5px; transform: rotate(1deg); z-index: -2; } .wrapper { height: 550px; border : 10px double green; border-radius: 5px; overflow-y: auto; background-color:white; } .papel { background: #fff; box-shadow: /* The top layer shadow */ 0 -1px 1px rgba(0,0,0,0.15), /* The second layer */ 0 -10px 0 -5px #eee, /* The second layer shadow */ 0 -10px 1px -4px rgba(0,0,0,0.15), /* The third layer */ 0 -20px 0 -10px #eee, /* The third layer shadow */ 0 -20px 1px -9px rgba(0,0,0,0.15); /* Padding for demo purposes */ padding: 30px; } a:hover { background-color: yellow; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } img#propix { max-width:100px; } H1, H5#pangs { font-family: 'Sonsie One';font-size: 25px; } H2 { font-family: 'Sonsie One';font-size: 17px; } #desss{ font-family: 'Sonsie One';font-size: 15px; } .col-lg-2 { background-color:#add8e6; height: 550px; } hr { border: 2px solid black; } .table-bordered th, .table-bordered td { padding: 15px !important; text-align: center !important; border: 1px solid #000 !important; } .table-fit { width: auto !important;; } </style> </head> <body> <div class="container-fluid"> <br> <br> <div class="row" > <div class="col-lg-1" > </div> <div class="col-lg-10" > <br> <div class="papel"> <div class="col-md-12 form-group"> <div class="col-md-1"> <a href="studlist.php" > <img src ="img/showicon.png" class="img-responsive" id="propix" name="showpropix"></img> </a> </div> <div class="col-md-3"> </div> <div class="col-md-8"> <H1>Student's Permanent Record</H1> </div> </div> <hr> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $studinfo = $func->select_one('studtbl',array('studID','=',$col)); if ($studinfo){ ?> <a href="reportstud.php?id=<?php echo $col; ?>">Back</a> <form method="POST" name="add_student"> <div class="paper"> <div class="col-md-12 form-group"> <label class="col-md-2 control-label" style="text-align: right">Student No: </label> <label class="col-md-2 control-label"><u id="desss"> <?php echo escape($studinfo[0]['studNum']) ?></u> </label> <label class="col-md-3 control-label" style="text-align: right">Student Name:</label> <label class="col-md-5 control-label"><u id="desss"><?php echo escape($studinfo[0]['lName']).", ". escape($studinfo[0]['fName']) ." ". escape($studinfo[0]['mName']); ?></u> </label> </div> </div> <div class="row" > <div class="col-lg-12" > <h3>Academic Status</h3> <div class="col-lg-12 form-group"> <div id="printarea"> <div class="col-lg-12 form-group"> <div class="row" > <?php for($j=1;$j<=5;$j++){ $reginfo = $func->select_logic('registrationtbl',array('studID','=',$col),'AND',array('regYrlevel','=',$j)); echo'<div class="col-md-12 form-group">'; echo"<p>"; if ($reginfo[0]['regYrlevel'] == 1){ echo "1st Year ";} else if ($reginfo[0]['regYrlevel'] == 2){ echo "2nd Year ";} else if ($reginfo[0]['regYrlevel'] == 3){ echo "3rd Year ";} else if ($reginfo[0]['regYrlevel'] == 4){ echo "4th Year ";} else if ($reginfo[0]['regYrlevel'] == 5){ echo "5th Year ";} echo"</p>"; for($k=1;$k<=4;$k++){ $reginfo = $func->select_logics2('registrationtbl',array('studID','=',$col),'AND',array('regYrlevel','=',$j),'AND',array('regSem','=',$k)); echo '<div class="col-md-5">'; echo"<p>"; if ($reginfo[0]['regSem'] == 1){ echo "1st Semester ";} else if ($reginfo[0]['regSem'] == 2){ echo "2nd Semester ";} else if ($reginfo[0]['regSem'] == 3){ echo "Summer ";} else if ($reginfo[0]['regSem'] == 4){ echo "Midyear ";} echo"</p>"; $gradenya = $func->select_one('gradetbl',array('regID','=',$reginfo[0]['regID'])); if(count($gradenya) != 0){ //start if ?> <div class="table-responsive"> <table border=1 class="table table-fit" style="text-align: center"> <tr> <th>Subject</th> <th>Rating</th> <th>Re Exam</th> <th>Credit</th> </tr> <?php for($f=0; $f<count($gradenya);$f++): ?> <tr> <td><?php $pangsubj = $func->select_one('subjtbl',array('subjID','=',$gradenya[$f]['subjID'])); echo escape($pangsubj[0]['subjCode']); ?></td> <td><?php if($reginfo[0]['regResidency'] == 1){ echo "X"; } else{ if($gradenya[$f]['rating']> 0){ echo escape($gradenya[$f]['rating']); } else { echo " "; } } ?></td> <td><?php if($reginfo[0]['regResidency'] == 1){ echo "X"; } else{ if($gradenya[$f]['rexam']> 0){ echo escape($gradenya[$f]['rexam']); } else { echo " "; } } ?></td> <td><?php if($reginfo[0]['regResidency'] == 1){ echo " "; } else{ if($pangsubj[0]['subjUnit'] < 0){ echo "(" .$pangsubj[0]['subjUnit'] * -1 .")" ; } else { echo escape($pangsubj[0]['subjUnit']); } } ?></td> </tr> <?php endfor; ?> </table> </div> <?php } //end if echo'</div>'; } echo'</div>'; }?> </div> <!--end of print area --> </div> <button type="submit" class="btn btn-success" name="printdata" onclick="printDiv('printarea')">Print Form</button> </div> </form> </div> <hr> <!-- registration list --> <div> <a class="word-export" href="javascript:void(0)" onclick="ExportToDoc()">Export to Doc</a> </div> <?php } ?> </div> </div> </div> </div> </div> </div> </div> <br> <br> <br> <script> document.getElementById('ownerlist').className = "active-link"; $("link[rel*='icon']").attr("href", "img/logo.png"); function printDiv(divName) { var printContents = document.getElementById(divName).innerHTML; var originalContents = document.body.innerHTML; document.body.innerHTML = printContents; window.print(); document.body.innerHTML = originalContents; } </script> <script type="text/javascript"> function ExportToDoc(filename = ''){ var HtmlHead = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:w='urn:schemas-microsoft-com:office:word' ><head><meta charset='utf-8'><title>Export HTML To Doc</title></head><body>"; var EndHtml = "</body></html>"; //complete html var html = HtmlHead +document.getElementById("printarea").innerHTML+EndHtml; //specify the types var blob = new Blob(['\ufeff', html], { type: 'application/msword' }); // Specify link url var url = 'data:application/vnd.ms-word;charset=utf-8,' + encodeURIComponent(html); // Specify file name filename = filename?filename+'.doc':'document.doc'; // Create download link element var downloadLink = document.createElement("a"); document.body.appendChild(downloadLink); if(navigator.msSaveOrOpenBlob ){ navigator.msSaveOrOpenBlob(blob, filename); }else{ // Create a link to the file downloadLink.href = url; // Setting the file name downloadLink.download = filename; //triggering the function downloadLink.click(); } document.body.removeChild(downloadLink); } </script> </body> <file_sep>/lib/script_blank.js //JS ang Leaflet stuff //Variables var mapSW = [0,4096], mapNE = [4096,0]; //Declare Map Object var map = L.map('mapid').setView([0, 0], 2); //Reference the tiles L.tileLayer('bhay/{z}/{x}/{y}.png', { minZoom: 0, maxZoom: 4, continuousWorld: false, noWrap: true, crs: L.CRS.Simple, attribution: 'Map data &copy; ', }).addTo(map); map.setMaxBounds(new L.LatLngBounds( map.unproject(mapSW,map.getMaxZoom()), map.unproject(mapNE,map.getMaxZoom()) )); //Add some GeoJSON<file_sep>/menu.php <?php $usern = null; ?> <!DOCTYPE html> <html style = "height: 100%; margin: 0;" lang="en"> <head> <link rel="icon" href="img/papayalogo.png" type="image/*" sizes="16x16"> <title>NEUST OCP Grade Management System</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css"> <script src="lib/bootstrap/js/jquery-3.2.1.js"></script> <script src="lib/bootstrap/js/bootstrap.min.js"></script> <link href="lib/assets/css/font-awesome.css" rel="stylesheet" /> <!-- CUSTOM STYLES--> <link href="lib/assets/css/custom.css" rel="stylesheet" /> <!--Leaflet basic--> <link rel="stylesheet" href="lib/leaflet/leaflet.css" /> <script src="lib/leaflet/leaflet.js"/></script> <!--Ckeditor--> <script src="cdn/ckeditor_4.6.2_standard/ckeditor/ckeditor.js"/></script> <!--css style--> <style type="text/css"> #mapid { height:100%; width:100%; background:#888888; } .navbar { color: #FFFFFF; background-color: #0080ff; } </style> </head> <?php session_start(); include 'core/init.php'; error_reporting(0); //anti - Full Path Disclosure ?> <center><div id="menu"> <?php if(empty($_SESSION['userid'])){ ?> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <ul class="nav navbar-nav navbar-right"> <li ><H1> NEUST PAPAYA OFF CAMPUS GRADE MANAGEMENT SYSTEM </H1> </li> </ul> <a class="navbar-brand" rel="home"> <img style="max-width:135px; margin-top: -2px;" src="img/headpay.png"> </a> </div> <div class="navbar-header " style="float:left;"></div> </nav> <?php header('location:index.php'); } else { $useracc = $func->select_one('userstbl',array('userID','=',$_SESSION['userid'])); if($useracc[0]['permission'] >= 1){ $perid = $useracc[0]['staffID']; $_SESSION['peracc'] = $perid; $peracc = $func->select_one('stafftbl',array('staffID','=',$perid)); ?> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" rel="home" href="index.php"> <img style="max-width:120px; margin-top: -7px;" src="img/headpay.png"> </a> </div> <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> <li class="act" id="studlist" ><a href="studlist.php" >Student List</a></li> <li class="act" id="account" ><a href="account.php" >Accounts</a></li> <li class="act" id="dash"><a href="dashboard.php" >Dashboard </a> </li> <?php if($useracc[0]['permission'] >= 2){?> <li class="a" id="bor"><a href="neighbormap.php" >Community Map</a></li> <li class="act" id="gallery"><a href="multialbum_gallery.php" >Gallery</a></li> <?php } if($useracc[0]['permission'] == 3){ ?> <li class="act" id="contact"><a href="contactus.php" >Contact Us</a></li> <li class="act" id="faq"><a href="faq.php" >FAQ</a></li> <?php }?> </ul> <ul class="nav navbar-nav navbar-right"> <li class="act" id="signuplog"><a href="logout.php"><span class="glyphicon glyphicon-log-out"></span> <?php echo $peracc[0]['firstName']; ?> Log out</a></li> </ul> </div> </div> </nav> <?php $usern = $peracc[0]['firstName'] . $peracc[0]['cpnum']; $staffid = $peracc[0]['staffID']; } } ?> </div></center> <file_sep>/cor_print.php <?php include 'core/init.php'; require('fpdf17/fpdf.php'); //A4 width: 219mm //default margin : 10 mm each side //writable horizontal: 219 (10 *2) = 189mm class PDF extends FPDF { function Header(){ $this-> SetFont('Arial','B',13); $this->Ln(5); $this->Ln(5); $this->Cell(35); $this->Image("img/NEUST-LOGO.png",15,20,20); $this->Cell(100,5,'NUEVA ECIJA UNIVERSITY OF SCIENCE AND TECHNOLOGY',0,0,'C'); $this->Cell(35); $this->Image("img/gentiniologo.png",175,20,20); $this->Cell(35); $this->Cell(100,5,'GENERAL TINIO (PAPAYA) OFF-CAMPUS',0,1,'C'); $this->Cell(35); $this-> SetFont('Arial','B',12); $this->Cell(100,5,'Brgy. Concepcion, General Tinio (Papaya), Nueva Ecija',0,1,'C'); $this->Cell(35); $this->Cell(100,5,'OFFICE OF THE REGISTRAR',0,1,'C'); $this->Ln(5); $this->Ln(5); $this-> SetFont('Arial','U',15); $this->Cell(169,5,'CERTIFICATE OF GRADES',0,1,'C'); $this->Ln(5); $this->Ln(5); $this->Ln(5); $this->Ln(5); } } $image1 = "img/NEUST-LOGO.png"; $pdf = new PDF('P','mm','A4'); $pdf->SetMargins(20, 10); $pdf->AddPage(); //set font to arial, bold, 14pt $pdf->SetFont('Arial','',11); //Cell(width, height, text,border, end line, [align]) if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } if (isset($_GET['stf'])) { $stf = (get_magic_quotes_gpc()) ? $_GET['stf'] : addslashes($_GET['stf']); } $cors = $func->select_one('registrationtbl',array('regID','=',$col)); $pangalannya = $func->select_one('studtbl',array('studID','=',$cors[0]['studID'])); $gender = ""; if($pangalannya[0]['gender'] == 1){ $gender = "MR. ";} else{$gender = "MS. "; } $angang = $func->select_one('curriculum',array('currID','=',$cors[0]['currID'])); $angcoursemajor = $func->selectjoin_where('coursetbl','majortbl','courseID','courseID','majortbl',array('majorID','=',$angang[0]['majorID'])); $textnya = " This is to certifies that according to the records in this university, ". $gender. strtoupper($pangalannya[0]['fName'])." ".strtoupper($pangalannya[0]['mName'])." ". strtoupper($pangalannya[0]['lName'])." ". "was officially enrolled under the program ". $angcoursemajor[0]['courseTitle']." (". $angcoursemajor[0]['majorName'] .") ". "and has obtained the following grades for:"; $cellWidth=169; $cellHeight=5; //check whether overflowing if($pdf->GetStringWidth($textnya) <$cellWidth){ $line=1; } else{ $textLength = strlen($textnya); $errMargin=20; $startChar=0; $maxChar=0; $textArray=array(); $tmpString=""; while($startChar < $textLength){ while( $pdf->GetStringWidth($tmpString) < ($cellWidth - $errMargin) && ($startChar + $maxChar) < $textLength ){ $maxChar++; $tmpString=substr($textnya, $startChar,$maxChar); } $startChar=$startChar+$maxChar; array_push($textArray,$tmpString); $maxChar = 0; $tmpString =""; } $line=count($textArray); } $xPos = $pdf->GetX(); $YPos = $pdf->GetY(); $pdf->MultiCell($cellWidth,$cellHeight,$textnya,0); $pdf->SetXY($xPos + $cellWidth, $YPos); $pdf->Cell(1,($line * $cellHeight),"",0,1); $pdf->Cell(169,5,"",0,1); $yrlevel = ""; $semlevel = ""; $acadhead = ""; if ($cors[0]['regYrlevel'] == 1){ $yrlevel = "1st Year "; } else if ($cors[0]['regYrlevel'] == 2){ $yrlevel = "2nd Year "; } else if ($cors[0]['regYrlevel'] == 3){ $yrlevel = "3rd Year "; } else if ($cors[0]['regYrlevel'] == 4){ $yrlevel = "4th Year "; } else if ($cors[0]['regYrlevel'] == 5){ $yrlevel = "5th Year "; } if ($cors[0]['regSem'] == 1){ $semlevel = "1st Semester "; } else if ($cors[0]['regSem'] == 2){ $semlevel = "2nd Semester "; } else if ($cors[0]['regSem'] == 3){ $semlevel = "Summer ";} else if ($cors[0]['regSem'] == 4){ $semlevel = "Midyear "; } $acadhead = $yrlevel . $semlevel ."A.Y. ". $cors[0]['regAcadYr']; $pdf->Ln(5); $pdf->SetFont('Arial','B',11); $pdf->Cell(169,5,$acadhead,0,1,'C'); $pdf->Ln(5); $pdf->Cell(25,5,'Subj. Code',1,0,'C'); $pdf->Cell(89,5,'Descriptive Title',1,0,'C'); $pdf->Cell(15,5,'Units',1,0,'C'); $pdf->Cell(18,5,'Grades',1,0,'C'); $pdf->Cell(22,5,'Remarks',1,1,'C'); $selectenrollsub = $func->select_one('gradetbl',array('regID','=',$cors[0]['regID'])); $pdf->SetFont('Arial','',10); $talunits= 0; for($t=0;$t<count($selectenrollsub);$t++){ $subjlist41 = $func->select_one('subjtbl',array('subjID','=',$selectenrollsub[$t]['subjID'])); $pdf->Cell(25,5,$subjlist41[0]['subjCode'],1,0,'C'); $pdf->Cell(89,5,$subjlist41[0]['subjTitle'],1,0,'C'); $subjunit = ""; if($subjlist41[0]['subjUnit'] == 0){ $subjunit = ""; $talunits = $talunits; } else if($subjlist41[0]['subjUnit']<= 0){ $talunits = $talunits + 0; $subjunit = '(' .$subjlist41[0]['subjUnit'] * -1 .')'; } else{ $subjunit = $subjlist41[0]['subjUnit']; $talunits = $talunits + $subjunit; } $pdf->Cell(15,5,$subjunit,1,0,'C'); $raty = ""; if ($selectenrollsub[$t]['rating'] == 0){ $raty = ""; } else { $raty = $selectenrollsub[$t]['rating']; } $pdf->Cell(18,5,$raty,1,0,'C'); $remarka = ""; if($selectenrollsub[$t]['remarks'] == 1){ $remarka = "Passed"; }else if($selectenrollsub[$t]['remarks'] == 0){ $remarka = "Failed"; } $pdf->Cell(22,5,$remarka,1,1,'C'); } $pdf->Cell(25,5,"",1,0,'C'); $pdf->Cell(89,5,'X------------------X',1,0,'C'); $pdf->Cell(15,5,$talunits,1,0,'C'); $pdf->Cell(18,5,'',1,0,'C'); $pdf->Cell(22,5,'',1,1,'C'); $pdf->Ln(5); $curday =""; $currentDay = date('d'); if($currentDay == 1){ $curday = "1st "; } else if($currentDay == 2){ $curday = "2nd "; } else if($currentDay == 3){ $curday = "3rd "; } else{ $curday = $currentDay ."th "; } $textnya = " This is certification is issued this " .$curday. " day of " .date('F Y'). " upon the request of the above-named person for references purposes."; if($pdf->GetStringWidth($textnya) <$cellWidth){ $line=1; } else{ $textLength = strlen($textnya); $errMargin=20; $startChar=0; $maxChar=0; $textArray=array(); $tmpString=""; while($startChar < $textLength){ while( $pdf->GetStringWidth($tmpString) < ($cellWidth - $errMargin) && ($startChar + $maxChar) < $textLength ){ $maxChar++; $tmpString=substr($textnya, $startChar,$maxChar); } $startChar=$startChar+$maxChar; array_push($textArray,$tmpString); $maxChar = 0; $tmpString =""; } $line=count($textArray); } $xPos = $pdf->GetX(); $YPos = $pdf->GetY(); $pdf->MultiCell($cellWidth,$cellHeight,$textnya,0); $pdf->SetXY($xPos + $cellWidth, $YPos); $pdf->Cell(1,($line * $cellHeight),"",0,1); $pdf->Cell(169,5,"",0,1); $pdf->Ln(5); $pdf->Cell(169,5," Prepared by:",0,1); $pdf->Cell(25,5,"",0,0,'C'); $pdf->Ln(5); $pdf->Ln(5); $pdf->Cell(25,5,"",0,0,'C'); $staffko = $func->select_one('stafftbl',array('staffID','=',$stf)); $thestaff = strtoupper(escape($staffko[0]['firstName'])." ". substr(escape($staffko[0]['midName']),0,1) .". ".escape($staffko[0]['lastName'])) ; $pdf->SetFont('Arial','U',12); $pdf->Cell(40,5,$thestaff,0,1,'C'); $pdf->Cell(25,5,"",0,0,'C'); $pdf->SetFont('Arial','',11); $pdf->Cell(40,5,'Clerk',0,0,'C'); $pdf->Cell(80,5,'Check and Verified by:',0,0,'R'); $pdf->Ln(5); $pdf->Ln(5); $pdf->Ln(5); $pdf->SetFont('Arial','U',12); $pdf->Cell(120,5,'',0,0,'R'); $pdf->Cell(40,5,'<NAME>',0,1,'C'); $pdf->Cell(120,5,'',0,0,'R'); $pdf->SetFont('Arial','',12); $pdf->Cell(40,5,'Campus Registrar',0,1,'C'); $pdf->Output(); ?><file_sep>/mena.php <!DOCTYPE html> <html style = "height: 100%; margin: 0;" lang="en"> <head> <link rel="icon" href="img/papayalogo.png" type="image/*" sizes="16x16"> <title>NEUST OCP Grading Management System</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css"> <script src="lib/bootstrap/js/jquery-3.2.1.js"></script> <script src="lib/bootstrap/js/bootstrap.min.js"></script> <link href="lib/assets/css/font-awesome.css" rel="stylesheet" /> <!-- CUSTOM STYLES--> <link href="lib/assets/css/custom.css" rel="stylesheet" /> <!--Ckeditor--> <script src="cdn/ckeditor_4.6.2_standard/ckeditor/ckeditor.js"/></script> <!--css style--> <style type="text/css"> #mapid { height:100%; width:100%; background:#888888; } .navbar { color: #FFFFFF; background-color: #0080ff; } </style> </head> <?php session_start(); include 'core/init.php'; error_reporting(0); //anti - Full Path Disclosure ?> <center><div id="mena"> <nav class="navbar navbar-inverse navbar-fixed-top"> <div class="container-fluid"> <div class="navbar-header"> <ul class="nav navbar-nav navbar-right"> <li ><H1> NEUST PAPAYA OFF CAMPUS GRADE MANAGEMENT SYSTEM </H1> </li> </ul> <a class="navbar-brand" rel="home"> <img style="max-width:135px; margin-top: -2px;" src="img/headpay.png"> </a> </div> <div class="navbar-header " style="float:left;"></div> </nav> </div></center> <file_sep>/register1.php <?php include'menu.php'; $warn = null; $validity = 2; $status = null; $loginstatus = null; //Login if(isset($_POST['g-recaptcha-response']) && $_POST['g-recaptcha-response']){ // var_dump($_POST); $secret = "<KEY>"; $captcha = $_POST['g-recaptcha-response']; $ip = $_SERVER['REMOTE_ADDR']; $rsp =file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$captcha&remotepip$ip"); var_dump($rsp); $arr = json_decode($rsp,TRUE); if($arr['success']){ $validity = 1; echo 'DOne'; } else { $validity = 2; echo 'spam'; } } if (!isset($_SESSION["attempts"])) $_SESSION["attempts"] = 0; if(isset($_POST['login']) ){ $login_email = $strip->strip($_POST['login_email']); $login_password = md5($strip->strip($_POST['login_password'])); $loginstatus = $_SESSION["attempts"]; if ($_SESSION["attempts"] < 2) { $userl = $func->select_logic('users',array('username','=',$login_email),'AND',array('password','=',$login_password)); if (count($userl)==1){ $_SESSION['userid'] = $userl[0]['user_id']; $_SESSION['permission'] = $userl[0]['permission']; $permit = $_SESSION['permission']; if ($permit == 1){ header('location:myaccount.php'); } else if ($permit == 2){ header('location:dashboard.php'); } else { header('location:index.php'); } } else { $_SESSION["attempts"] = $_SESSION["attempts"] + 1; $loginstatus = $_SESSION["attempts"] . " try(ies)"; } } else { $loginstatus = "You've failed too many times, dude. Try again after 30 mins"; $_SESSION['locked'] = 'locked'; $_SESSION['timeup'] = time(); } } //signup for members if (isset($_POST['signup'])){ $reg_fname= $strip->strip($_POST['reg_fname']); $reg_lname= $strip->strip($_POST['reg_lname']); $reg_midname= $strip->strip($_POST['reg_midname']); $reg_address= $strip->strip($_POST['reg_address']); $reg_bday= $strip->strip($_POST['reg_bday']); $reg_cpno= $strip->strip($_POST['reg_cpno']); $reg_gender= $strip->strip($_POST['reg_gender']); $reg_email1= $strip->strip($_POST['reg_email1']); $reg_email2= $strip->strip($_POST['reg_email2']); $reg_password1= $strip->strip($_POST['reg_password1']); $reg_password2= $strip->strip($_POST['reg_password2']); $ref_fname= $strip->strip($_POST['ref_fname']); $ref_lname= $strip->strip($_POST['ref_lname']); //checking if reference person is in the person table $selectUser = $func->select_one('users',array('username','=',$reg_email1)); if($selectUser){ $warn ="Username already Taken"; } else { //checking if reference person is in the person table $selectperson = $func->select_logic('person',array('firstname','=',$ref_fname),'AND',array('lastname','=',$ref_lname)); if($selectperson && $validity == 1){ $refemail = $selectperson[0]['email']; $pid = $selectperson[0]['person_id']; //checking if the id is in mngt list $member = $func->select_one('mngt_memberslist',array('pid','=',$pid)); if ($member ) { //creates code $magicword = chr(mt_rand(97, 122)). substr(md5(str_shuffle(time() . rand(0, 999999))), 1); $magicword = substr($magicword,10,8); //mail credentials $subject = 'VERIFICATION CODE'; $message = "Your verification Code is ".$magicword ." Verify " ."<a href='http://ireneaestate.x10host.com/verify.php'>Here</a>"; //send codes to email mail($refemail, $subject, $message); //set registration info into cookies setcookie("regfname", $reg_fname, time() + 3600); setcookie("reglname", $reg_lname, time() + 3600); setcookie("regaddress", $reg_address, time() + 3600); setcookie("regbday", $reg_bday, time() + 3600); setcookie("regcpno", $reg_cpno, time() + 3600); setcookie("reggender", $reg_gender, time() + 3600); setcookie("regemail", $reg_email1, time() + 3600); setcookie("regpassword", md5($<PASSWORD>1), time() + 3600); setcookie("refid", $pid, time() + 3600); setcookie("magicword", $magicword, time() + 3600); header('location:verify.php'); } else { echo '<script>alert("Sorry! Your Reference Person is not in our list");</script>'; } } else{ echo '<script>alert("Sorry! Your Reference Person is not in our list");</script>'; } } } $expireAfter =2; if(isset($_SESSION['timeup'])){ //Figure out how many seconds have passed //since the user was last active. $secondsInactive = time() - $_SESSION['timeup']; //Convert our minutes into seconds. $expireAfterSeconds = $expireAfter * 60; //Check to see if they have been inactive for too long. if($secondsInactive >= $expireAfterSeconds){ //User has been inactive for too long. //Kill their session. session_unset(); session_destroy(); } header("Refresh: 120;url='register.php'"); } ?> <!DOCTYPE html> <head> <title>Registration</title> <style> .container .well{ background-color: #0080ff; /*border-bottom : 2px groove black; height: 100px;*/ } .container .row .well{ background-color: #F5F9F9; /*border-bottom : 2px groove black; height: 100px;*/ } h1{ color:white; } p#warn{ color:red; font-weight:600; } </style> <script src='https://www.google.com/recaptcha/api.js'></script> </head> <body> <script> document.getElementById('signuplog').className = "active"; </script> <br> <br> <br> <div class="container"> <div class="col-lg-5"> <div class="well well-lg"> <?php if(isset($_SESSION['locked']) ) { ?> <H1><?php echo $loginstatus; ?></H1> <?php } else { ?> <form method="POST" action=""> <div class="form-group"> <p><?php echo $loginstatus; ?> </p> <H1>Log In</H1> </div> <div class="form-group"> <input type="email" placeholder="Enter Email Address Here.." class="form-control" name="login_email"> </div> <div class="form-group"> <input type="password" placeholder="Enter Password Here.." class="form-control" name="login_password"> </div> <button type="submit" class="btn btn-lg btn-info" name="login">Login</button> </form> <?php } ?> </div> <div class="jumbotron"> <H2>Enjoy Your Priviledges!!</H2> <blockquote> <p>If you are a bonafide resident of Irenea Subdivision. This is for you! With your account you can enjoy more feautures of the website has to offer such as know your neighbors and more.</p> </blockquote> </div> </div> <div class="col-lg-1"> </div> <div class="col-lg-6 well"> <H1>Sign Up</H1> <div class="row"> <form method="POST" name="register" onSubmit="return formValidation();"> <div class="paper"> <p id="warn"><?php echo $warn; ?></p> <div class="form-group"> <label>First Name</label> <input type="text" placeholder="Enter First Name Here.." class="form-control" name="reg_fname" required> </div> <div class="form-group"> <label>Middle Name</label> <input type="text" placeholder="Enter Middle Name Here.." class="form-control" name="reg_midname" required> </div> <div class="form-group"> <label>Last Name</label> <input type="text" placeholder="Enter Last Name Here.." class="form-control" name="reg_lname" required> </div> <div class="form-group"> <label>Address</label> <input type="text" placeholder="Enter Address Here.." rows="3" class="form-control" name="reg_address" required> </div> <div class="form-group"> <label>Gender :</label> <label class="radio-inline"> <input type="radio" name="reg_gender" value="Male" checked="checked">Male </label> <label class="radio-inline"> <input type="radio" name="reg_gender" value="Female">Female </label> </div> <div class="row"> <div class="col-sm-6 form-group"> <label>Birthday</label> <input type="date" placeholder="Enter City Name Here.." class="form-control" name="reg_bday" required> </div> <div class="col-sm-6 form-group"> <label>Cellphone No.</label> <input type="number" placeholder="09XXXXXXXXX" class="form-control" max="99999999999" name="reg_cpno" required> </div> </div> <div class="form-group"> <label>Email Address</label> <input type="email" placeholder="Enter Email Address Here.." class="form-control" name="reg_email1" required> </div> <div class="form-group"> <label>Verify Email Address</label> <input type="email" placeholder="Verify Email Address Here.." class="form-control" name="reg_email2" required> </div> <div class="form-group"> <label>Password</label> <input type="password" placeholder="Minimum of 8 characters, First character must be letter" class="form-control" name="reg_password1" required> </div> <div class="form-group"> <label>Verify Password</label> <input type="password" placeholder="Verify Password Here.." class="form-control" name="reg_password2" required> </div> </div> <div class="paper2"> <hr> <div class="form-group"> <label>REFERENCE PERSON INFO:</label> <p class="bg-info">Enters the info about the unit owner to verify your legitimacy. We will send verification code to your reference's email address.</p> </div> <div class="row"> <div class="col-sm-6 form-group"> <label>First Name</label> <input type="text" placeholder="Enter First Name Here.." class="form-control" name="ref_fname" required> </div> <div class="col-sm-6 form-group"> <label>Last Name</label> <input type="text" placeholder="Enter Last Name Here.." class="form-control" name="ref_lname" required> </div> </div> <div class="g-recaptcha" data-sitekey="<KEY>"></div> <button type="submit" class="btn btn-lg btn-info"name="signup" >Sign Up</button> </div> </form> </div> </div> </div> <script> function formValidation() { var email1 = document.register.reg_email1.value; var email2 = document.register.reg_email2.value; var pass1 = document.register.reg_password1; var pass2 = document.register.reg_password2; var passlen = pass1.value.length; var passval = pass1.value; var passval2 = pass2.value; if (samelike(email1,email2,'EMAILS')){ if (samelike(passval,passval2,'PASSWORD')){ if(passlength(passlen)){ if(alphanumeric(passval)){ return true; } } } } return false; } function samelike(formelem1,formelem2,textvalue){ if(formelem1 == formelem2){ return true; } else { alert(textvalue + " did not match"); return false; } } function passlength(pass){ if(pass < 8){ alert("Password must be minimum of 8 characters"); return false; } else { return true; } } function alphanumeric(uadd) { var letters = new RegExp('^[a-zA-Z]{1}[0-9a-zA-Z]+$'); if(uadd.match(letters)) { return true; } else { alert('Password must start with a letter'); uadd.focus(); return false; } } </script> </body><file_sep>/dashboardedit.php <?php include'menu.php'; include'menuside_dash.php'; if (isset($_POST['savecoursebut'])){ $coursetitle=$_POST['course_title']; $courseacro=$_POST['course_acro']; $coursedept=$_POST['course_dept']; $pid=$_POST['idnya']; $courseUpdate = $func->update('coursetbl','courseID',$pid, array( 'courseAcro' => $courseacro, 'courseTitle' => $coursetitle, 'courseDept' => $coursedept )); if($courseUpdate){ echo '<script>alert("Succeed");</script>'; } else { echo '<script>alert("EDITING COURSE FAILED !!");</script>'; } } ?> <link href='https://fonts.googleapis.com/css?family=Sonsie One' rel='stylesheet'> <style> div#test { background-color:#0080ff; border-color:black;} div#test > div> img { height: 200px; width: 200px; cursor:pointer; } .profile-pic { position: relative; display: inline-block; } .profile-pic:hover .edit { display: block; } .edit { padding-top: 7px; padding-right: 7px; position: absolute; right: 0; top: 0; display: none; } .edit a { color: #000; } #page-wrapper { padding: 15px 15px; min-height: 800px; background:#0080ff; } #page-inner { width:95%; margin:10px 20px 10px 20px; background-color:#fff!important; padding:10px; min-height:800px; } .myDiv { border: 5px outset blue; } #pangs{ font-family: 'Sonsie One'; font-size: 25px; color:#000; } .panel-title{ font-family: 'Sonsie One'; color:red; font-size: 20px; } .row{ margin:10px 20px 10px 30px; } .form-control { color: black; } } </style> <script> document.getElementById('main').className = "active-link"; </script> <!-- /. NAV SIDE --> <div id="page-wrapper"> <p id="pangs">Course </p> <div id="page-inner"> <div class="row" > <div class="col-lg-11 form-group paper"> <br> <p id="pangs" >Edit Course</p> <?php //for edit $col = "-1"; if (isset($_GET['id'])) { $col = (get_magic_quotes_gpc()) ? $_GET['id'] : addslashes($_GET['id']); } $cors = $func->select_one('coursetbl',array('courseID','=',$col)); if ($cors){ ?> <strong><a href="dashboard.php">Back to List</a></strong> <form method="POST" name="add_course"> <div id="editcourse"> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-2 control-label">Course Title</label> <div class="col-md-8"> <input type="text" placeholder="Ex: B.S. Information Technology" class="form-control" name="course_title" value="<?php echo $cors[0]['courseTitle'] ?>" required> <br> </div> <div class="col-lg-12 form-group"> <label class="col-md-1 control-label"></label> <label class="col-md-2 control-label">Acronym:</label> <div class="col-md-3"> <input type="text" placeholder="Ex: BSIT" class="form-control" name="course_acro" value="<?php echo $cors[0]['courseAcro'] ?>" required> </div> <label class="col-md-2 control-label">Department:</label> <div class="col-md-3"> <input type="text" placeholder="Ex: CICT" class="form-control" name="course_dept" value="<?php echo $cors[0]['courseDept'] ?>" required> </div> </div> <input type="hidden" name = "idnya" value="<?php echo $cors[0]['courseID'] ?>"> <?php } ?> <button type="submit" class="btn btn-md btn-info" name="savecoursebut" style="float:right">Save</button> </div> </div> </div> </form> </div> </div> </div>
ab07af7c7136cd38991e32b882107f7e81f304b8
[ "JavaScript", "SQL", "PHP" ]
40
PHP
skylar04yue/gmsdev
42f120d4071d405373eaacb976842073a438e41c
8e4bf76f66f4d11de3bf86605f452f0483d175b0
refs/heads/master
<repo_name>basestart/drag<file_sep>/src/Drag.js import React, { Component } from 'react'; import Draggable from 'react-draggable'; export default class Drag extends Component { componentDidMount () { this.flag = false; //是否按下鼠标的标记 this.cur = { //记录鼠标按下时的坐标 x:0, y:0 } Object.assign(this, { nx: 0, ny: 0 }); this.div2 = this.refs.box; document.addEventListener("touchmove",function(event){ event.preventDefault(); },false); } down (event){ this.flag = true; var touch ; if(event.touches){ touch = event.touches[0]; }else { touch = event; } //确认鼠标按下 this.cur.x = touch.clientX; //记录当前鼠标的x坐标 this.cur.y = touch.clientY; //记录当前鼠标的y坐标 let {offsetLeft, offsetTop, offsetWidth, offsetHeight} = touch.target; this.center = [offsetLeft + offsetWidth / 2, offsetTop + offsetHeight / 2]; } move (event) { if(this.flag){ var touch ; if(event.touches){ touch = event.touches[0]; }else { touch = event; } this.nx = touch.clientX - this.cur.x; this.ny = touch.clientY - this.cur.y; let {offsetLeft, offsetTop, offsetWidth, offsetHeight} = touch.target; this.center = [offsetLeft + this.nx + offsetWidth / 2, offsetTop + this.ny + offsetHeight / 2]; this.div2.style.transform = `translate(${this.nx}px, ${this.ny}px)`; } } //鼠标释放时候的函数 end(){ console.log(this.center) let {end} = this.props; let res = end(this.props.id, this.center); this.div2.style.transform = `translate(0px, 0px)` this.flag = false; } render () { return <div onMouseDown={this.down.bind(this)} onTouchStart={this.down.bind(this)} onMouseMove={this.move.bind(this)} onTouchMove={this.move.bind(this)} onMouseUp={this.end.bind(this)} onTouchEnd={this.end.bind(this)} ref="box" style={{height:"200px", width: "200px", border: "1px solid red", borderRadius: "100px"}} ></div> } } <file_sep>/src/Drop.js import React, { Component } from 'react'; export default class Drag extends Component { componentDidMount () { this.sendCenter(); } handleOver(e) { console.log(e); } sendCenter () { let {sendCenter, id} = this.props; let {tar} = this.refs; let {offsetLeft, offsetTop, offsetWidth, offsetHeight} = tar; let center = [offsetLeft + offsetWidth / 2, offsetTop + offsetHeight / 2]; // debugger; sendCenter(id, center); console.log(tar) } render () { return <div ref="tar" onMouseOver={this.handleOver.bind(this)} style={{height:"200px", width: "200px", border: "1px solid red", borderRadius: "100px"}} ></div> } }
814cb922d98e5e6d214494ca118f6f0070e6088a
[ "JavaScript" ]
2
JavaScript
basestart/drag
8060879c860128fa2ea82747f40457aa2e4cce50
f82d0862211cb112fc524ec8f0305679db916a53
refs/heads/master
<repo_name>Masagis/learn-erd-restful-API<file_sep>/index.js const express = require('express') let pemilih = require('./db/pemilih.json') let calon = require('./db/kandidat.json') let hasil = require('./db/hasil.json') const app = express() app.use(express.json()) app.use(express.urlencoded({ extended: true })) app.get('/api/v1/pemilih', (req, res) => { res.status(200).json(pemilih) }) app.get('/api/v1/pemilih/:id', (req, res) => { const terpilih = pemilih.find(i => i.id == +req.params.id) res.status(200).json(terpilih) }) app.post('/api/v1/pemilih', (req, res) => { console.log(req.body) const { nim, nama_mhs, prodi, vote_who, keterangan } = req.body const id = pemilih[pemilih.length - 1].id + 1 const terpilih = { id, nim, nama_mhs, prodi, vote_who, keterangan } pemilih.push(terpilih) res.status(201).json(pemilih) }) app.get('/api/v1/calon', (req, res) => { res.status(200).json(calon) }) app.get('/api/v1/calon/:id', (req, res) => { const kandidat = calon.find(i => i.id == +req.params.id) res.status(200).json(kandidat) }) app.get('/api/v1/hasil', (req, res) => { res.status(200).json(hasil) }) app.get('/api/v1/hasil/:id', (req, res) => { const result = hasil.find(i => i.id == +req.params.id) res.status(200).json(result) }) app.listen(3000, () => { console.log('Server ready') })
686a9d6b265818a09939c665e77786c7b4b1f74e
[ "JavaScript" ]
1
JavaScript
Masagis/learn-erd-restful-API
7b591c4686dd1295b47d8bd838b2476493fd75ff
91d7312b08c0d62dca2a0ce69511c1b1ce9cd948
refs/heads/master
<repo_name>YYChen01988/Hash_Map<file_sep>/settings.gradle rootProject.name = 'Hash_Map_Demo' <file_sep>/src/main/java/HashMapDemo.java import java.util.HashMap; public class HashMapDemo { public static void main(String[] args) { HashMap<String, String> favouriteFruits = new HashMap(); favouriteFruits.put("Alice", "Apple"); favouriteFruits.put("Sarah", "Banana"); favouriteFruits.put("Bob", "Strawberry"); // System.out.println(favouriteFruits.get("Alice")); // for (String value : favouriteFruits.values()){ // System.out.println("The favourite fruit is: " + value); // } for (String key : favouriteFruits.keySet()){ System.out.println(key + " favourite fruit is: " + favouriteFruits.get(key)); } } }
80e7be2b0de88efd538b1ebf33ba73ba0cf06482
[ "Java", "Gradle" ]
2
Gradle
YYChen01988/Hash_Map
1cf78b01f9b8e735e8b7c835f99a41d47259745b
1f7b155286727e2089a3d89d40b8c8c7bfd3077f
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using ChartJS_SQL_Populated.Models; using ChartJS_SQL_Populated.Repository; namespace ChartJS_SQL_Populated.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; private readonly IDatabaseRepository repository; public HomeController(ILogger<HomeController> logger, IDatabaseRepository repository) { _logger = logger; this.repository = repository; } public IActionResult Index() { //below method will will call GetBtcPrices which uses nomics.com API to get prices. //method is currently commented out as my DB has results. However, a javascript function //will be written to call this method at set time intervals, so each day the DB is populated with new results. //repository.GetBtcPrices(); return View(); } public IActionResult DisplayBtcPrices(int range) { //This method is the primary method fo retrieving all relevant information //from the SQL database. var array = repository.DisplayBtcPrices(range); //retrieve results as json ready to be plotted in graph. return Json(new { sucess = true, html = array }); } public IActionResult Privacy() { return View(); } public void GetBtcPrices() { repository.GetBtcPrices(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ChartJS_SQL_Populated.Models; namespace ChartJS_SQL_Populated.Repository { public interface IDatabaseRepository { public void GetBtcPrices(); List<BtcPriceModel> DisplayBtcPrices(int range); } } <file_sep># Bitcoin-Chart---ChartJS-SQL-Populated Simple .Net Core app that tracks BTC price with nomics.com API. Results are saved to a SQL db and retrived via an SQL query to be plotted onto a Js chart This app is still under development, but has core functionality. When this small project is complete I will implement it into a angular project to make the front end pretty. * Create a db within SQL server * Enter this query: ```alter database [YourDbName] set enable_broker with rollback immediate;``` ![](Screenshots/BtcChart.PNG) GetBtcPrices function needs to be modified via JavaScirpt to retrieve daily results. Next Steps: * create card layout, for different crpyto protocols. i.e, 3 x 3 grid Watch this space :) <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using ChartJS_SQL_Populated.Models; namespace ChartJS_SQL_Populated { public class MainDbContext : DbContext { public MainDbContext(DbContextOptions<MainDbContext> options) : base(options) { } public DbSet<BtcPriceModel> BtcPriceList { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ChartJS_SQL_Populated.Models { public class BtcPriceModel { public string Date { get; set; } public string Price { get; set; } } } <file_sep>using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ChartJS_SQL_Populated.Models; using System.Net; using System.Data.SqlClient; using Newtonsoft.Json; using System.IO; namespace ChartJS_SQL_Populated.Repository { public class DatabaseRepository : IDatabaseRepository { //initialise main database context and database connection string variables private readonly MainDbContext mainDbContext; string connectionString = ""; //initialsie random database name variable. public DatabaseRepository(MainDbContext mainDbContext, IConfiguration configuration) { //Class constructor to assign initilaied variables. //Assign mainDbContext and connection string that is stored within the app settings file. this.mainDbContext = mainDbContext; connectionString = configuration.GetConnectionString("DefaultConnection"); } public string BtcUrlConfig(string url) { //This method will create URI from the Transport API call that is used in the following method. //This is to parse the JSON data. Uri uri = new Uri(url); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.Method = WebRequestMethods.Http.Get; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string output = reader.ReadToEnd(); response.Close(); return output; } public void GetBtcPrices() { //Get btc prices and add them to SQL database string commandText = @"INSERT INTO BTC_Prices (Date, Price) VALUES (@date, @price)"; string apiKey = "Key goes here"; //your nomics API key here //This string contains the API call URL with the relevant optional paramaters present in the URL. string getJson = BtcUrlConfig("https://api.nomics.com/v1/exchange-rates/history?key=" + apiKey + "&currency=BTC&start=2018-04-14T00%3A00%3A00Z&end=2020-11-14T00%3A00%3A00Z%22"); //Create dynamic arrray to store deserialized json attributes. dynamic btcPriceArray = JsonConvert.DeserializeObject(getJson); //cycle thorugh each json result foreach (var price in btcPriceArray) { //Establish SQL connection. using (SqlConnection conn = new SqlConnection(connectionString)) { try { conn.Open(); SqlDependency.Start(connectionString); SqlCommand cmd = new SqlCommand(commandText, conn); //insert the json paramaters to the SQL table string timestamp = price["timestamp"]; timestamp.Substring(timestamp.Length - 8); cmd.Parameters.AddWithValue("@date", timestamp); cmd.Parameters.AddWithValue("@price", price["rate"].ToString()); //Console.WriteLine(price["timestamp"]); //Console.WriteLine(price["rate"]); //Execute the query cmd.ExecuteNonQuery(); } finally { //Close the connection when all results have been gathered. conn.Close(); } } } } public List<BtcPriceModel> DisplayBtcPrices(int range) { //initially, range will be null, if so change this to 30 days. if(range == 0) { range = 30; } //This method will display the BTC prices, for a given time range selected on the index page. //initialise list for results using the BtcPriceModel class to store each class object. List<BtcPriceModel> results = new List<BtcPriceModel>(); //currently the method will display results for the last 7 days. This is going to be worked on so that the user can specify the amount of time. string commandText = "SELECT * FROM BTC_Prices WHERE DATE BETWEEN DATEADD(DD, -@range, GETDATE()) AND GETDATE()"; using (SqlConnection conn = new SqlConnection(connectionString)) { //Establish SQL connection. conn.Open(); SqlDependency.Start(connectionString); //SqlDependency.Start(connectionString); SqlCommand cmd = new SqlCommand(commandText, conn); cmd.Parameters.AddWithValue("@range", range); //Execute SQL comand and add results to BtcPriceModel List var reader = cmd.ExecuteReader(); try { //Read all results until null while (reader.Read()) { var tempResult = new BtcPriceModel { //Assign class objects with the fields in SQL table. Date = reader["Date"].ToString(), Price = reader["Price"].ToString(), }; results.Add(tempResult); } } finally { reader.Close(); } } return results; } } }
44d6f344ac28080f8867da03e07fd7843c3841de
[ "Markdown", "C#" ]
6
C#
kieron-cairns/Bitcoin-Chart---ChartJS-SQL-Populated
2b3a8e40a5073ed87ba3fc563ac597a99d390872
fcb940dc2460a0c09597e29efad83a6fb9502334
refs/heads/master
<repo_name>Spacerat/sdk-codegen<file_sep>/packages/api-explorer/README.md # OpenAPI Explorer Use this **OpenAPI Explorer** to read any [OpenAPI](https://www.openapis.org/) specification and explore its **methods** and **types**. Fast and powerful searching is also supported. This is an Open Source project that builds on the specification processing created in the Looker [SDK Codegen project](https://github.com/looker-open-source/sdk-codegen). ## Getting started This project uses `yarn`. See the [yarn installation](https://classic.yarnpkg.com/en/docs/install/) instructions if you need to install it. With yarn installed, ```sh yarn ``` followed by ```sh yarn develop ``` will start the development server and monitor for changes. To see the other scripts supported by the project, do ```sh yarn run ``` <file_sep>/packages/api-explorer/src/reducers/spec/actions.spec.ts import { specs } from '../../test-data' import { selectSpec } from './actions' describe('Spec reducer actions', () => { test('returns a SELECT_SPEC action object with provided values', () => { const action = selectSpec(specs, '3.1') expect(action).toEqual({ type: 'SELECT_SPEC', key: '3.1', payload: specs, }) }) }) <file_sep>/packages/api-explorer/src/components/DocCode/utils.ts import { IMarker } from 'react-ace' export const highlightSourceCode = ( pattern: string, content: string, className = 'codeMarker' ): IMarker[] => { const result: IMarker[] = [] if (pattern) { const lines = content.split('\n') const target = new RegExp(pattern, 'gi') lines.forEach((line, index) => { let found while ((found = target.exec(line))) { const mark: IMarker = { className, endCol: found.index + found[0].length, endRow: index, startCol: found.index, startRow: index, type: 'text', } result.push(mark) } }) } return result } <file_sep>/packages/api-explorer/src/components/SideNavToggle/index.ts export { SideNavToggle } from './SideNavToggle' <file_sep>/packages/api-explorer/src/components/DocReferences/utils.ts import { ApiModel, IMethod, IType, Method } from '@looker/sdk-codegen' import { buildMethodPath, buildTypePath } from '../../utils' /** * Returns the tag for a given method name * @param Parsed api * @param Method name * @returns Corresponding tag */ const getTag = (api: ApiModel, methodName: string) => { // Find tag containing methodName return Object.entries(api.tags) .filter(([, methods]) => methodName in methods) .map(([methodTag]) => methodTag)[0] } /** * Builds a path matching MethodScene or TypeScene route * @param api * @param item A method or type item * @param specKey A string to identify the spec in the url * @returns a method or type path */ export const buildPath = ( api: ApiModel, item: IMethod | IType, specKey: string ) => { let path if (item instanceof Method) { path = buildMethodPath(specKey, getTag(api, item.name), item.name) } else { path = buildTypePath(specKey, item.name) } return path } <file_sep>/packages/sdk/src/rtl/extensionSdk.ts /* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { Readable } from 'readable-stream' import { Looker31SDK } from '../sdk/3.1/methods' import { DefaultSettings, IApiSettings } from './apiSettings' import { ExtensionSession } from './extensionSession' import { ExtensionTransport } from './extensionTransport' import { Authenticator, HttpMethod, IRawResponse, ITransportSettings, Values, } from './transport' import { APIMethods } from './apiMethods' import { IAuthSession } from './authSession' export interface IHostConnection { rawRequest( httpMethod: string, path: string, body?: any, params?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings> ): Promise<IRawResponse> request( httpMethod: string, path: string, body?: any, params?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings> ): Promise<any> stream<T>( callback: (readable: Readable) => Promise<T>, method: HttpMethod, path: string, queryParams?: Values, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings> ): Promise<T> } export class LookerExtensionSDK { /** * Creates a [[LookerSDK]] object. * * Examples: * LookerExtensionSDK.createClient(host) => constructs a Looker31SDK * * LookerExtensionSDK.createClient(host, Looker40SDK) => constructs a Looker40SDK */ static createClient<T extends APIMethods>( hostConnection: IHostConnection, type?: new (authSession: IAuthSession) => T, settings?: IApiSettings ): T { settings = settings || DefaultSettings() const transport = new ExtensionTransport(settings, hostConnection) const session = new ExtensionSession(settings, transport) if (type) { // eslint-disable-next-line new-cap return new type(session) } else { // work around TS2322 return (new Looker31SDK(session) as any) as T } } } <file_sep>/python/tests/rtl/test_serialize.py # The MIT License (MIT) # # Copyright (c) 2019 Looker Data Sciences, Inc. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import copy import enum import functools import json # ignoring "Module 'typing' has no attribute 'ForwardRef'" from typing import Optional, Sequence try: from typing import ForwardRef # type: ignore except ImportError: from typing import _ForwardRef as ForwardRef # type: ignore # from .. import attr import attr import cattr import pytest # type: ignore from looker_sdk.rtl import model as ml from looker_sdk.rtl import serialize as sr class Enum1(enum.Enum): """Predifined enum, used as ForwardRef. """ entry1 = "entry1" invalid_api_enum_value = "invalid_api_enum_value" Enum1.__new__ = ml.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class ModelNoRefs1(ml.Model): """Predifined model, used as ForwardRef. Since this model has no properties that are forwardrefs to other objects we can just decorate the class rather than doing the __annotations__ hack. """ name1: str def __init__(self, *, name1: str): self.name1 = name1 @attr.s(auto_attribs=True, init=False) class Model(ml.Model): """Representative model. [De]Serialization of API models relies on the attrs and cattrs libraries with some additional customization. This model represents these custom treatments and provides documentation for how and why they are needed. """ # enum1 and model_no_refs1 are both defined before this class # yet we will still refer to them using forward reference (double quotes) # because we do not keep track of definition order in the generated code enum1: "Enum1" model_no_refs1: "ModelNoRefs1" # enum2 and model_no_refs2 are both defined after this class and so the # forward reference annotation is required. enum2: "Enum2" model_no_refs2: "ModelNoRefs2" # Optional[] and List[] list_enum1: Sequence["Enum1"] list_model_no_refs1: Sequence["ModelNoRefs1"] opt_enum1: Optional["Enum1"] = None opt_model_no_refs1: Optional["ModelNoRefs1"] = None # standard types id: Optional[int] = None name: Optional[str] = None # testing reserved keyword translations class_: Optional[str] = None finally_: Optional[Sequence[int]] = None # Because this model has "bare" forward ref annotated properties # (enum1, enum2, model_no_refs1, and model_no_refs2) we need to tell # the attr library that they're actually ForwardRef objects so that # cattr will match our forward_ref_structure_hook structure hook # # # Note: just doing the following: # # `converter.register_structure_hook("Enum1", structure_hook)` # # does not work. cattr stores these hooks using functools singledispatch # which in turn creates a weakref.WeakKeyDictionary for the dispatch_cache. # While the registration happens, the cache lookup throws a TypeError # instead of a KeyError so we never look in the registry. __annotations__ = { # python generates these entries as "enum1": "Enum1" etc, we need # them to be of the form "enum1": ForwardRef("Enum1") "enum1": ForwardRef("Enum1"), "model_no_refs1": ForwardRef("ModelNoRefs1"), "enum2": ForwardRef("Enum2"), "model_no_refs2": ForwardRef("ModelNoRefs2"), # python "correctly" inserts the remaining entries but we have to # define all or nothing using this API "list_enum1": Sequence["Enum1"], "list_model_no_refs1": Sequence["ModelNoRefs1"], "opt_enum1": Optional["Enum1"], "opt_model_no_refs1": Optional["ModelNoRefs1"], "id": Optional[int], "name": Optional[str], "class_": Optional[str], "finally_": Optional[Sequence[int]], } def __init__( self, *, enum1: "Enum1", model_no_refs1: "ModelNoRefs1", enum2: "Enum2", model_no_refs2: "ModelNoRefs2", list_enum1: Sequence["Enum1"], list_model_no_refs1: Sequence["ModelNoRefs1"], opt_enum1: Optional["Enum1"] = None, opt_model_no_refs1: Optional["ModelNoRefs1"] = None, id: Optional[int] = None, name: Optional[str] = None, class_: Optional[str] = None, finally_: Optional[Sequence[int]] = None, ): """Keep mypy and IDE suggestions happy. We cannot use the built in __init__ generation attrs offers because mypy complains about unknown keyword argument, even when kw_only=True is set below. Furthermore, IDEs do not pickup on the attrs generated __init__ so completion suggestion fails for insantiating these classes otherwise. """ self.enum1 = enum1 self.model_no_refs1 = model_no_refs1 self.enum2 = enum2 self.model_no_refs2 = model_no_refs2 self.list_enum1 = list_enum1 self.list_model_no_refs1 = list_model_no_refs1 self.opt_enum1 = opt_enum1 self.opt_model_no_refs1 = opt_model_no_refs1 self.id = id self.name = name self.class_ = class_ self.finally_ = finally_ class Enum2(enum.Enum): """Post defined enum, used as ForwardRef. """ entry2 = "entry2" invalid_api_enum_value = "invalid_api_enum_value" Enum2.__new__ = ml.safe_enum__new__ @attr.s(auto_attribs=True, init=False) class ModelNoRefs2(ml.Model): """Post defined model, used as ForwardRef. Since this model has no properties that are forwardrefs to other objects we can just decorate the class rather than doing the __annotations__ hack. """ name2: str def __init__(self, *, name2: str): self.name2 = name2 converter = cattr.Converter() structure_hook = functools.partial(sr.forward_ref_structure_hook, globals(), converter) translate_keys_structure_hook = functools.partial( sr.translate_keys_structure_hook, converter ) converter.register_structure_hook(ForwardRef("Model"), structure_hook) converter.register_structure_hook(ForwardRef("ChildModel"), structure_hook) converter.register_structure_hook(ForwardRef("Enum1"), structure_hook) converter.register_structure_hook(ForwardRef("Enum2"), structure_hook) converter.register_structure_hook(ForwardRef("ModelNoRefs1"), structure_hook) converter.register_structure_hook(ForwardRef("ModelNoRefs2"), structure_hook) converter.register_structure_hook(Model, translate_keys_structure_hook) MODEL_DATA = { "enum1": "entry1", "model_no_refs1": {"name1": "model_no_refs1_name"}, "enum2": "entry2", "model_no_refs2": {"name2": "model_no_refs2_name"}, "list_enum1": ["entry1"], "list_model_no_refs1": [{"name1": "model_no_refs1_name"}], "opt_enum1": "entry1", "opt_model_no_refs1": {"name1": "model_no_refs1_name"}, "id": 1, "name": "my-name", "class": "model-name", "finally": [1, 2, 3], } def test_deserialize_single(): """Deserialize functionality Should handle python reserved keywords as well as attempting to convert field values to proper type. """ # check that type conversion happens, str -> int in this case data = copy.deepcopy(MODEL_DATA) data["id"] = "1" d = json.dumps(data) model = sr.deserialize(data=d, structure=Model, converter=converter) assert model == Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], opt_enum1=Enum1.entry1, opt_model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), id=1, name="my-name", class_="model-name", finally_=[1, 2, 3], ) def test_deserialize_list(): # check that type conversion happens data = [MODEL_DATA] models = sr.deserialize( data=json.dumps(data), structure=Sequence[Model], converter=converter ) assert models == [ Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], opt_enum1=Enum1.entry1, opt_model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), id=1, name="my-name", class_="model-name", finally_=[1, 2, 3], ), ] def test_deserialize_partial(): data = copy.deepcopy(MODEL_DATA) del data["id"] del data["opt_enum1"] del data["opt_model_no_refs1"] model = sr.deserialize(data=json.dumps(data), structure=Model, converter=converter) assert model == Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], opt_enum1=None, opt_model_no_refs1=None, id=None, name="my-name", class_="model-name", finally_=[1, 2, 3], ) def test_deserialize_with_null(): data = copy.deepcopy(MODEL_DATA) # json.dumps sets None to null data["id"] = None data["opt_enum1"] = None data["opt_model_no_refs1"] = None model = sr.deserialize(data=json.dumps(data), structure=Model, converter=converter) assert model == Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], opt_enum1=None, opt_model_no_refs1=None, id=None, name="my-name", class_="model-name", finally_=[1, 2, 3], ) @pytest.mark.parametrize( "data, structure", [ # ?? # Error: mypy: Variable "tests.rtl.test_serialize.Model" is not valid as a type (MODEL_DATA, Sequence[Model]), # type: ignore ([MODEL_DATA], Model), ], ) def test_deserialize_data_structure_mismatch(data, structure): data = json.dumps(data) with pytest.raises(sr.DeserializeError): sr.deserialize(data=data, structure=structure, converter=converter) def test_serialize_single(): model = Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], opt_enum1=Enum1.entry1, opt_model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), id=1, name="my-name", class_="model-name", finally_=[1, 2, 3], ) expected = json.dumps(MODEL_DATA).encode("utf-8") assert sr.serialize(model) == expected def test_serialize_sequence(): model = Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], opt_enum1=Enum1.entry1, opt_model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), id=1, name="my-name", class_="model-name", finally_=[1, 2, 3], ) expected = json.dumps([MODEL_DATA, MODEL_DATA]).encode("utf-8") assert sr.serialize([model, model]) == expected def test_serialize_partial(): """Do not send json null for model None field values. """ model = Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], ) expected = json.dumps( { "enum1": "entry1", "model_no_refs1": {"name1": "model_no_refs1_name"}, "enum2": "entry2", "model_no_refs2": {"name2": "model_no_refs2_name"}, "list_enum1": ["entry1"], "list_model_no_refs1": [{"name1": "model_no_refs1_name"}], } ).encode("utf-8") assert sr.serialize(model) == expected def test_serialize_explict_null(): """Send json null for model field EXPLICIT_NULL values. """ # pass EXPLICIT_NULL into constructor model = Model( enum1=Enum1.entry1, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.entry2, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], name=ml.EXPLICIT_NULL, class_=ml.EXPLICIT_NULL, ) # set property to EXPLICIT_NULL model.finally_ = ml.EXPLICIT_NULL expected = json.dumps( { "enum1": "entry1", "model_no_refs1": {"name1": "model_no_refs1_name"}, "enum2": "entry2", "model_no_refs2": {"name2": "model_no_refs2_name"}, "list_enum1": ["entry1"], "list_model_no_refs1": [{"name1": "model_no_refs1_name"}], # json.dumps puts these into the json as null "name": None, "class": None, "finally": None, } ).encode("utf-8") assert sr.serialize(model) == expected def test_safe_enum_deserialization(): data = copy.deepcopy(MODEL_DATA) data["enum1"] = "not an Enum1 member!" data["enum2"] = "" model = Model( enum1=Enum1.invalid_api_enum_value, model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), enum2=Enum2.invalid_api_enum_value, model_no_refs2=ModelNoRefs2(name2="model_no_refs2_name"), list_enum1=[Enum1.entry1], list_model_no_refs1=[ModelNoRefs1(name1="model_no_refs1_name")], opt_enum1=Enum1.entry1, opt_model_no_refs1=ModelNoRefs1(name1="model_no_refs1_name"), id=1, name="my-name", class_="model-name", finally_=[1, 2, 3], ) assert ( sr.deserialize(data=json.dumps(data), structure=Model, converter=converter) == model ) <file_sep>/packages/api-explorer/src/components/DocSDKs/index.ts export { DocSDKs } from './DocSDKs' <file_sep>/packages/api-explorer/src/context/index.ts export { SearchContext, defaultSearchContextValue } from './search' <file_sep>/packages/api-explorer/src/test-data/index.ts export { api, specs, specState } from './specs' <file_sep>/packages/sdk-codegen/README.md # Looker SDK code generator core files This package contains the OpenAPI analysis files, and all source code necessary to generate method and type declarations for supported languages. ## Supported languages This package includes the following language generators: - Typescript - Python - Kotlin - Swift See the [SDK Codegen project](https://github.com/looker-open-source/sdk-codegen) repository for more information. <file_sep>/packages/api-explorer/src/components/DocReferences/utils.spec.ts import { api } from '../../test-data' import { buildPath } from './utils' describe('DocReferences utils', () => { describe('buildPath', () => { test('given a method it builds a method path', () => { const path = buildPath(api, api.methods.create_dashboard, '3.1') expect(path).toEqual('/3.1/methods/Dashboard/create_dashboard') }) test('given a type it creates a type path', () => { const path = buildPath(api, api.types.Dashboard, '3.1') expect(path).toEqual('/3.1/types/Dashboard') }) }) }) <file_sep>/packages/api-explorer/src/reducers/spec/reducer.spec.ts import { ApiModel } from '@looker/sdk-codegen' import { specs } from '../../test-data' import { specReducer } from './reducer' import { fetchSpec } from './utils' describe('Spec Reducer', () => { test('it selects a spec', () => { const action = { type: 'SELECT_SPEC', key: '4.0', payload: specs, } const state = specReducer(fetchSpec('3.1', specs), action) expect(state.api).toBeInstanceOf(ApiModel) expect(state.key).toEqual('4.0') expect(state.status).toEqual(action.payload['4.0'].status) }) }) <file_sep>/packages/api-explorer/src/utils/path.ts /** * Builds a path matching the route used by MethodScene * @param methodName A method name * @param specKey A string to identify the spec in the URL * @param tag Corresponding method tag * @returns a Method path */ export const buildMethodPath = ( specKey: string, tag: string, methodName: string ) => `/${specKey}/methods/${tag}/${methodName}` /** * Builds a path matching the route used by TypeScene * @param typeName A type name * @param specKey A string to identify the spec in the URL * @returns a Type path */ export const buildTypePath = (specKey: string, typeName: string) => `/${specKey}/types/${typeName}` <file_sep>/packages/sdk/src/rtl/browserTransport.ts /* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import { PassThrough, Readable } from 'readable-stream' import { ISDKError, SDKResponse, ITransportSettings, HttpMethod, Authenticator, trace, IRequestProps, IRequestHeaders, LookerAppId, agentPrefix, Values, IRawResponse, responseMode, ResponseMode, safeBase64, } from './transport' import { BaseTransport } from './baseTransport' import { lookerVersion } from './constants' import { ICryptoHash } from './cryptoHash' async function parseResponse(res: IRawResponse) { if (res.contentType.match(/application\/json/g)) { try { return JSON.parse(await res.body) } catch (error) { return Promise.reject(error) } } else if ( res.contentType === 'text' || res.contentType.startsWith('text/') ) { return res.body.toString() } else { try { return res.body } catch (error) { return Promise.reject(error) } } } export class BrowserCryptoHash implements ICryptoHash { arrayToHex(array: Uint8Array): string { return Array.from(array) .map((b) => b.toString(16).padStart(2, '0')) .join('') } fromBase64(str: string) { return atob(str) .split('') .map(function(c) { return c.charCodeAt(0) }) } secureRandom(byteCount: number): string { const bytes = new Uint8Array(byteCount) window.crypto.getRandomValues(bytes) return this.arrayToHex(bytes) } async sha256Hash(message: string): Promise<string> { const msgUint8 = new TextEncoder().encode(message) const hashBuffer = await window.crypto.subtle.digest('SHA-256', msgUint8) return safeBase64(new Uint8Array(hashBuffer)) } } export class BrowserTransport extends BaseTransport { constructor(protected readonly options: ITransportSettings) { super(options) } async rawRequest( method: HttpMethod, path: string, queryParams?: Values, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings> ): Promise<IRawResponse> { options = { ...this.options, ...options } const requestPath = this.makeUrl(path, options, queryParams) const props = await this.initRequest( method, requestPath, body, authenticator, options ) const req = fetch( props.url, props // Weird package issues with unresolved imports for RequestInit :( ) const res = await req const contentType = String(res.headers.get('content-type')) const mode = responseMode(contentType) return { body: mode === ResponseMode.binary ? await res.blob() : await res.text(), contentType, ok: true, statusCode: res.status, statusMessage: res.statusText, } } async request<TSuccess, TError>( method: HttpMethod, path: string, queryParams?: any, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings> ): Promise<SDKResponse<TSuccess, TError>> { try { const res = await this.rawRequest( method, path, queryParams, body, authenticator, options ) const parsed = await parseResponse(res) if (this.ok(res)) { return { ok: true, value: parsed } } else { return { error: parsed, ok: false } } } catch (e) { const error: ISDKError = { message: typeof e.message === 'string' ? e.message : `The SDK call was not successful. The error was '${e}'.`, type: 'sdk_error', } return { error, ok: false } } } private async initRequest( method: HttpMethod, path: string, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings> ) { const agentTag = options?.agentTag || `${agentPrefix} ${lookerVersion}` options = options ? { ...this.options, ...options } : this.options const headers: IRequestHeaders = { [LookerAppId]: agentTag } if (options && options.headers) { Object.entries(options.headers).forEach(([key, val]) => { headers[key] = val }) } // Make sure an empty body is undefined if (!body) { body = undefined } else { if (typeof body !== 'string') { body = JSON.stringify(body) headers['Content-Type'] = 'application/json' } } let props: IRequestProps = { body, credentials: 'same-origin', headers, method, url: path, } if (authenticator) { // Add authentication information to the request props = await authenticator(props) } return props } // TODO finish this method async stream<TSuccess>( callback: (readable: Readable) => Promise<TSuccess>, method: HttpMethod, path: string, queryParams?: any, body?: any, authenticator?: Authenticator, options?: Partial<ITransportSettings> ): Promise<TSuccess> { options = options ? { ...this.options, ...options } : this.options const stream = new PassThrough() const returnPromise = callback(stream) const requestPath = this.makeUrl(path, options, queryParams) const props = await this.initRequest( method, requestPath, body, authenticator, options ) trace(`[stream] attempting to stream via download url`, props) return Promise.reject<TSuccess>( // Silly error message to prevent linter from complaining about unused variables Error( `Streaming for${returnPromise ? 'callback' : ''} ${props.method} ${ props.requestPath } is not implemented` ) ) /* TODO complete this for the browser implementation const streamPromise = new Promise<void>((resolve, reject) => { trace(`[stream] beginning stream via download url`, props) reject(Error('Not implemented yet!')) // let hasResolved = false // const req = this.requestor(props) // // req // .on("error", (err) => { // if (hasResolved && (err as any).code === "ECONNRESET") { // trace('ignoring ECONNRESET that occurred after streaming finished', props) // } else { // trace('streaming error', err) // reject(err) // } // }) // .on("finish", () => { // trace(`[stream] streaming via download url finished`, props) // }) // .on("socket", (socket) => { // trace(`[stream] setting keepalive on socket`, props) // socket.setKeepAlive(true) // }) // .on("abort", () => { // trace(`[stream] streaming via download url aborted`, props) // }) // .on("response", () => { // trace(`[stream] got response from download url`, props) // }) // .on("close", () => { // trace(`[stream] request stream closed`, props) // }) // .pipe(stream) // .on("error", (err) => { // trace(`[stream] PassThrough stream error`, err) // reject(err) // }) // .on("finish", () => { // trace(`[stream] PassThrough stream finished`, props) // resolve() // hasResolved = true // }) // .on("close", () => { // trace(`[stream] PassThrough stream closed`, props) // }) }) const results = await Promise.all([returnPromise, streamPromise]) return results[0] */ } } <file_sep>/packages/api-explorer/src/utils/index.ts export { highlightHTML } from './highlight' export { buildMethodPath, buildTypePath } from './path' <file_sep>/packages/api-explorer/src/reducers/spec/index.ts export { initDefaultSpecState } from './utils' export { selectSpec } from './actions' export { specReducer, SpecAction, SpecState } from './reducer' <file_sep>/packages/api-explorer/src/reducers/index.ts export { specReducer, selectSpec, initDefaultSpecState, SpecState, SpecAction, } from './spec' export { searchReducer, setCriteria, setPattern, defaultSearchState, SearchState, SearchAction, } from './search' <file_sep>/packages/run-it/src/components/ConfigForm/configUtils.ts /* MIT License Copyright (c) 2020 Looker Data Sciences, Inc. 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. */ export const RunItConfigKey = 'RunItConfig' export const RunItValuesKey = 'RunItValues' export type StorageLocation = 'session' | 'local' export interface IStorageValue { location: StorageLocation value: string } /** * Tries to get the value saved with `key` from either session or local storage * * If no value is saved with that key, the default response returns * `{ location: 'session', value: defaultValue }` * * @param key storage key * @param defaultValue to retrieve. Defaults to '' * @returns the location where the key was found, and its value */ export const getStorage = (key: string, defaultValue = ''): IStorageValue => { let value = sessionStorage.getItem(key) if (value) { return { location: 'session', value, } } value = localStorage.getItem(key) if (value) { return { location: 'local', value, } } return { location: 'session', value: defaultValue, } } export const setStorage = ( key: string, value: string, location: StorageLocation = 'session' ): string => { switch (location.toLocaleLowerCase()) { case 'local': localStorage.setItem(key, value) break case 'session': sessionStorage.setItem(key, value) break } return value } export const removeStorage = (key: string) => { localStorage.removeItem(key) sessionStorage.removeItem(key) } /** * Validates URL and standardizes it * @param url to validate * @returns the standardized url.origin if it's valid, or an empty string if it's not */ export const validateUrl = (url: string) => { try { const result = new URL(url) if (url.endsWith(':')) return url return result.origin } catch { return '' } } export const validLocation = (location: string) => ['local', 'session'].includes(location.toLocaleLowerCase())
50bac84684c93ea5e7182ac16efc9d39c01f1341
[ "Markdown", "Python", "TypeScript" ]
19
Markdown
Spacerat/sdk-codegen
adc500b1e09d5b064016fe09dc49cf05a6cec97f
c36b95fa0d3c3ece6d6fbb6e09a9625f00adc9e5
refs/heads/master
<file_sep><?php include('config.php'); $sel = $_POST['item_selected']; $sql= "delete from product where item_id = '".$sel."'"; $conn->query($sql); $conn->close(); header('Location:index.php'); ?><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Mar 30, 2020 at 05:56 AM -- Server version: 5.7.26 -- PHP Version: 7.0.33 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: `proger` -- -- -------------------------------------------------------- -- -- Table structure for table `product` -- DROP TABLE IF EXISTS `product`; CREATE TABLE IF NOT EXISTS `product` ( `id` int(255) NOT NULL AUTO_INCREMENT, `item_id` varchar(255) NOT NULL, `item_name` varchar(255) NOT NULL, `item_description` varchar(255) NOT NULL, `item_quantity` int(255) NOT NULL, `item_image` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=22 DEFAULT CHARSET=latin1; -- -- Dumping data for table `product` -- INSERT INTO `product` (`id`, `item_id`, `item_name`, `item_description`, `item_quantity`, `item_image`) VALUES (21, 'pr_2', 'soap', 'this is a test item', 20, 'jpg-vs-jpeg.jpg'), (20, 'pr_1', 'soap', 'this is a test item', 201, 'download.jpg'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- DROP TABLE IF EXISTS `users`; CREATE TABLE IF NOT EXISTS `users` ( `id` int(255) NOT NULL AUTO_INCREMENT, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `pass` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; 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 include('config.php'); $flag = 0 ; if(isset($_POST['selection_button'])){ } if(isset($_POST['submit'])){ $id = $_POST['itemid']; $name = $_POST['itemName']; $description = $_POST['itemDescription']; $quantity = $_POST['itemQuantity']; $sql = "update product set item_name = '".$name."',item_description ='".$description."' ,item_quantity = ".$quantity." where item_id ='".$id."'"; if ($conn->query($sql) === TRUE) { echo "queersr"; header('location: index.php'); } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); } ?> <file_sep><!doctype html> <html lang="en"> <head> <?php // Start the session session_start(); ?> <?php include('config.php');?> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Proger</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Proger</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item "> <a class="nav-link" href="index.php">HOME </a> </li> <li class="nav-item"> <a class="nav-link" href="add.php">ADD</a> </li> <li class="nav-item active"> <a class="nav-link" href="update.php">UPDATE<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="delete.php">DELETE</a> </li> </ul> </div> </nav> <br> <div class="container"> <form method="POST" action="update.php"> <?php $selected_item; if(isset($_POST['select_button'])){ $selected_item = $_POST['item_id_selected']; } else{ $selected_item = $_SESSION['select_item']; } $sql = "select * from product where item_id = '".$selected_item."'"; $result = $conn->query($sql); $row= $result->fetch_assoc(); ?> <div class="form-group"> <label for="itemId">ITEM ID SELECTION</label> <select class="custom-select" id="itemId" aria-describedby=" itemHelp " name="item_id_selected"> <?php $sql1 = "select * from product "; $result1= $conn->query($sql1); while($row1= $result1->fetch_assoc()){ ?> <option value=<?php echo $row1['item_id'];?>> <?php echo $row1['item_id'];?> </option> <?php }?> </select> <small id="itemHelp " class="form-text text-muted ">Select the item to update</small> <button name="select_button" type="submit" class="btn btn-primary " value="submit">Submit</button> </div> </form> <form action="actual_update.php" method="post"> <div class="form-group"> <label for="itemName">ITEM ID</label> <input type="text" class="form-control" readonly id="itemName" value = "<?php echo $row['item_id'];?>"name="itemid" aria-describedby=" itemHelp "> </div> <div class="form-group"> <label for="itemName">ITEM NAME</label> <input type="text" class="form-control" id="itemName" value = "<?php echo $row['item_name'];?>"name="itemName" aria-describedby=" itemHelp "> <small id="itemHelp " class="form-text text-muted ">Enter name of the item.</small> </div> <div class="form-group "> <label for="itemDescription ">ITEM DESCRIPTION</label> <input type="text " class="form-control " id="itemDescription " value="<?php echo $row['item_description'];?>"name="itemDescription" aria-describedby="itemHelp "> <small id="itemHelp " class="form-text text-muted ">Enter name of the Description.</small> </div> <div class="form-group "> <label for="itemQuantity ">ITEM QUANTITY</label> <input type="number" class="form-control " id="itemQuantity" name="itemQuantity" value="<?php echo $row['item_quantity'];?>" aria-describedby="itemHelp "> <small id="itemHelp " class="form-text text-muted ">Enter quantity of the item.</small> </div> <div class="custom-file"> <input type="file" class="custom-file-input" id="itemImage" value = "<?php echo $row['item_image'];?>"aria-describedby="itemHelp" name="imageUP"> <label class="custom-file-label" for="itemImage"><?php echo $row['item_image'];?></label> <small id="itemHelp " class="form-text text-muted ">Enter path of the item image.</small> </div> <br><br> <button type="submit " name = "submit" class="btn btn-primary ">Submit</button> </form> <?php $conn->close(); ?> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep><!doctype html> <html lang="en"> <head> <?php include('config.php');?> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Proger</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Proger</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item "> <a class="nav-link" href="index.php">Home </a> </li> <li class="nav-item active"> <a class="nav-link" href="add.php">ADD<span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="update.php">UPDATE</a> </li> <li class="nav-item"> <a class="nav-link" href="delete.php">DELETE</a> </li> </ul> </div> </nav> <br> <div class="container"> <form method="POST" action="add.php" enctype="multipart/form-data"> <div class="form-group"> <label for="itemName">ITEM ID</label> <input type="text" class="form-control" id="itemName" name="itemID" aria-describedby="itemHelp"> <small id="itemHelp" class="form-text text-muted">Enter item id.</small> </div> <div class="form-group"> <label for="itemName">ITEM NAME</label> <input type="text" class="form-control" id="itemName" name="itemName" aria-describedby=" itemHelp "> <small id="itemHelp " class="form-text text-muted ">Enter name of the item.</small> </div> <div class="form-group "> <label for="itemDescription ">ITEM DESCRIPTION</label> <input type="text " class="form-control " id="itemDescription " name="itemDescription" aria-describedby="itemHelp "> <small id="itemHelp " class="form-text text-muted ">Enter name of the Description.</small> </div> <div class="form-group "> <label for="itemQuantity ">ITEM QUANTITY</label> <input type="number" class="form-control " id="itemQuantity" name="itemQuantity" aria-describedby="itemHelp "> <small id="itemHelp " class="form-text text-muted ">Enter quantity of the item.</small> </div> <div class="custom-file"> <input type="file" class="custom-file-input" id="itemImage" aria-describedby="itemHelp" name="imageUP"> <label class="custom-file-label" for="itemImage" value ="Chose the image"></label> <small id="itemHelp " class="form-text text-muted ">Enter path of the item image.</small> </div> <br><br> <button type="submit " name ="submit"class="btn btn-primary ">Submit</button> </form> </div> <!-- PHP script Section --> <?php if(isset($_POST['submit'])){ $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["imageUP"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION)); // Check if image file is a actual image or fake image if(isset($_POST["submit"])) { $check = getimagesize($_FILES["imageUP"]["tmp_name"]); if($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } // Check if file already exists // Check file size if ($_FILES["imageUP"]["size"] > 500000) { echo "Sorry, your file is too large."; $uploadOk = 0; } // Allow certain file formats if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } // Check if $uploadOk is set to 0 by an error if ($uploadOk == 0) { echo "Sorry, your file was not uploaded."; // if everything is ok, try to upload file } else { if (move_uploaded_file($_FILES["imageUP"]["tmp_name"], $target_file)) { echo "The file ". basename( $_FILES["imageUP"]["name"]). " has been uploaded."; } else { die(); echo "Sorry, there was an error uploading your file."; } } $id = $_POST['itemID']; $name = $_POST['itemName']; $description = $_POST['itemDescription']; $quantity = $_POST['itemQuantity']; $image =$_FILES["imageUP"]["name"]; $sql= "INSERT INTO `product` ( `item_id`, `item_name`, `item_description`, `item_quantity`,`item_image`) VALUES ( '$id', '$name', '$description', '$quantity','$image')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); } ?> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js " integrity="<KEY> crossorigin="anonymous "></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js " integrity="<KEY> crossorigin="anonymous "></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js " integrity="<KEY> crossorigin="anonymous "></script> </body> </html><file_sep><!doctype html> <html lang="en"> <head> <?php // Start the session session_start(); ?> <?php include('config.php');?> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title>Proger</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Proger</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="index.php">HOME <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="add.php">ADD</a> </li> <li class="nav-item"> <a class="nav-link" href="update.php">UPDATE</a> </li> <li class="nav-item"> <a class="nav-link" href="delete.php">DELETE</a> </li> </ul> </div> </nav> <br> <div class="row"> <?php $sql = "SELECT * FROM product"; $result = $conn->query($sql); while($row = mysqli_fetch_assoc($result)) { ?> <div class="card" style="width:20rem;margin:30px"> <img src="uploads/<?php echo $row['item_image']?>" class="card-img-top" alt="..." style="height:20rem;"> <div class="card-body"> <h5 class="card-title"><?php echo $row['item_name'] ?></h5> <p class="card-text"><?php echo $row['item_description']?></p> <a href="update.php" class="btn btn-primary">Update</a> <?php $_SESSION['select_item']=$row['item_id']?> </div> </div> <?php } $conn->close(); ?> </div> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html>
d602341f5e1317e4ae7c6a3fe1d004d40e76d1e3
[ "SQL", "PHP" ]
6
PHP
akmore10/akmore10
9f0b35907e820016babcf23c684e712b6bafd176
2958e46e0c3e799f0d533a6b3218f80ccbddebd9
refs/heads/master
<file_sep>#ifndef __MAIN_HPP__ #define __MAIN_HPP__ #endif <file_sep>#include <iostream> #include <algorithm> #include <limits> #include <map> #include <random> #include <string> #include <vector> #include <pthread.h> #include <time.h> #include <chrono> #include <random> #include <iterator> #include "mcts.hpp" #include "reversi.hpp" #include "main.hpp" // adapted from // https://stackoverflow.com/questions/6942273/how-to-get-a-random-element-from-a-c-container template<typename Iter, typename RandomGenerator> Iter select_randomly(Iter start, Iter end, RandomGenerator& g) { std::uniform_int_distribution<> dis(0, std::distance(start, end) - 1); std::advance(start, dis(g)); return start; } template<typename Iter> Iter select_randomly(Iter start, Iter end) { static std::random_device rd; static std::mt19937 gen(rd()); return select_randomly(start, end, gen); } mcts::mcts(Reversi* game) { this->game = game; } mcts::~mcts() { } struct threadParams { void* context; int move; }; int mcts::checkOutcome(Reversi gameCopy) { if (gameCopy.getIsGameFinished() && (gameCopy.getNumX() == gameCopy.getNumO())) { return 0; } else if (gameCopy.getIsGameFinished() && (gameCopy.getNumO() > gameCopy.getNumX())) { return 1; } else if (gameCopy.getIsGameFinished() && (gameCopy.getNumO() < gameCopy.getNumX())) { return -1; } return -2; } int mcts::doRandomPayout(int move) { // srand(time(0)); Reversi* gameCopy_p = this->game; Reversi gameCopy = *(Reversi*) gameCopy_p; gameCopy.setSimulation(true); gameCopy.placePiece(move); gameCopy.checkOppTurn(); gameCopy.setNumO(0); gameCopy.setNumX(0); while (!gameCopy.getIsGameFinished()) { std::vector<int> legalMoves = gameCopy.getLegalMoves(); if (legalMoves.size() == 0) { if (gameCopy.getTurn() == "X") { gameCopy.setTurn("O"); } else { gameCopy.setTurn("X"); } legalMoves = gameCopy.getLegalMoves(); if (legalMoves.size() == 0) { gameCopy.setIsGameFinished(true); gameCopy.checkNumTiles(); break; } } else { int randomMove; if (gameCopy.getTurn() == "O") { if (this->player_struct.mcts) { if (!this->player_struct.heuristic) { randomMove = *select_randomly(legalMoves.begin(), legalMoves.end()); } else { randomMove = heuristic(gameCopy); } } else if (this->player_struct.heuristic) { randomMove = heuristic(gameCopy); } } else { if (this->player_struct.mcts) { randomMove = *select_randomly(legalMoves.begin(), legalMoves.end()); } else if (this->player_struct.heuristic) { randomMove = heuristic(gameCopy); } } gameCopy.placePiece(randomMove); gameCopy.checkOppTurn(); // gameCopy.displayBoard(); } } // std::cout << "Score: \033[92mX\033[0m: " << gameCopy.getNumX() << " \033[36mO\033[0m: " << // gameCopy.getNumO() << std::endl; gameCopy.displayBoard(); std::cout << std::endl; return this->checkOutcome(gameCopy); } int mcts::playOutNTimes(int move) { int winNum; int numPlayouts = 0; auto start = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds; for (int i = 0; i < 250; i++) { // while(true){ winNum += this->doRandomPayout(move); numPlayouts++; auto end = std::chrono::system_clock::now(); elapsed_seconds = end-start; if (elapsed_seconds > std::chrono::seconds(5)) { // std::cout << "elapsed time limit: " << elapsed_seconds.count() << "s\n"; break; } } // double sec = elapsed_seconds.count(); // printf("played %f games/sec\n", (double)numPlayouts/sec); return winNum; } static void *playoutHelper(void *context) { struct threadParams* params = (struct threadParams*)context; return (void*)(long)((mcts *)params->context)->playOutNTimes(params->move); } void mcts::chooseMove() { Reversi game = *(Reversi*) this->game; std::map<int, int> countWinningMoves; std::vector<int> legalMoves = game.getLegalMoves(); for (auto move : legalMoves) { countWinningMoves.insert(std::pair<int, int>(move, 0)); } pthread_t threadPool[64]; for (long unsigned int i = 0; i < legalMoves.size(); i++) { struct threadParams params; params.context = (void*) this; params.move = legalMoves.at(i); pthread_create(&threadPool[i], NULL, playoutHelper, &params); } for (long unsigned int i = 0; i < legalMoves.size(); i++) { int* status; pthread_join(threadPool[i], (void**)&status); countWinningMoves[legalMoves.at(i)] += (int)(long)status; } std::map<int, int>::iterator it; int maxWins = (int) -INFINITY; int chosenMove = -1; for (it = countWinningMoves.begin(); it != countWinningMoves.end(); it++) { // printf("key: %d Value: %d\n", it->first, it->second); if (it->second > maxWins) { chosenMove = it->first; maxWins = it->second; } } std::cout << "Player " << this->game->getTurn() << " placing: " << chosenMove << std::endl; this->game->placePiece(chosenMove); } int mcts::heuristic(Reversi gameCopy) { /** * { 20, -3, 11, 8, 8, 11, -3, 20 } { -3, -7, -4, 1, 1, -4, -7, -3 }, { 11, -4, 2, 2, 2, 2, -4, 11 } { 8, 1, 2, -3, -3, 2, 1, 8 }, { 8, 1, 2, -3, -3, 2, 1, 8 } { 11, -4, 2, 2, 2, 2, -4, 11 }, { -3, -7, -4, 1, 1, -4, -7, -3 } { 20, -3, 11, 8, 8, 11, -3, 20 } * */ int weightMap[8][8] = { { 20, -3, 11, 8, 8, 11, -3, 20 }, { -3, -7, -4, 1, 1, -4, -7, -3 }, { 11, -4, 2, 2, 2, 2, -4, 11 }, { 8, 1, 2, -3, -3, 2, 1, 8 }, { 8, 1, 2, -3, -3, 2, 1, 8 }, { 11, -4, 2, 2, 2, 2, -4, 11 }, { -3, -7, -4, 1, 1, -4, -7, -3 }, { 20, -3, 11, 8, 8, 11, -3, 20 } }; std::vector<int> legalMoves = gameCopy.getLegalMoves(); std::map<int, std::vector<int>> getFrontiers; for (auto move : legalMoves) { int row = gameCopy.getTileRow(move); int col = gameCopy.getTileColumn(move); std::vector<int> frontierWeightPair; frontierWeightPair.push_back(checkFrontiers(move, gameCopy)); frontierWeightPair.push_back(weightMap[row][col]); getFrontiers.insert(std::pair<int, std::vector<int>>(move, frontierWeightPair)); } int largestWeight = (int) -INFINITY; int smallestFrontier = (int) INFINITY; int chosenMove = -1; for (std::map<int, std::vector<int>>::iterator it = getFrontiers.begin(); it != getFrontiers.end(); it++) { if (it->second.at(0) < smallestFrontier) { chosenMove = it->first; smallestFrontier = it->second.at(0); } else if (it->second.at(0) == smallestFrontier) { if (it->second.at(1) > largestWeight) { chosenMove = it->first; largestWeight = it->second.at(1); } } } // std::cout << "Player " << gameCopy.getTurn() << " placing: " << chosenMove << std::endl; // this->game->placePiece(chosenMove); return chosenMove; } int mcts::checkFrontiers(int move, Reversi gameCopy) { int downLeft = move + 7; int down = move + 8; int downRight = move + 9; int upLeft = move - 9; int up = move - 8; int upRight = move - 7; int right = move + 1; int left = move - 1; int frontierCounter = 0; if ((move % 8) != 0) { // if not left edge move if (downLeft < 56) { if (gameCopy.getBoardAt(downLeft) != "X" && gameCopy.getBoardAt(downLeft) != "O") { frontierCounter++; } } if (gameCopy.getBoardAt(left) != "X" && gameCopy.getBoardAt(left) != "O") { frontierCounter++; } if (upLeft > 0) { if (gameCopy.getBoardAt(upLeft) != "X" && gameCopy.getBoardAt(upLeft) != "O") { frontierCounter++; } } } if ((move + 1 % 8) != 0) { // if not right edge if (downRight < 63) { if (gameCopy.getBoardAt(downRight) != "X" && gameCopy.getBoardAt(downRight) != "O") { frontierCounter++; } } if (gameCopy.getBoardAt(right) != "X" && gameCopy.getBoardAt(right) != "O") { frontierCounter++; } if (upRight > 0) { if (gameCopy.getBoardAt(upRight) != "X" && gameCopy.getBoardAt(upRight) != "O") { frontierCounter++; } } } if (move > 7) { if (gameCopy.getBoardAt(up) != "X" && gameCopy.getBoardAt(up) != "O") { frontierCounter++; } } if (move < 56) { if (gameCopy.getBoardAt(down) != "X" && gameCopy.getBoardAt(down) != "O") { frontierCounter++; } } return frontierCounter; } <file_sep>CXX = g++ CXXFLAGS = -g -Wall -Wpedantic -pthread BUILD_DIR = build SUBMIT_DIR = submission OBJECTS = mcts.o main.o reversi.o TARGET = main OBJECT := $(addprefix $(BUILD_DIR)/,$(OBJECTS)) .PHONY: all valgrind clean all: $(TARGET) $(TARGET): $(OBJECT) $(CXX) $(CXXFLAGS) $(OBJECT) -o $(TARGET) $(BUILD_DIR)/%.o: %.cpp | $(BUILD_DIR) $(CXX) -c $(CXXFLAGS) $< -o $@ sub: $(SUBMIT_DIR) cp -t submission/\ main.cpp main.hpp\ mcts.cpp mcts.hpp\ reversi.cpp reversi.hpp\ README.md\ Makefile zip: sub zip -r 310FinalProj.zip submission clean: rm -Rf *.o *.out out build main mcts reversi submission $(BUILD_DIR): mkdir $@ $(SUBMIT_DIR): mkdir $@<file_sep>#ifndef _REVERSI_ #define _REVERSI_ #include <string> #include <vector> class Reversi { private: int boardLen; std::string board[8][8]; std::string turn; std::string oppTurn; bool didWeWin; bool didWelose; bool isGameTied; bool isGameFinished; int numX; int numO; bool simulation; enum direction {upLeft = -9, up = -8, upRight = -7, downLeft = 7, down = 8, downRight = 9, right = 1, left = -1}; public: Reversi(); void displayBoard(); void play(); void chooseMove(); bool checkWin(); int validMoves(int tile); void flipTiles(int toTile, int fromTile); bool canPlace(int toTile, int fromTile); int getTileRow(int tile); int getTileColumn(int tile); std::vector<int> getLegalMoves(); bool placePiece(int move); bool getIsGameTied(); bool getDidWeWin(); bool getDidWeLose(); bool getIsGameFinished(); std::string getTurn(); void setTurn(std::string turn); void checkOppTurn(); void setIsGameFinished(bool gameStatus); int getNumX(); int getNumO(); void setNumX(int x); void setNumO(int o); void checkNumTiles(); void setSimulation(bool sim); bool getSimulation(); // std::vector<std::vector<std::string>> getBoard(); std::string* getBoard(); enum direction getDirections(); std::string getBoardAt(int move); }; #endif<file_sep>#include <iostream> #include "reversi.hpp" #include "mcts.hpp" #include "main.hpp" void play(Reversi* game_p) { mcts AI = mcts(game_p); bool result = false; std::string inputS = ""; char input; bool optionChosen = true; AI.player_struct.heuristic = false; AI.player_struct.human = false; AI.player_struct.mcts = false; printf("You are \033[92mX\033[0m and the computer is \033[36mO\033[0m\n"); printf("the \033[93mYellow tiles\033[0m are the available moves for the current player\n"); printf("\n"); std::cout << "Please select a gamemode:" << std::endl; std::cout << "0: Player (X) vs. MCTS (O)" << std::endl; std::cout << "1: Player (X) vs. Heuristic MCTS (O)" << std::endl; std::cout << "2: MCTS (X) vs. MCTS (O)" << std::endl; std::cout << "3: MCTS (X) vs. Heuristic MCTS (O)" << std::endl; std::cout << "4: Heuristic MCTS (X) vs. Heuristic MCTS (O)" << std::endl; do { std::cin.clear(); std::cin >> input; switch (input) { case '0': AI.player_struct.human = true; AI.player_struct.mcts = true; optionChosen = true; std::cout << "Chosen: Player (X) vs. MCTS (O)" << std::endl; break; case '1': AI.player_struct.human = true; AI.player_struct.heuristic = true; optionChosen = true; std::cout << "Chosen: Player (X) vs. Heuristic MCTS (O)" << std::endl; break; case '2': AI.player_struct.mcts = true; std::cout << "Chosen: MCTS (X) vs. MCTS (O)" << std::endl; break; case '3': AI.player_struct.mcts = true; AI.player_struct.heuristic = true; optionChosen = true; std::cout << "Chosen: MCTS (X) vs. Heuristic MCTS (O)" << std::endl; break; case '4': AI.player_struct.heuristic = true; optionChosen = true; std::cout << "Chosen: Heuristic MCTS (X) vs. Heuristic MCTS (O)" << std::endl; break; default: std::cout << "Please select a valid option" << std::endl; optionChosen = false; break; } } while (!optionChosen); std::cout << "X goes first? Y/N" << std::endl; std::cin >> inputS; game_p->setSimulation(false); if (inputS == "Y" || inputS == "y") { game_p->setTurn("X"); } else { game_p->setTurn("O"); } while(!result) { game_p->displayBoard(); if (game_p->getTurn() == "X") { if (AI.player_struct.human) { game_p->chooseMove(); } else { AI.chooseMove(); } std::cout << std::endl; game_p->checkNumTiles(); std::cout << "Score: \033[92mX\033[0m: " << game_p->getNumX() << " \033[36mO\033[0m: " << game_p->getNumO() << std::endl; game_p->setTurn("O"); } else if (game_p->getTurn() == "O") { AI.chooseMove(); game_p->setTurn("X"); game_p->checkNumTiles(); std::cout << std::endl; std::cout << "Score: \033[92mX\033[0m: " << game_p->getNumX() << " \033[36mO\033[0m: " << game_p->getNumO() << std::endl; } if (game_p->checkWin()) { result = game_p->getIsGameFinished(); game_p->displayBoard(); } } std::cout << "Game finished" << std::endl; } int main(int argc, char** argv) { Reversi game; play(&game); return 0; }<file_sep># ReversiAI Reversi using Monte-Carlo Tree Search. ## How to Run ``` make ./main ``` ### Notes - If you want to see the output of the timing, you can comment back in line 136 and 137 of mcts.cpp - For the calculations, they are output to a file "out.txt" and reformatted/parsed the output to find the average per each turn.<file_sep>#ifndef __MCTS_HPP__ #define __MCTS_HPP__ #include "reversi.hpp" #include <iostream> class mcts { private: Reversi* game; public: mcts(Reversi* game); ~mcts(); std::string getName(); struct { bool human; bool heuristic; bool mcts; } player_struct; int checkOutcome(Reversi gameCopy); int doRandomPayout(int move); void chooseMove(); int heuristic(Reversi gameCopy); int checkFrontiers(int move, Reversi gameCopy); int playOutNTimes(int move); }; #endif<file_sep>#include "reversi.hpp" #include "mcts.hpp" #include <iomanip> #include <iostream> #include <string> #include <vector> Reversi::Reversi() { boardLen = 8; int tile = 0; std::string sTile = " "; for (int i = 0; i < boardLen; i++) { for (int j = 0; j < boardLen; j++) { sTile = std::to_string(tile); Reversi::board[i][j] = sTile; tile++; } } Reversi::board[3][4] = "O"; Reversi::board[3][3] = "X"; Reversi::board[4][3] = "O"; Reversi::board[4][4] = "X"; } void Reversi::displayBoard() { for (int i = 0; i < boardLen; i++) { for (int j = 0; j < boardLen; j++) { if (board[i][j] == "X") { std::cout << std::right <<std::setw(2) << " \033[92mX\033[0m" << " "; } else if (board[i][j] == "O") { std::cout << std::setw(2) << " \033[36mO\033[0m" << " "; } else if(validMoves(i*8+j) != -1) { if (i*8+j < 10) { std::cout << std::setw(2) << " \033[93m" << board[i][j] << "\033[0m" << " "; } else { std::cout << std::setw(2) << "\033[93m" << board[i][j] << "\033[0m" << " "; } } else { std::cout << std::setw(2) << board[i][j] << " "; } } std::cout << std::endl; } } int Reversi::getTileRow(int tile) { int row = tile / 8; return row; } int Reversi::getTileColumn(int tile) { int row = tile / 8; int column = tile - (row * 8); return column; } void Reversi::flipTiles(int toTile, int fromTile) { // std::string oppTurn; int diff = toTile - fromTile; int curr = fromTile; bool valid = false; if (curr < 0 || curr > 63) { valid = false; return; } Reversi::checkOppTurn(); board[getTileRow(curr)][getTileColumn(curr)] = turn; curr += diff; while (!valid) { if (curr < 0 || curr > 63) { valid = false; break; } if (board[getTileRow(curr)][getTileColumn(curr)] == oppTurn) { if ((diff == direction::upLeft || diff == direction::left || diff == direction::downLeft) && (curr % 8 == 0)) { valid = false; break; } else if ((diff == direction::upRight || diff == direction::right || diff == direction::downRight) && ((curr + 1) % 8 == 0)) { valid = false; break; } board[getTileRow(curr)][getTileColumn(curr)] = turn; curr += diff; continue; } else if (board[getTileRow(curr)][getTileColumn(curr)] == turn) { valid = true; break; } else { valid = false; break; } } } bool Reversi::canPlace(int toTile, int fromTile) { int diff = toTile - fromTile; int curr = fromTile + diff; bool valid = false; Reversi::checkOppTurn(); // board[getTileRow(curr)][getTileColumn(curr)] = turn; while (!valid) { if (curr < 0 || curr > 63) { valid = false; break; } if (board[getTileRow(curr)][getTileColumn(curr)] == oppTurn) { if ((diff == direction::upLeft || diff == direction::left || diff == direction::downLeft) && (curr % 8 == 0)) { valid = false; break; } else if ((diff == direction::upRight || diff == direction::right || diff == direction::downRight) && ((curr + 1) % 8 == 0)) { valid = false; break; } curr += diff; continue; } else if (board[getTileRow(curr)][getTileColumn(curr)] == turn) { valid = true; break; } else { valid = false; break; } } return valid; } int Reversi::validMoves(int tile) { // std::string oppTurn; int downLeft = tile + 7; int down = tile + 8; int downRight = tile + 9; int upLeft = tile - 9; int up = tile - 8; int upRight = tile - 7; int right = tile + 1; int left = tile - 1; int valid = -1; Reversi::checkOppTurn(); if (board[getTileRow(tile)][getTileColumn(tile)] == this->oppTurn) { return valid; } if ((upLeft > 0) && (tile % 8 != 0) && (board[getTileRow(upLeft)][getTileColumn(upLeft)] == oppTurn)) { if (canPlace(upLeft, tile)) { // flipTiles(upLeft, tile); valid = 0; return valid; } } if ((upRight > 0) && ((tile+1) % 8 != 0) && (board[getTileRow(upRight)][getTileColumn(upRight)] == oppTurn)) { if (canPlace(upRight, tile)) { // flipTiles(upRight, tile); valid = 1; return valid; } } if ((up > 0) && (board[getTileRow(up)][getTileColumn(up)] == oppTurn)) { if (canPlace(up, tile)) { // flipTiles(up, tile); valid = 2; return valid; } } if ((downLeft < 64) && (tile % 8 != 0) && (board[getTileRow(downLeft)][getTileColumn(downLeft)] == oppTurn)) { if (canPlace(downLeft, tile)) { // flipTiles(downLeft, tile); valid = 3; return valid; } } if ((downRight < 64) && ((tile+1) % 8 != 0) && (board[getTileRow(downRight)][getTileColumn(downRight)] == oppTurn)) { if (canPlace(downRight, tile)) { // flipTiles(downRight, tile); valid = 4; return valid; } } if ((down < 64) && (board[getTileRow(down)][getTileColumn(down)] == oppTurn)) { if (canPlace(down, tile)) { // flipTiles(down, tile); valid = 5; return valid; } } if (((tile+1) % 8 != 0) && (board[getTileRow(right)][getTileColumn(right)] == oppTurn)) { if (canPlace(right, tile)) { // flipTiles(right, tile); valid = 6; return valid; } } if ((tile % 8 != 0) && (board[getTileRow(left)][getTileColumn(left)] == oppTurn)) { if (canPlace(left, tile)) { // flipTiles(left, tile); valid = 7; return valid; } } return -1; } void Reversi::chooseMove() { std::string sTile; bool valid = false; std::string curr; while (!valid) { std::cout << "Player " << turn << ", Choose a tile" << std::endl; std::cin >> sTile; try { try { if (std::stoi(sTile) > 63) { throw std::invalid_argument("Out of bounds"); } } catch(const std::out_of_range&) { throw std::invalid_argument("Out of bounds"); } curr = board[getTileRow(std::stoi(sTile))][getTileColumn(std::stoi(sTile))]; if (curr == "X" || curr == "O") { std::cout << "Invalid tile, choose again" << std::endl; } int fromTile = std::stoi(sTile); if (placePiece(fromTile)) { break; } } catch(const std::invalid_argument&) { std::cout << "Please enter a number !!" << std::endl; } } } void Reversi::checkOppTurn() { if (Reversi::turn == "X") { Reversi::oppTurn = "O"; } else { Reversi::oppTurn = "X"; } } std::vector<int> Reversi::getLegalMoves() { std::vector<int> validMoveVec; for(int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++ ) { int tile = i*8+j; if(validMoves(tile) != -1) { if (board[getTileRow(tile)][getTileColumn(tile)] != "X" && board[getTileRow(tile)][getTileColumn(tile)] != "O") { validMoveVec.push_back(tile); } } } } return validMoveVec; } bool Reversi::placePiece(int move) { int toTile; bool didWeMakeMove = false; int valMoves = 0; while ( valMoves != -1) { valMoves = validMoves(move); switch (valMoves) { case 0: toTile = move - 9; flipTiles(toTile, move); didWeMakeMove = true; break; case 1: toTile = move - 7; flipTiles(toTile, move); didWeMakeMove = true; break; case 2: toTile = move - 8; flipTiles(toTile, move); didWeMakeMove = true; break; case 3: toTile = move + 7; flipTiles(toTile, move); didWeMakeMove = true; break; case 4: toTile = move + 9; flipTiles(toTile, move); didWeMakeMove = true; break; case 5: toTile = move + 8; flipTiles(toTile, move); didWeMakeMove = true; break; case 6: toTile = move + 1; flipTiles(toTile, move); didWeMakeMove = true; break; case 7: toTile = move - 1; flipTiles(toTile, move); didWeMakeMove = true; break; default: break; } } if (this->simulation) { if (this->getTurn() == "X") { this->setTurn("O"); } else { this->setTurn("X"); } } return didWeMakeMove; } void Reversi::checkNumTiles() { this->setNumX(0); this->setNumO(0); for(int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { int tile = i*8+j; if (board[getTileRow(tile)][getTileColumn(tile)] == "X") { int numX = getNumX(); numX++; setNumX(numX); } else if (board[getTileRow(tile)][getTileColumn(tile)] == "O") { int numO = getNumO(); numO++; setNumO(numO); } } } } bool Reversi::getIsGameFinished() { return this->isGameFinished; } void Reversi::setIsGameFinished(bool gameStatus) { Reversi::isGameFinished = true; } bool Reversi::getIsGameTied() { bool isGameTied = Reversi::isGameTied; return isGameTied; } bool Reversi::checkWin() { std::vector<int> legalMoves = this->getLegalMoves(); if (legalMoves.size() == 0) { if (this->getTurn() == "X") { this->setTurn("O"); } else { this->setTurn("X"); } legalMoves = this->getLegalMoves(); if (legalMoves.size() == 0) { this->setIsGameFinished(true); this->checkNumTiles(); return true; } else { return false; } } return false; } bool Reversi::getDidWeWin() { bool didWeWin = Reversi::didWeWin; return didWeWin; } bool Reversi::getDidWeLose() { bool didWeLose = Reversi::didWelose; return didWeLose; } std::string Reversi::getTurn() { return this->turn; } void Reversi::setTurn(std::string t) { this->turn = t; } int Reversi::getNumX() { return Reversi::numX; } int Reversi::getNumO() { return Reversi::numO; } void Reversi::setNumX(int x) { this->numX = x; } void Reversi::setNumO(int o) { this->numO = o; } void Reversi::setSimulation(bool sim) { this->simulation = sim; } bool Reversi::getSimulation() { return this->simulation; } std::string* Reversi::getBoard() { return *this->board; } std::string Reversi::getBoardAt(int move) { int row = this->getTileRow(move); int col = this->getTileColumn(move); return this->board[row][col]; }
21b0964c58a1a00a6dd1f7d78a366c132083656d
[ "Markdown", "Makefile", "C++" ]
8
C++
epolovina/cmpt310project
878bd73d6f1401fc345962147f0ef48accae35de
ea53740a4e9e25a4a6aee8764a19579360f175b7
refs/heads/master
<repo_name>mini/SOFTENG206_Assignment2<file_sep>/src/main/java/dpha900/se206/namesayer/NameSayerApp.java package dpha900.se206.namesayer; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.border.TitledBorder; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import dpha900.se206.namesayer.CreationModel.Creation; import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent; import uk.co.caprica.vlcj.discovery.NativeDiscovery; import uk.co.caprica.vlcj.player.MediaPlayer; import uk.co.caprica.vlcj.player.MediaPlayerEventAdapter; public class NameSayerApp { public static final String CREATION_DIR = "creations/"; public static final String CREATION_EXT = ".creation.mkv"; public static final String THUMBS_DIR = CREATION_DIR + "thumbs/"; public static final String THUMB_EXT = ".png"; public static final String RECORDING_PATH = CREATION_DIR + "recording.wav"; private static final String DEFAULT_TITLE = "NameSayer GUI"; private JFrame frame; private EmbeddedMediaPlayerComponent mediaPlayer; private boolean isPlayingSelected = false; private CreationModel creationModel; private JTable creationsTable; private JButton newButton; private JButton playButton; private JButton deleteButton; private JLabel thumbLabel; private Creation selectedCreation; public NameSayerApp() { buildGUI(); attachEventHandlers(); frame.setVisible(true); } private void buildGUI() { JPanel contentPane = new JPanel(new BorderLayout()); JPanel leftPane = new JPanel(new BorderLayout()); JPanel controlsPanel = new JPanel(); newButton = new JButton("New"); controlsPanel.add(newButton); playButton = new JButton("Play"); playButton.setEnabled(false); controlsPanel.add(playButton); deleteButton = new JButton("Delete"); deleteButton.setEnabled(false); controlsPanel.add(deleteButton); leftPane.add(controlsPanel, BorderLayout.NORTH); leftPane.setPreferredSize(new Dimension(300, 0)); creationModel = new CreationModel(); creationsTable = new JTable(creationModel); creationsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); leftPane.add(new JScrollPane(creationsTable), BorderLayout.CENTER); thumbLabel = new JLabel(); thumbLabel.setVisible(false); thumbLabel.setBorder(new TitledBorder("Preview")); leftPane.add(thumbLabel, BorderLayout.SOUTH); contentPane.add(leftPane, BorderLayout.WEST); mediaPlayer = new EmbeddedMediaPlayerComponent(); contentPane.add(mediaPlayer, BorderLayout.CENTER); frame = new JFrame(DEFAULT_TITLE); frame.setSize(new Dimension(1280, 720)); frame.setMinimumSize(new Dimension(900, 500)); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); frame.setContentPane(contentPane); } private void attachEventHandlers() { newButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { new NewCreationDialog(frame, creationModel); } }); playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (!isPlayingSelected) { mediaPlayer.getMediaPlayer().playMedia(selectedCreation.getPath()); } else { mediaPlayer.getMediaPlayer().pause(); } } }); deleteButton.addActionListener(new ActionListener() { private static final int DELETE = 1; public void actionPerformed(ActionEvent e) { final String[] options = { "Cancel", "Delete" }; mediaPlayer.getMediaPlayer().stop(); int response = JOptionPane.showOptionDialog(frame, "Are you sure you want to delete '" + selectedCreation.getName() + "'?", // Message "Confirm Deletion", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[0]); if (response == DELETE) { selectedCreation.delete(); selectedCreation = null; enableCreationButtons(false); } } }); creationsTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { enableCreationButtons(true); isPlayingSelected = false; if (creationsTable.getSelectedRow() != -1) { selectedCreation = creationModel.getCreation(creationsTable.getSelectedRow()); thumbLabel.setIcon(new ImageIcon(selectedCreation.getThumbPath())); thumbLabel.setVisible(true); } else { thumbLabel.setIcon(null); thumbLabel.setVisible(false); } } }); mediaPlayer.getMediaPlayer().addMediaPlayerEventListener(new MediaPlayerEventAdapter() { @Override public void playing(MediaPlayer mediaPlayer) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mediaStarted(); } }); } @Override public void paused(MediaPlayer mediaPlayer) { finished(mediaPlayer); } @Override public void finished(MediaPlayer mediaPlayer) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mediaEnded(); } }); } @Override public void error(MediaPlayer mediaPlayer) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { mediaEnded(); JOptionPane.showMessageDialog(frame, "An error occured while trying to play the file.", "Error", JOptionPane.ERROR_MESSAGE); } }); } }); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { mediaPlayer.release(); System.exit(0); } }); } private void mediaStarted() { isPlayingSelected = true; playButton.setText("Stop"); setTitle("Playing " + selectedCreation.getName()); } private void mediaEnded() { isPlayingSelected = false; setTitle(null); playButton.setText("Play"); } private void enableCreationButtons(boolean enable) { playButton.setEnabled(enable); deleteButton.setEnabled(enable); } private void setTitle(String title) { frame.setTitle(title == null ? DEFAULT_TITLE : title); } public static void main(String[] args) { new NativeDiscovery().discover(); SwingUtilities.invokeLater(new Runnable() { public void run() { new NameSayerApp(); } }); new File(THUMBS_DIR).mkdirs(); } } <file_sep>/README.md # SOFTENG206 Assignment 2 ## GUI NameSayer A program to help people pronounce names. ### Usage #### Creating a creation 1. Click the "New" button 2. Fill out the fields * Valid characters are [A-Za-z0-9 ',-_] 3. Click the record button to record for 5s * After that you can play it back * Or record again 4. If the fields are valid and the recording is done, then the save button should become enabled. 5. If the creation already exists you will be asked to overwrite or cancel #### Playing a creation 1. Select a creation from the list * You'll need to create some if its your first time 2. Click play #### Deleting a creation 1. Select a creation from the list 2. Click delete 3. Click delete again Note: You can find all created files in ./creations or ~/creations depending if the current directory is writable.
b45e53d5749a02d3608b2176f1f7aa0b9ac93ef6
[ "Markdown", "Java" ]
2
Java
mini/SOFTENG206_Assignment2
619051984a33e289c19eb053ffd74592882cd7df
e0f9d8a6694ab88c40cdd610035fb15aca579fcd
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using AutoMapper; using DutchTreat.Library2.Models.Persistent; using DutchTreat.MVC.ViewModels; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace DutchTreat.MVC.Controllers { public class OrdersMvcController : Controller { public IMapper Mapper { get; } public OrdersMvcController(IMapper mapper) { Mapper = mapper; } public async Task<IActionResult> PostAsync([FromBody]OrderViewModel orderViewModel) { if (ModelState.IsValid) { var newOrder = new Order(); newOrder = this.Mapper.Map<OrderViewModel, Order>(orderViewModel); if (newOrder.OrderDate == DateTime.MinValue) newOrder.OrderDate = DateTime.Now; var httpClient = new HttpClient(); var response = await httpClient.PostAsync( "http://localhost:50939/api/orders/", new StringContent(JsonConvert.SerializeObject(newOrder), Encoding.UTF8, "application/json")); //newOrder = JsonConvert.DeserializeObject<Order>(response.Content.ReadAsStringAsync().Result); //var newOrderViewModel = this.Mapper.Map<Order, OrderViewModel>(newOrder); return this.Redirect(""); } else return BadRequest(ModelState); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories.Interface; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace DutchTreat.Api.Controllers { public class ProductsController : ApiController<Product> { public IEntityRepository<Product> ProductRepository { get; } public ILogger<ProductsController> Logger { get; } public ProductsController(IEntityRepository<Product> productRepository, ILogger<ProductsController> logger) { this.ProductRepository = productRepository; Logger = logger; } [HttpGet("/api/products")] public override IActionResult GetAll() { try { return Ok(this.ProductRepository.GetAll()); } catch (Exception ex) { this.Logger.LogError($"Failed to get products: {ex}"); return BadRequest("Failed to get products"); } } } }<file_sep> let shopper = new StoreCustomer("Alex", "Anastopoulos"); shopper.showName();<file_sep>"# MyDutchTreat" "# MyDutchTreat" "# MyDutchTreat" <file_sep>using AutoMapper; using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models; using DutchTreat.Library2.Models.Persistent; using DutchTreat.MVC.Services; using DutchTreat.MVC.Services.Interfaces; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.IdentityModel.Tokens; using System; using System.Text; namespace DutchTreat.MVC { public class Startup { public IConfiguration Configuration { get; } public IHostingEnvironment Enviroment { get; } /// <summary> /// Initializes a new instance of the <see cref="DataBaseContext"/> class. /// </summary> public Startup(IConfiguration config, IHostingEnvironment env) { this.Configuration = config; this.Enviroment = env; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddTransient<IMailService, MailService>(); services.AddAutoMapper(); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .WithExposedHeaders("content-disposition") .AllowAnyHeader() .AllowCredentials() .SetPreflightMaxAge(TimeSpan.FromSeconds(3600))); }); services.AddDbContext<DutchContext>(cfg => { cfg.UseSqlServer(this.Configuration.GetConnectionString("DutchConnectionString")); }); services.AddIdentity<StoreUser, IdentityRole>(config => { config.User.RequireUniqueEmail = true; config.Password.RequiredLength = 8; }) .AddEntityFrameworkStores<DutchContext>(); services.AddAuthentication() .AddCookie() .AddJwtBearer(cfg => { cfg.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = this.Configuration["Tokens:Issuer"], ValidAudience = this.Configuration["Tokens:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["Tokens:Key"])) }; }); services.AddMvc(opt => { if (this.Enviroment.IsProduction() && Configuration["DisabeleSSL"] != "true") opt.Filters.Add(new RequireHttpsAttribute()); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) app.UseDeveloperExceptionPage(); else app.UseExceptionHandler("/error"); app.UseStaticFiles(); app.UseAuthentication(); app.UseCors("CorsPolicy"); app.UseMvc(cfg => { cfg.MapRoute("Default", "{controller}/{action}/{id?}", new { controller = "App", Action = "Index" }); }); } } } <file_sep>using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Net.Http; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using DutchTreat.Library2.Models.Persistent; using DutchTreat.MVC.ViewModels; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.IdentityModel.Tokens; using Newtonsoft.Json; namespace DutchTreat.MVC.Controllers { public class AccountController : Controller { public ILogger<AccountController> Logger { get; } public SignInManager<StoreUser> Manager { get; } public UserManager<StoreUser> RegisterManager { get; } public IConfiguration Configuration { get; } public AccountController(ILogger<AccountController> logger, SignInManager<StoreUser> manager, UserManager<StoreUser> registerManager, IConfiguration configuration) { this.Logger = logger; this.Manager = manager; this.RegisterManager = registerManager; this.Configuration = configuration; } public IActionResult Login() { if (this.User.Identity.IsAuthenticated) return RedirectToAction("Index", "App"); return View(); } [HttpPost] public async Task<IActionResult> Login(LoginViewModel model) { if (ModelState.IsValid) { var result = await this.Manager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, false); if (result.Succeeded) { if (Request.Query.Keys.Contains("ReturnUrl")) return Redirect(Request.Query["ReturnUrl"].First()); else return RedirectToAction("Shop", "App"); } } ModelState.AddModelError("", "Failed to login"); return this.View(); } public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new StoreUser() { FirstName = model.UserName, LastName = model.LastName, Email = model.Email, UserName = model.UserName }; var result = await this.RegisterManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (Request.Query.Keys.Contains("ReturnUrl")) return Redirect(Request.Query["ReturnUrl"].First()); else return RedirectToAction("Shop", "App"); } else ModelState.AddModelError("", "Failed to register"); } return this.View(); } public async Task<IActionResult> Logout() { if (User.Identity.IsAuthenticated) { await this.Manager.SignOutAsync(); } return RedirectToAction("Index", "App"); } [HttpPost] public async Task<IActionResult> CreateToken([FromBody] LoginViewModel model) { if (ModelState.IsValid) { var user = await this.RegisterManager.FindByNameAsync(model.UserName); if (user != null) { var result = await this.Manager.CheckPasswordSignInAsync(user, model.Password, false); if (result.Succeeded) { //Create the token var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.Email), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName) }; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["Tokens:Key"])); var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( this.Configuration["Tokens:Issuer"], this.Configuration["Tokens:Audience"], claims, expires: DateTime.Now.AddHours(3), signingCredentials: credentials ); var results = new { token = new JwtSecurityTokenHandler().WriteToken(token), expiration = token.ValidTo }; return Created("", results); } } } return BadRequest(); } } }<file_sep>using DutchTreat.Library2.Models; using DutchTreat.Library2.Models.Persistent; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Text; namespace DutchTreat.Library2.DBContext { public class DutchContext : IdentityDbContext<StoreUser> { /// <summary> /// Initializes a new instance of the <see cref="DataBaseContext"/> class. /// </summary> public DutchContext(DbContextOptions<DutchContext> options, ILogger<DutchContext> logger) : base(options) { } public DbSet<Product> Products { get; set; } public DbSet<Order> Orders { get; set; } public DbSet<OrderItem> OrderItems { get; set; } } } <file_sep>using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories.Interface; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Library2.Repositories { public class OrdersRepository : IEntityRepository<Order> { public DutchContext DutchContext { get; } public ILogger Logger { get; } public OrdersRepository(DutchContext dutchContext, ILogger<OrdersRepository> logger) { this.DutchContext = dutchContext; this.Logger = logger; } public void AddEntity(Order order) { try { this.Logger.LogInformation("The add entity was called"); this.DutchContext.Add(order); } catch (Exception ex) { this.Logger.LogError($"Failed to get all orders: {ex}"); } } public void DeleteEntity(int id) { var localOrder = this.DutchContext.Orders .Include(order => order.Items) .SingleOrDefault(order => order.Id == id); if (localOrder == null) throw new ArgumentException(); if (localOrder.Items.Count > 0) { localOrder.Items.ToList().ForEach(item => { this.DutchContext.OrderItems.Remove(item); }); } this.DutchContext.Orders.Remove(localOrder); } public IEnumerable<Order> GetAll() { try { this.Logger.LogInformation("The get orders was called"); return this.DutchContext.Orders .Include(order => order.Items) .ThenInclude(orderItem => orderItem.Product) .ToList(); } catch (Exception ex) { this.Logger.LogError($"Failed to get all orders: {ex}"); return null; } } public IEnumerable<Order> GetByUserName(string username) { try { this.Logger.LogInformation("The get orders by username was called"); return this.DutchContext.Orders .Where(order => order.User.UserName == username) .Include(order => order.Items) .ThenInclude(orderItem => orderItem.Product) .ToList(); } catch (Exception ex) { this.Logger.LogError($"Failed to get all orders: {ex}"); return null; } } public Order GetEntityByName(string EntityName, string username) { throw new NotImplementedException(); } public async Task<bool> SaveChangesAsync() { return (await this.DutchContext.SaveChangesAsync() > 0); } public void UpdateEntity(Order entity) { //Convert new products to lookup of product entity.Items.ToList().ForEach(item => { item.Product = this.DutchContext.Products.Find(item.Product.Id); }); AddEntity(entity); } public Order GetEntityById(int id) { try { this.Logger.LogInformation("The get orders was called"); return this.DutchContext.Orders .Include(order => order.Items) .ThenInclude(orderItem => orderItem.Product) .Where(order => order.Id == id) .FirstOrDefault(); } catch (Exception ex) { this.Logger.LogError($"Failed get all orders: {ex}"); return null; } } public Order GetEntityByIdAndUserName(string username, int id) { try { this.Logger.LogInformation("The get orders was called"); return this.DutchContext.Orders .Where(order => order.Id == id && order.User.UserName == username) .Include(order => order.Items) .ThenInclude(orderItem => orderItem.Product) .FirstOrDefault(); } catch (Exception ex) { this.Logger.LogError($"Failed get all orders: {ex}"); return null; } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models; using DutchTreat.Library2.Models.Data; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories; using DutchTreat.Library2.Repositories.Interface; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; namespace DutchTreat.Api { public class Startup { public IConfiguration Configuration { get; } /// <summary> /// Initializes a new instance of the <see cref="DataBaseContext"/> class. /// </summary> public Startup(IConfiguration config) { this.Configuration = config; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddTransient<IEntityRepository<Product>, ProductsRepository>(); services.AddTransient<IEntityRepository<Order>, OrdersRepository>(); services.AddTransient<IEntityRepository<StoreUser>, StoreUserRepository>(); services.AddDbContext<DutchContext>(cfg => { cfg.UseSqlServer(this.Configuration.GetConnectionString("DutchConnectionString")); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .WithExposedHeaders("content-disposition") .AllowAnyHeader() .AllowCredentials() .SetPreflightMaxAge(TimeSpan.FromSeconds(3600))); }); services.AddTransient<DutchSeeder>(); services.AddIdentity<StoreUser, IdentityRole>(config => { config.User.RequireUniqueEmail = true; config.Password.RequiredLength = 8; }) .AddEntityFrameworkStores<DutchContext>(); services.AddAuthentication() .AddCookie() .AddJwtBearer(cfg => { cfg.TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = this.Configuration["Tokens:Issuer"], ValidAudience = this.Configuration["Tokens:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(this.Configuration["Tokens:Key"])) }; }); services.AddMvc() .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //seed the dataBase using (var scope = app.ApplicationServices.CreateScope()) { var seeder = scope.ServiceProvider.GetService<DutchSeeder>(); seeder.Seed().Wait(); } } app.UseAuthentication(); app.UseCors("CorsPolicy"); app.UseMvc(cfg => { cfg.MapRoute("Default", "{controller}/{action}/{id?}", new { controller = "Products", Action = "GetAll" }); }); } } } <file_sep>using DutchTreat.Library2.Models.Persistent.Interfaces; namespace DutchTreat.Library2.Models.Persistent { public class OrderItem : IEntity { public int Id { get; set; } public Product Product { get; set; } public int Quantity { get; set; } public decimal UnitPrice { get; set; } public Order Order { get; set; } } }<file_sep>using DutchTreat.Library2.Models.Persistent.Interfaces; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Api.Controllers { public abstract class ApiController<T> : Controller where T : IEntity { public virtual IActionResult GetAll() { throw new NotImplementedException(); } public virtual IActionResult GetById(string username, int id) { throw new NotImplementedException(); } public virtual IActionResult GetByUsernameOrEmail(T entity) { throw new NotImplementedException(); } public virtual Task<IActionResult> Post(T entity) { throw new NotImplementedException(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories.Interface; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace DutchTreat.Api.Controllers { [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] public class OrdersController : ApiController<Order> { public IEntityRepository<Order> OrdersRepository { get; } public ILogger<OrdersController> Logger { get; } public UserManager<StoreUser> UserManager { get; } public OrdersController(IEntityRepository<Order> ordersRepository, ILogger<OrdersController> logger, UserManager<StoreUser> userManager) { this.OrdersRepository = ordersRepository; this.Logger = logger; this.UserManager = userManager; } [HttpGet("/api/orders")] public override IActionResult GetAll() { try { return Ok(this.OrdersRepository.GetByUserName(User.Identity.Name)); } catch (Exception ex) { this.Logger.LogError($"Failed to get orders: {ex}"); return BadRequest("Failed to get orders"); } } [HttpGet("/api/orders/{id}")] public override IActionResult GetById(string username, int id) { try { var order = this.OrdersRepository.GetEntityByIdAndUserName(User.Identity.Name, id); if (order != null) return Ok(order); else return NotFound(); } catch (Exception ex) { this.Logger.LogError($"Failed to get order: {ex}"); return BadRequest("Failed to get order"); } } [HttpPost("/api/orders")] public override async Task<IActionResult> Post([FromBody]Order order) { try { order.User = await this.UserManager.FindByNameAsync(User.Identity.Name); this.OrdersRepository.AddEntity(order); if (await this.OrdersRepository.SaveChangesAsync()) return Created($"/api/orders/{order.Id}", order); } catch (Exception ex) { this.Logger.LogError($"Failed to save the order: {ex}"); } return BadRequest("Failed to save the new order"); } /// <summary> /// Deletes orders. /// </summary> /// <param name="order"> /// The order. /// </param> /// <returns> /// The <see cref="IActionResult"/>. /// </returns> [HttpPost("/api/orders/delete")] public async Task<IActionResult> Delete([FromBody]Order order) { this.OrdersRepository.DeleteEntity(order.Id); if (await this.OrdersRepository.SaveChangesAsync()) { return this.Ok("The order removed successfully"); } else return BadRequest("Failed to store changes to database"); } } }<file_sep>using AutoMapper; using DutchTreat.Library2.Models.Persistent; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.MVC.ViewModels.Mappings { public class DutchMappingProfile: Profile { public DutchMappingProfile() => CreateMap<Order, OrderViewModel>() .ForMember(order=> order.OrderId, ex => ex.MapFrom(or => or.Id)) .ReverseMap(); } } <file_sep>import { Component, OnInit } from "@angular/core"; import { DataService } from "../shared/dataService"; import { Router } from "@angular/router"; import { Order } from "../shared/order"; @Component({ selector: "order-list", templateUrl: "orderList.component.html", styleUrls: ["orderList.component.css"] }) export class OrderList implements OnInit{ public orders: Order[]; constructor(public data: DataService, public router: Router) { } errorMessage: string = ""; ngOnInit(): void { this.data.getOrders() .subscribe(() => this.orders = this.data.orders); } deleteOrder(order: Order) { this.data.deleteOrder(order) .subscribe(success => { if (success) { this.router.navigate(["/"]); } }, err => this.errorMessage = "Failed to save order"); } }<file_sep>using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models.Persistent; using DutchTreat.MVC.Services.Interfaces; using DutchTreat.MVC.ViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace DutchTreat.MVC.Controllers { public class AppController: Controller { private readonly IMailService localMailService; public AppController(IMailService mailService) { this.localMailService = mailService; } public IActionResult Index() { return this.View(); } [HttpGet("contact")] public IActionResult Contact() { ViewBag.Title = "Contact Us"; return this.View(); } [HttpPost("contact")] public IActionResult Contact(ContactViewModel model) { if (ModelState.IsValid) { //this.localMailService.SendMail(model.Email, "<EMAIL>", model.Subject, model.Message); this.localMailService.SendMessage("<EMAIL>", model.Subject, $"From: {model.Name} - {model.Email}, Message:{model.Message}"); ViewBag.UserMessage = "Mail Sent"; ModelState.Clear(); } return this.View(); } public IActionResult About() { ViewBag.Title = "About Us"; return this.View(); } public IActionResult Shop() { List<Product> products = null; var httpClient = new HttpClient(); var response = httpClient.GetAsync("http://localhost:50939/api/products").Result; if (response.IsSuccessStatusCode) { var stateInfo = response.Content.ReadAsStringAsync().Result; products = JsonConvert.DeserializeObject<List<Product>>(stateInfo); return this.View(products); } else return BadRequest("Couldn't connect to database"); } } } <file_sep>using DutchTreat.MVC.Services.Interfaces; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace DutchTreat.MVC.Services { public class MailService : IMailService { private readonly ILogger<MailService> localLogger; public MailService(ILogger<MailService> logger) { this.localLogger = logger; } public void SendMessage(string to, string subject, string body) { this.localLogger.LogInformation($"To: {to}, Subject: {subject}, Body: {body}"); } public void SendMail(string from, string to, string subject, string body) { MailMessage mail = new MailMessage(from, to); SmtpClient client = new SmtpClient { Port = 25, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, Credentials = new NetworkCredential("datacom_psagianos", "welcome1!", "axa"), Host = "smtp.gmail.com" }; mail.Subject = subject; mail.Body = body; client.Send(mail); } } } <file_sep>using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories.Interface; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Library2.Repositories { public class ProductsRepository : IEntityRepository<Product> { private readonly DutchContext localDutchContext; public ILogger<ProductsRepository> Logger { get; } public ProductsRepository(DutchContext dutchContext, ILogger<ProductsRepository> logger) { this.localDutchContext = dutchContext; Logger = logger; } public void AddEntity(Product entity) { throw new NotImplementedException(); } public void DeleteEntity(int entity) { throw new NotImplementedException(); } public IEnumerable<Product> GetAll() { try { this.Logger.LogInformation("Get all was called"); return this.localDutchContext.Products .OrderBy(prod => prod.Title) .ToList(); } catch (Exception ex) { this.Logger.LogError($"Failed to get all products: {ex}"); return null; } } public IEnumerable<Product> GetAllProductsByCategory() { try { this.Logger.LogInformation("Get all products by category was called"); return this.localDutchContext.Products .OrderBy(prod => prod.Category) .ToList(); } catch (Exception ex) { this.Logger.LogError($"Failed to get all products: {ex}"); return null; } } public IEnumerable<Product> GetByUserName(string username) { throw new NotImplementedException(); } public Product GetEntityByName(string EntityName, string username) { throw new NotImplementedException(); } public async Task<bool> SaveChangesAsync() { return (await this.localDutchContext.SaveChangesAsync() > 0); } public void UpdateEntity(Product entity) { throw new NotImplementedException(); } public Product GetEntityById(int id) { throw new NotImplementedException(); } public Product GetEntityByIdAndUserName(string username, int id) { throw new NotImplementedException(); } } } <file_sep>using DutchTreat.Library2.Models.Persistent.Interfaces; using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Library2.Models.Persistent { public class StoreUser : IdentityUser, IEntity { public string FirstName { get; set; } public string LastName { get; set; } int IEntity.Id { get; set; } } } <file_sep>namespace DutchTreat.MVC.Services.Interfaces { public interface IMailService { void SendMail(string from, string to, string subject, string body); void SendMessage(string to, string subject, string body); } }<file_sep>using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories.Interface; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Library2.Repositories { public class StoreUserRepository : IEntityRepository<StoreUser> { public DutchContext DutchContext { get; } public ILogger<StoreUserRepository> Logger { get; } public StoreUserRepository(DutchContext dutchContext, ILogger<StoreUserRepository> logger) { this.DutchContext = dutchContext; this.Logger = logger; } public void AddEntity(StoreUser entity) { throw new NotImplementedException(); } public void DeleteEntity(int entity) { throw new NotImplementedException(); } public IEnumerable<StoreUser> GetAll() { return this.DutchContext.Users; } public IEnumerable<StoreUser> GetByUserName(string username) { return this.DutchContext.Users; } public StoreUser GetEntityById(int id) { throw new NotImplementedException(); } public StoreUser GetEntityByName(string username, string email) { try { this.Logger.LogInformation("Get user by name was called"); return this.DutchContext.Users.Where(user => (user.Email == email) || (user.UserName == username)).FirstOrDefault(); } catch (Exception ex) { this.Logger.LogError($"Failed to get current user: {ex}"); return null; } } public Task<bool> SaveChangesAsync() { throw new NotImplementedException(); } public void UpdateEntity(StoreUser entity) { throw new NotImplementedException(); } public StoreUser GetEntityByIdAndUserName(string username, int id) { throw new NotImplementedException(); } } } <file_sep>using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models.Persistent; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Library2.Models.Data { public class DutchSeeder { public DutchContext DutchContext { get; } public IHostingEnvironment Hosting { get; } public UserManager<StoreUser> Manager { get; } public DutchSeeder(DutchContext dutchContext, IHostingEnvironment hosting, UserManager<StoreUser> manager) { this.DutchContext = dutchContext; this.Hosting = hosting; Manager = manager; } public async Task Seed() { this.DutchContext.Database.EnsureCreated(); var user = await this.Manager.FindByEmailAsync("<EMAIL>"); if (user == null) { user = new StoreUser() { FirstName = "Alex", LastName = "Anastopoulos", Email = "<EMAIL>", UserName = "Dark_Ark" }; var result = await this.Manager.CreateAsync(user, "Passw0rd!"); if (result != IdentityResult.Success) throw new InvalidOperationException("Failed to create user"); } if (!this.DutchContext.Products.Any()) { //Creating sample data var filepath = Path.Combine("Models/Data/art.json"); var json = File.ReadAllText(filepath); var products = JsonConvert.DeserializeObject<IEnumerable<Product>>(json); this.DutchContext.AddRange(products); var order = new List<Order>() { new Order() { OrderDate = DateTime.Now, OrderNumber = "123456", Items = new List<OrderItem>() { new OrderItem() { Product = products.First(), Quantity = 5, UnitPrice = products.First().Price }, new OrderItem() { Product = products.Skip(1).First(), Quantity = 10, UnitPrice = products.Skip(1).First().Price }, new OrderItem() { Product = products.Skip(3).First(), Quantity = 5, UnitPrice = products.Skip(3).First().Price }, new OrderItem() { Product = products.Skip(4).First(), Quantity = 8, UnitPrice = products.Skip(4).First().Price }, new OrderItem() { Product = products.Skip(5).First(), Quantity = 15, UnitPrice = products.Skip(5).First().Price } }, User = user }, new Order() { OrderDate = DateTime.Now, OrderNumber = "456786", Items = new List<OrderItem>() { new OrderItem() { Product = products.Last(), Quantity = 5, UnitPrice = products.Last().Price }, new OrderItem() { Product = products.Skip(3).First(), Quantity = 10, UnitPrice = products.Skip(3).First().Price }, new OrderItem() { Product = products.Skip(2).First(), Quantity = 5, UnitPrice = products.Skip(2).First().Price }, new OrderItem() { Product = products.Skip(4).First(), Quantity = 8, UnitPrice = products.Skip(4).First().Price }, new OrderItem() { Product = products.Skip(1).First(), Quantity = 15, UnitPrice = products.Skip(1).First().Price } }, User = user }, new Order() { OrderDate = DateTime.Now, OrderNumber = "89765", Items = new List<OrderItem>() { new OrderItem() { Product = products.First(), Quantity = 5, UnitPrice = products.First().Price }, new OrderItem() { Product = products.Skip(2).First(), Quantity = 10, UnitPrice = products.Skip(2).First().Price }, new OrderItem() { Product = products.Skip(1).First(), Quantity = 5, UnitPrice = products.Skip(1).First().Price }, new OrderItem() { Product = products.Skip(6).First(), Quantity = 8, UnitPrice = products.Skip(6).First().Price }, new OrderItem() { Product = products.Skip(5).First(), Quantity = 15, UnitPrice = products.Skip(5).First().Price } }, User = user } }; this.DutchContext.Orders.AddRange(order); this.DutchContext.SaveChanges(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DutchTreat.Library2.DBContext; using DutchTreat.Library2.Models.Data; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories; using DutchTreat.Library2.Repositories.Interface; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace DutchTreat.Library2 { public class Startup { private readonly IConfiguration localConfig; /// <summary> /// Initializes a new instance of the <see cref="DataBaseContext"/> class. /// </summary> public Startup(IConfiguration config) { this.localConfig = config; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddIdentity<StoreUser, IdentityRole>(config => { config.User.RequireUniqueEmail = true; config.Password.RequiredLength = 8; }) .AddEntityFrameworkStores<DutchContext>(); services.AddDbContext<DutchContext>(cfg=> { cfg.UseSqlServer(this.localConfig.GetConnectionString("DutchConnectionString")); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .WithExposedHeaders("content-disposition") .AllowAnyHeader() .AllowCredentials() .SetPreflightMaxAge(TimeSpan.FromSeconds(3600))); }); services.AddTransient<IEntityRepository<Product>, ProductsRepository>(); services.AddTransient<IEntityRepository<Order>, OrdersRepository>(); services.AddTransient<IEntityRepository<StoreUser>, StoreUserRepository>(); services.AddTransient<DutchSeeder>(); services.AddMvc() .AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); //seed the dataBase using (var scope = app.ApplicationServices.CreateScope()) { var seeder = scope.ServiceProvider.GetService<DutchSeeder>(); seeder.Seed().Wait(); } } app.UseCors("CorsPolicy"); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } } <file_sep>using DutchTreat.Library2.Models.Persistent.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DutchTreat.Library2.Repositories.Interface { public interface IEntityRepository<T> where T:IEntity { /// <summary> /// The get all trips. /// </summary> /// <returns> /// The <see cref="IEnumerable"/>. /// </returns> IEnumerable<T> GetByUserName(string username); IEnumerable<T> GetAll(); void AddEntity(T entity); void UpdateEntity(T entity); Task<bool> SaveChangesAsync(); T GetEntityByName(string EntityName, string username); T GetEntityById(int id); T GetEntityByIdAndUserName(string username, int id); void DeleteEntity(int entity); } } <file_sep>import * as _ from "lodash"; export class Order { orderId: number; orderDate: Date = new Date(); orderNumber: string; items: Array <OrderItem> = new Array<OrderItem>(); user: User = new User(); get subtotal(): number { return _.sum(_.map(this.items, i => i.unitPrice * i.quantity)); }; } export class OrderItem { id: number; quantity: number; unitPrice: number; productId: number; productCategory: string; productSize: string; productTitle: string; productArtist: string; productArtId: string; } export class User { firstName: string; lastName: string; id: string; userName: string; normalizedUserName: string; email: string; normalizedEmail: string; emailConfirmed: boolean; passwordHash: string; securityStamp: string; concurrencyStamp: string; phoneNumber?: any; phoneNumberConfirmed: boolean; twoFactorEnabled: boolean; lockoutEnd?: any; lockoutEnabled: boolean; accessFailedCount: number; } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DutchTreat.Library2.Models.Persistent; using DutchTreat.Library2.Repositories.Interface; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace DutchTreat.Api.Controllers { public class StoreUserController : ApiController<StoreUser> { public IEntityRepository<StoreUser> EntityRepository { get; } public ILogger<StoreUserController> Logger { get; } public StoreUserController(IEntityRepository<StoreUser> entityRepository, ILogger<StoreUserController> logger) { this.EntityRepository = entityRepository; this.Logger = logger; } [HttpGet("/api/storeuser")] public override IActionResult GetAll() { try { var user = new StoreUser(); return Ok(this.EntityRepository.GetEntityByName(user.UserName, user.Email)); } catch (Exception ex) { this.Logger.LogError($"Failed to get current user: {ex}"); return BadRequest("Failed to get current user"); } } [HttpPost("/api/storeuser")] public override IActionResult GetByUsernameOrEmail([FromBody]StoreUser user) { try { return Ok(this.EntityRepository.GetEntityByName(user.UserName, user.Email)); } catch (Exception ex) { this.Logger.LogError($"Failed to get current user: {ex}"); return BadRequest("Failed to get current user"); } } ////[HttpPost("/api/storeuser")] //public override async Task<IActionResult> Post([FromBody]StoreUser user) //{ // try // { // this.EntityRepository.AddEntity(user); // if (await this.EntityRepository.SaveChangesAsync()) // return Created($"/api/orders/{user.Id}", user); // } // catch (Exception ex) // { // this.Logger.LogError($"Failed to save the order: {ex}"); // } // return BadRequest("Failed to save the new order"); //} } }
c9d81208ecd41b8101daf6066d418287690d9d7a
[ "Markdown", "C#", "TypeScript" ]
25
C#
Alanastop/MyDutchTreat
b31dc71b879ec65616618e91839d58717d137248
eada3ca1ed64e891adabc0aca83cf112d4e5429e
refs/heads/master
<file_sep>rootProject.name='Lab04part01' include ':app' <file_sep>package com.example.lab04part01; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; public class DownloadActivity extends AppCompatActivity { public static final String KEY_DRAWABLE = "keyDrawable"; private ProgressBar progressBar; private TextView textView; private ImageView imageView; private int progressStatus; private static int staticStatus; private Handler handler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); progressBar = findViewById(R.id.progressBar); textView = findViewById(R.id.textView); imageView = findViewById(R.id.imageView); imageView.setVisibility(View.GONE); // Gone means removed, Invisible means still, cannot see staticStatus = 0; new Thread(new Runnable() { @Override public void run() { while(progressStatus < 100) { progressStatus = downloadImage(); // update the progressStatus handler.post(new Runnable() { // set another thread to update the progress bar @Override public void run() { progressBar.setProgress(progressStatus); } }); } if(progressStatus == 100) { // when status is 100% handler.post(new Runnable() { // another thread to change the visibility @Override public void run() { progressBar.setVisibility(View.GONE); textView.setVisibility(View.GONE); imageView.setVisibility(View.VISIBLE); imageView.setImageResource(R.drawable.ultraman); } }); } } private int downloadImage() { // simulating the download // in an actual app, this is where the download takes place try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } return ++staticStatus; } }).start(); // start the thread running } public void onReturnClick(View view) { Intent intent = new Intent(); intent.putExtra(KEY_DRAWABLE, R.drawable.ultraman); setResult(RESULT_OK, intent); finish(); } }
2d3f3d925f6c81de7bf027ebaf86ef184a1004e5
[ "Java", "Gradle" ]
2
Gradle
breakfastset/aad_Lab04part01
dedd777c27b106e793845087c4e2f7b183e4c882
264d738843f54d0add16d3e17a8e57fbb345b540
refs/heads/master
<file_sep>import React from 'react'; import {fetchCurrentBusinessInfo} from '../../actions/businesses_actions'; import {createNewTicket} from '../../actions/tickets_actions'; import {connect} from 'react-redux'; import {withRouter} from 'react-router-dom'; const mapDispatchToProps = (dispatch) => ({ fetchCurrentBusinessInfo: (business_id) => dispatch(fetchCurrentBusinessInfo(business_id)), createNewTicket: (data, business_id) => dispatch(createNewTicket(data, business_id)) }) const mapStateToProps = (state) => ({ current_business: state.entities.current_business, current_business_id: state.ui.current_business_id, show_customer: state.entities.show_customer }) class NewTicketForm extends React.Component{ constructor(props){ super(props) this.state = { bag_weight: 0.0, total_price: 0.0 } this.handleChange = this.handleChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) } componentDidMount(){ this.props.fetchCurrentBusinessInfo(this.props.current_business_id) } handleChange(e){ let total_price = Math.round((this.props.current_business.price_per_pound * e.target.value) * 100) / 100 this.setState({[e.target.name]: e.target.value, total_price: total_price}) } handleSubmit(e){ e.preventDefault() let date = new Date() let data = { business_id: this.props.current_business_id, customer_id: this.props.show_customer.id, date_dropped_off: date.toDateString(), time_dropped_off: date, bag_weight: this.state.bag_weight, grand_total: this.state.total_price } this.props.createNewTicket(data, this.props.current_business_id).then( () => this.props.history.push('/dashboard/tickets') ) } render(){ return( <form onSubmit={this.handleSubmit} class="form"> <label className="form__label-and-field"> Bag weight (lb) <input type="number" value={this.state.bag_weight} name="bag_weight" onChange={this.handleChange} /> </label> <label className="form__label-and-field"> Total <h2>{this.state.total_price}</h2> </label> <input type="submit" /> </form> ) } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(NewTicketForm));<file_sep>class CreateTickets < ActiveRecord::Migration[5.2] def change create_table :tickets do |t| t.integer :business_id, null:false t.integer :customer_id, null:false t.integer :status_id, null:false t.date :date_dropped_off, null:false t.time :time_dropped_off, null:false t.date :date_fulfilled, null:true t.time :time_filfilled, null:true t.integer :note_id, null:true t.float :bag_weight, null:true t.float :grand_total, null:false t.integer :ticket_type_id, null:false t.timestamps end end end <file_sep>class EditTicketColumnName < ActiveRecord::Migration[5.2] def change remove_column :tickets, :deliver_method_id add_column :tickets, :delivery_method_id, :integer, null:false end end <file_sep>import React from "react" import { withScriptjs, withGoogleMap, GoogleMap, Marker} from "react-google-maps" class Gmap extends React.PureComponent { constructor(props) { super(props); this.state = { map: null, // default_center: { lat: 40.7484, lng: -73.9967 }, // center: { lat: 40.7484, lng: -73.9967 }, // markers: [] } } // componentDidUpdate(prevProps) { // if(this.props.business_on_map && // (this.props.business_on_map.id != prevProps.business_on_map.id)){ // this.setState({ center: { // lat: Number(this.props.business_on_map.latitude), // lng: Number(this.props.business_on_map.longitude) // }}) // } // } mapLoaded(map) { if (this.state.map == null) { this.setState({ map: map }) } } render() { let marker_view = <Marker position={{ lat: Number(this.props.business_on_map.latitude), lng: Number(this.props.business_on_map.longitude) }} /> return ( <GoogleMap ref={this.mapLoaded.bind(this)} defaultZoom={13} defaultCenter={this.state.default_center} center={this.props.center} defaultOptions={{ styles: [{ featureType: "poi", elementType: "labels", stylers: [ { visibility: "off" } ] }, { featureType: "road", elementType: "all", stylers: [ { visibility: "off" } ] }, { featureType: "transit", elementType: "all", stylers: [ { visibility: "off" } ] }], streetViewControl: false, mapTypeControl: false }} > {this.props.isMarkerShown && marker_view} </GoogleMap> ) } } export default withScriptjs(withGoogleMap(Gmap))<file_sep>class WeightValidator < ActiveModel::EachValidator # if ticket type involves a Laundry Bag, ensure that bag_wieght is not blank def validate_each(record, attribute, value) unless TicketType.find(record.ticket_type_id).type_name == "Dry Cleaning" if record[attribute].blank? record.errors[attribute] << "bag weight can't be blank" end end end end class Ticket < ApplicationRecord include PgSearch # default_scope {order(created_at: :asc)} pg_search_scope :id_scope, :against => [:id], :using => { :tsearch => {:prefix => true} } pg_search_scope :global_scope, :associated_against => { :customer => [:first_name, :last_name], :status => [:status_name], }, :against => [:id], :using => { :tsearch => {:prefix => true} } pg_search_scope :customer_name_scope, :associated_against => { :customer => [:first_name, :last_name] }, :using => { :tsearch => {:prefix => true} } validates :business_id, :customer_id, :status_id, :date_dropped_off, :time_dropped_off, :grand_total, :bag_weight, presence:true # validates :bag_weight, weight: true belongs_to :business, class_name: 'Business', foreign_key: :business_id, primary_key: :id belongs_to :customer, class_name: 'Customer', foreign_key: :customer_id, primary_key: :id belongs_to :status, class_name: 'Status', foreign_key: :status_id # belongs_to :ticket_type, # class_name: 'TicketType', # foreign_key: :ticket_type_id, # primary_key: :id # belongs_to :delivery_method, # class_name: 'DeliveryMethod', # foreign_key: :delivery_method_id, # primary_key: :id # has_one :note, # class_name: 'Note', # foreign_key: :ticket_id def self.search_by_global_scope(business_id, query, status) status = Status.where("status_name = ?", status.capitalize).first return Ticket.where("business_id = ? AND status_id = ?", business_id, status.id).global_scope(query) end def self.search_by_id_scope(business_id, query, status) status = Status.where("status_name = ?", status.capitalize).first return Ticket.where("business_id = ? AND status_id = ?", business_id, status.id).id_scope(query) end def self.search_by_customer_scope(business_id, query, status) status = Status.where("status_name = ?", status.capitalize).first return Ticket.where("business_id = ? AND status_id = ?", business_id, status.id).customer_name_scope(query) end def self.status_tickets_by_page_number(business_id, page, status) return nil unless page >= 0 ticket_per_page = 3 tickets_offset = page * ticket_per_page status = Status.where("status_name = ?", status.capitalize).first return Ticket.where("business_id = ? AND status_id = ?", business_id, status.id) .limit(ticket_per_page) .offset(tickets_offset) .order(created_at: :desc) end def set_to_unfulfilled! status = Status.where("status_name = ?", "Unfulfilled").first self.status_id = status.id end def change_status_to_notified! status = Status.where("status_name = ?", "Notified").first self.status_id = status.id self.save! end def fulfill! status = Status.where("status_name = ?", "Fulfilled").first self.status_id = status.id self.save! end end <file_sep>json.extract! @business, :name, :user_id, :business_type_id, :latitude, :longitude, :street_address, :price_per_pound, :zip_code, :city, :state json.owner_first_name @business.owner.first_name json.owner_last_name @business.owner.last_name json.business_type @business.business_type.type_name<file_sep>class AddColumnToTickets < ActiveRecord::Migration[5.2] def change add_column :tickets, :deliver_method_id, :integer, null:false end end <file_sep>json.extract! ticket, :id, :business_id, :date_dropped_off, :time_dropped_off, :date_fulfilled, :time_fulfilled, :bag_weight, :grand_total, :customer_id, :status_id, :ticket_type_id, :delivery_method_id json.customer_first_name ticket.customer.first_name json.customer_last_name ticket.customer.last_name <file_sep>json.extract! @customer, :id, :first_name, :last_name, :email_address, :phone_number, :street_address, :zip_code, :apt_number, :business_id<file_sep>class Api::BusinessesController < ApplicationController def index @businesses = Business.where("user_id = ?", params[:user_id]) render 'api/businesses/index' end def create @business = Business.new(business_params) @business.user_id = params[:user_id] if @business.save render 'api/businesses/show' else render json: @business.errors.messages, status: 400 end end def show @business = Business.includes(:owner, :business_type).find(params[:id]) render 'api/businesses/show' end def search @businesses = Business.where("user_id = ?", params[:user_id]).name_search(params[:q]) render 'api/businesses/index' end private def business_params params.require(:business).permit( :name, :business_type_id, :latitude, :street_address, :price_per_pound, :zip_code, :city, :state, :longitude ) end end <file_sep>import React from 'react'; import { withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; import { fetchShowTicket, clearShowTicket, notifyCustomer, fulfillTicket } from '../../actions/tickets_actions'; const mapStateToProps = (state) => ({ show_ticket: state.entities.show_ticket }) const mapDispatchToProps = (dispatch) => ({ fetchShowTicket: (ticket_id) => dispatch(fetchShowTicket(ticket_id)), clearShowTicket: () => dispatch(clearShowTicket()), notifyCustomer: (ticket_id) => dispatch(notifyCustomer(ticket_id)), fulfillTicket: (ticket_id) => dispatch(fulfillTicket(ticket_id)) }) class TicketView extends React.Component{ constructor(props){ super(props); this.state = { notification_response: null } this.renderTicket = this.renderTicket.bind(this); this.goBack = this.goBack.bind(this); this.sendNotification = this.sendNotification.bind(this); this.fulfillTicket = this.fulfillTicket.bind(this); } componentDidMount(){ this.props.fetchShowTicket(this.props.match.params.ticket_id) } renderTicket(){ if(this.props.show_ticket){ return( <div className="ticket-view__ticket-info"> <h1>id: {this.props.show_ticket.id}</h1> <h1>drop-off-date: {this.props.show_ticket.date_dropped_off}</h1> <h1>status: {this.props.show_ticket.status}</h1> <h1>customer: {this.props.show_ticket.customer_first_name} {this.props.show_ticket.customer_last_name}</h1> <h1>bag weight: {this.props.show_ticket.bag_weight} lb</h1> <h1>grand total: ${this.props.show_ticket.grand_total}</h1> </div> ) } } componentWillUnmount(){ this.props.clearShowTicket() } goBack(){ this.props.history.push('/dashboard/tickets') } sendNotification(){ this.props.notifyCustomer(this.props.show_ticket.id).then( ()=>{this.setState({notification_response: 'Notified customer!'}), ()=>{this.setState({notification_response: 'An error occured'})} }) } fulfillTicket(){ this.props.fulfillTicket(this.props.show_ticket.id).then( () => this.setState({notification_response: 'Ticket fulfilled!'}) ) } renderNotificationResponse(){ if(this.state.notification_response){ return( <p>{this.state.notification_response}</p> ) } } render(){ return( <div className="ticket-view-area"> <div className="ticket-view-area__back-button"> <button onClick={this.goBack}>back</button> </div> <div className="ticket-view"> <div className="ticket-view__action-button"> <button onClick={this.sendNotification} style={{ display: this.props.show_ticket && this.props.show_ticket.status == "Unfulfilled" ? 'block' : 'none' }}>notify</button> <button onClick={this.fulfillTicket} style={{ display: this.props.show_ticket && this.props.show_ticket.status == "Notified" ? 'block' : 'none' }}>fulfill</button> </div> {this.renderNotificationResponse()} {this.renderTicket()} </div> </div> ) } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TicketView));<file_sep>import * as APIUtil from '../util/tickets_api_util'; export const RECEIVE_TICKETS = 'RECEIVE_TICKETS'; export const RECEIVE_SEARCH_TICKETS = 'RECEIVE_SEARCH_TICKETS'; export const RECEIVE_SHOW_TICKET = 'RECEIVE_SHOW_TICKET'; export const RECEIVE_TICKET_STATUS = 'RECEIVE_TICKET_STATUS'; export const receiveTickets = (tickets) => ({ type: RECEIVE_TICKETS, tickets: tickets }) export const receiveSearchTickets = (tickets) => ({ type: RECEIVE_SEARCH_TICKETS, search_tickets: tickets }) export const clearSearchTickets = () => ({ type: RECEIVE_SEARCH_TICKETS, search_tickets: [] }) export const receiveShowTicket = (ticket) => ({ type: RECEIVE_SHOW_TICKET, ticket: ticket }) export const changeTicketStatus = (status) => ({ type: RECEIVE_TICKET_STATUS, status: status }) export const clearShowTicket = () => ({ type: RECEIVE_SHOW_TICKET, ticket: null }) export const fetchStatusTickets = (business_id, page, status) => (dispatch) => ( APIUtil.fetchStatusTickets(business_id,page, status).then( (tickets) => dispatch(receiveTickets(tickets)) ) ) export const fetchGlobalSearchTickets = (business_id, query, status) => (dispatch) => ( APIUtil.fetchGlobalSearchTickets(business_id, query, status).then( (tickets) => dispatch(receiveSearchTickets(tickets)) ) ) export const fetchIdSearchTickets = (business_id, query, status) => (dispatch) => ( APIUtil.fetchIdSearchTickets(business_id, query, status).then( (tickets) => dispatch(receiveSearchTickets(tickets)) ) ) export const fetchNameSearchTickets = (business_id, query, status) => (dispatch) => ( APIUtil.fetchNameSearchTickets(business_id, query, status).then( (tickets) => dispatch(receiveSearchTickets(tickets)) ) ) export const fetchShowTicket = (ticket_id) => (dispatch) => ( APIUtil.fetchShowTicket(ticket_id).then( (ticket) => dispatch(receiveShowTicket(ticket)) ) ) export const notifyCustomer = (ticket_id) => (dispatch) => ( APIUtil.notifyCustomer(ticket_id).then( (ticket) => dispatch(receiveShowTicket(ticket)) ) ) export const createNewTicket = (data, business_id) => (dispatch) => ( APIUtil.createNewTicket(data, business_id).then( (ticket) => dispatch(receiveShowTicket(ticket)) ) ) export const fulfillTicket = (ticket_id) => (dispatch) => ( APIUtil.fulfillTicket(ticket_id).then( (ticket) => dispatch(receiveShowTicket(ticket)) ) ) export const fetchTicketsByPage = (business_id, ticket_status, page) => (dispatch) => ( APIUtil.fetchTicketsByPage(business_id, ticket_status, page).then( (tickets) => dispatch(receiveTickets(tickets)) ) )<file_sep>class CreateBusinesses < ActiveRecord::Migration[5.2] def change create_table :businesses do |t| t.string :name, null: false t.integer :user_id, null: false t.string :business_type_id, null:false t.decimal :longtitude, null:false t.decimal :latitude, null:false t.integer :zipcode, null:false t.string :street_address, null:false t.float :price_per_pound, null:true t.timestamps end add_index :businesses, :name end end <file_sep>import { RECEIVE_TICKET_STATUS } from '../../actions/tickets_actions'; const CurrentTicketStatusReducer = (state = "Unfulfilled", action) => { switch(action.type){ case RECEIVE_TICKET_STATUS: return action.status default: return state } } export default CurrentTicketStatusReducer;<file_sep>class User < ApplicationRecord validates :first_name, :last_name, :email, presence: true has_many :businesses, class_name: 'Business', foreign_key: :user_id, dependent: :destroy has_one :settings, class_name: 'Setting', foreign_key: :user_id, dependent: :destroy after_initialize :ensure_session_token def self.generate_session_token SecureRandom.urlsafe_base64 end def self.find_by_credentials(email) user = User.find_by(email: email) return user unless user.nil? end def reset_session_token! self.session_token = User.generate_session_token self.save! self.session_token end private def ensure_session_token self.session_token ||= User.generate_session_token end end <file_sep>import * as APIUtil from '../util/businesses_api_util'; export const RECEIVE_CURRENT_BUSINESS_ID = 'RECEIVE_CURRENT_BUSINESS_ID'; export const RECEIVE_CURRENT_BUSINESS = 'RECEIVE_CURRENT_BUSINESS'; export const RECEIVE_BUSINESSES = 'RECEIVE_BUSINESSES'; export const RECEIVE_BUSINESS_ON_MAP = 'RECEIVE_BUSINESS_ON_MAP' export const receiveCurrentBusinessId = (id) => ({ type: RECEIVE_CURRENT_BUSINESS_ID, id: id }) export const receiveCurrentBusiness = (business) => ({ type: RECEIVE_CURRENT_BUSINESS, business: business }) export const receiveBusinesses = (businesses) => ({ type: RECEIVE_BUSINESSES, businesses: businesses }) export const setBusinessOnMap = (business) => ({ type: RECEIVE_BUSINESS_ON_MAP, business: business }) export const changeCurrentBusinessId = (id) => ({ type: RECEIVE_CURRENT_BUSINESS_ID, id: id }) export const fetchCurrentBusinessInfo = (business_id) => (dispatch) => ( APIUtil.fetchCurrentBusinessInfo(business_id).then( (business) => dispatch(receiveCurrentBusiness(business)) ) ) export const fetchBusinesses = (user_id) => (dispatch) => ( APIUtil.fetchBusinesses(user_id).then( (businesses) => dispatch(receiveBusinesses(businesses)) ) ) <file_sep>class EditTicketsColumn < ActiveRecord::Migration[5.2] def change remove_column :tickets, :time_filfilled add_column :tickets, :time_fulfilled, :time end end <file_sep>export const fetchCustomers = (business_id) => { return $.ajax({ method: "GET", url: `api/businesses/${business_id}/customers` }) } export const fetchSearchCustomers = (busines_id, query) => { return $.ajax({ method: 'GET', url: `api/businesses/${busines_id}/customers/search/${query}` }) } export const fetchShowCustomer = (customer_id) => { return $.ajax({ method: 'GET', url: `api/customers/${customer_id}` }) } export const createNewCustomer = (data) => { return $.ajax({ method: "POST", url: `api/businesses/${data.business_id}/customers`, data: { customer: data } }) }<file_sep>class BusinessType < ApplicationRecord validates :type_name, :description, presence:true end<file_sep>import { RECEIVE_TICKETS } from '../../actions/tickets_actions'; const TicketsReducer = (state = [], action) => { switch(action.type){ case RECEIVE_TICKETS: return action.tickets default: return state } } export default TicketsReducer;<file_sep>Rails.application.routes.draw do root 'static_pages#root' =begin Rails routes are matched in the order they are specified, so if you have a 'resources :photos' above a 'get 'photos/poll'' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first. =end # The 'defaults: { format: :json }' option tells the controller to first look for a .json.jbuilder view rather than an html.erb view. namespace :api, defaults: {format: :json} do # :users => name of controller, map to controller actions resource :sessions, only: [:create, :destroy] resources :users, only: [:show, :index] do resources :businesses, only: [:index, :create] do collection do get 'search/:q', to: 'businesses#search' end end end resources :businesses, only: [:show] do resources :tickets, only: [:index, :create] do collection do get 'search/:q/:s', to: 'tickets#search' get 'search/id/:q/:s', to: 'tickets#id_search' get 'search/cname/:q/:s', to: 'tickets#customer_search' # this route takes a page number as a param # multiplies page number by offset to facilitate pagination get ':s/:p', to: 'tickets#status_tickets' end end resources :customers, only: [:index, :create] do collection do get 'search/:q', to: 'customers#search' end end end resources :customers, only: [:show] resources :tickets, only: [:show] do get '/notify', to: 'tickets#notify_customer' get '/fulfill', to: 'tickets#fulfill_ticket' end end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end <file_sep>class EditTicketsColumns < ActiveRecord::Migration[5.2] def change change_column :tickets, :ticket_type_id, :integer, null:true change_column :tickets, :delivery_method_id, :integer, null:true end end <file_sep>import { RECEIVE_BUSINESS_ON_MAP } from '../../actions/businesses_actions'; const BusinessOnMapReducer = (state = null, action) => { switch(action.type){ case RECEIVE_BUSINESS_ON_MAP: return action.business default: return state } } export default BusinessOnMapReducer;<file_sep>import React from 'react'; import { connect } from 'react-redux'; import TicketsViewItem from './tickets_view_item'; import {fetchTicketsByPage} from '../../actions/tickets_actions'; const mapStateToProps = (state) => ({ tickets: state.entities.tickets, current_business_id: state.ui.current_business_id, current_ticket_status: state.ui.current_ticket_status }) const mapDispatchToProps = (dispatch) => ({ fetchTicketsByPage: (business_id, ticket_status, page) => dispatch(fetchTicketsByPage(business_id, ticket_status, page)) }) class TicketsView extends React.Component{ constructor(props){ super(props); this.renderTickets = this.renderTickets.bind(this) this.state = { page: 0 } this.handleNextPage = this.handleNextPage.bind(this) this.handlePrevPage = this.handlePrevPage.bind(this) } componentDidUpdate(prevProps){ if(this.props.current_ticket_status != prevProps.current_ticket_status){ this.setState({page: 0}) } } renderTickets(){ let tickets = [] this.props.tickets.forEach( (ticket,i)=> { tickets.push(<TicketsViewItem ticket={ticket} key={i}/>) }) return tickets } handleNextPage(e){ e.preventDefault() this.props.fetchTicketsByPage(this.props.current_business_id, this.props.current_ticket_status, this.state.page + 1) this.setState({page: this.state.page + 1}) } handlePrevPage(e){ e.preventDefault() this.props.fetchTicketsByPage(this.props.current_business_id, this.props.current_ticket_status, this.state.page - 1) this.setState({ page: this.state.page - 1 }) } render(){ return( <div className="tickets-view-area"> <div className="tickets-view-area__page_navigation"> <button style={{ display: this.state.page == 0 ? 'none' : 'block' }} onClick={this.handlePrevPage}>prev</button> <button onClick={this.handleNextPage}>next</button> </div> <div className="tickets-view"> {this.renderTickets()} </div> </div> ) } } export default connect(mapStateToProps, mapDispatchToProps)(TicketsView); <file_sep>class Status < ApplicationRecord validates :status_name, :status_description, presence:true end<file_sep>class AddColumnsToBusinesses < ActiveRecord::Migration[5.2] def change add_column :businesses, :city, :string, null:false add_column :businesses, :state, :string, null:false end end <file_sep>import React from 'react'; import { logout } from '../../actions/session_actions'; import { fetchStatusTickets, changeTicketStatus } from '../../actions/tickets_actions'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import classNames from 'classnames'; // var classNames = require('classnames'); const mapDispatchToProps = (dispatch) => ({ logout: () => dispatch(logout()), fetchStatusTickets: (busines_id, page, status) => dispatch(fetchStatusTickets(busines_id, page, status)), changeTicketStatus: (status) => dispatch(changeTicketStatus(status)) }) const mapStateToProps = (state) => ({ user: state.session.current_user, current_business_id: state.ui.current_business_id, current_ticket_status: state.ui.current_ticket_status }) class TicketsControl extends React.Component { constructor(props) { super(props); this.handleSubmit = this.handleSubmit.bind(this); this.handleNewTicketRedirect = this.handleNewTicketRedirect.bind(this) } // fetch new status tickets upon changing state (ticket_status) // new tickets will go through redux and be stored in entities.tickets // other components react to this change in the store. // such as tickets view, which renders tickets stored in the store (entities.tickets) componentDidUpdate(prevProps) { if (this.props.current_ticket_status != prevProps.current_ticket_status) { let id = this.props.current_business_id let status = this.props.current_ticket_status this.props.fetchStatusTickets(id, 0, status) } } componentDidMount() { // call fetchStatusTickets method with page 0 let business_id = this.props.current_business_id; this.props.fetchStatusTickets(business_id, 0, this.props.current_ticket_status); } handleSubmit(event) { event.preventDefault(); this.props.logout(); } handleStatusChange(e, status) { e.preventDefault() this.props.changeTicketStatus(status) if(this.props.location.pathname != "/dashboard/tickets"){ this.props.history.push('/dashboard/tickets') } } handleNewTicketRedirect() { // e.preventDefault() this.props.history.push('/dashboard/new-ticket-s1') } render() { return ( <div className="tickets-control"> <div className={classNames({ 'button__basic-active': this.props.current_ticket_status == "unfulfilled", "button__container": true})} onClick={(e) => this.handleStatusChange(e, "unfulfilled")}> <button className="button__basic-inactive">Unfulfilled</button> </div> <div className={classNames({ 'button__basic-active': this.props.current_ticket_status == "notified", "button__container": true })} onClick={(e) => this.handleStatusChange(e, "notified")}> <button className="button__basic-inactive">Notified</button> </div> <div className={classNames({ 'button__basic-active': this.props.current_ticket_status == "fulfilled", "button__container": true })} onClick={(e) => this.handleStatusChange(e, "fulfilled")}> <button className="button__basic-inactive">Fulfilled</button> </div> <div className="tickets-control__new-ticket-area"> <div className="tickets-control__new-ticket-button" onClick={this.handleNewTicketRedirect}><i className="fas fa-plus"></i></div> <p>new ticket</p> </div> </div> ) } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(TicketsControl));<file_sep>import * as APIUtil from '../util/customers_api_util'; export const RECEIVE_CUSTOMERS = 'RECEIVE_CUSTOMER'; export const RECEIVE_SEARCH_CUSTOMERS = 'RECEIVE_SEARCH_CUSTOMERS'; export const RECEIVE_SHOW_CUSTOMER = 'RECEIVE_SHOW_CUSTOMER'; export const receiveCustomers = (customers) => ({ type: RECEIVE_CUSTOMERS, customers: customers }) export const receiveShowCustomer = (customer) => ({ type: RECEIVE_SHOW_CUSTOMER, customer: customer }) export const clearSearchCustomers = () => ({ type: RECEIVE_SEARCH_CUSTOMERS, customers: [] }) export const receiveSearchCustomers = (customers) => ({ type: RECEIVE_SEARCH_CUSTOMERS, customers: customers }) export const fetchCustomers = (business_id) => (dispatch) => ( APIUtil.fetchCustomers(business_id).then( (customers) => dispatch(receiveCustomers(customers)) ) ) export const fetchSearchCustomers = (business_id, query) => (dispatch) => ( APIUtil.fetchSearchCustomers(business_id, query).then( (customers) => dispatch(receiveSearchCustomers(customers)) ) ) export const fetchShowCustomer = (customer_id) => (dispatch) => ( APIUtil.fetchShowCustomer(customer_id).then( (customer) => dispatch(receiveShowCustomer(customer)) ) ) export const createNewCustomer = (data) => (dispatch) => ( APIUtil.createNewCustomer(data).then( (customer) => dispatch(receiveShowCustomer(customer)) ) )<file_sep>json.array! @customers do |customer| json.partial! 'api/customers/customer', customer: customer end<file_sep>class ChangeBusinessesColumn < ActiveRecord::Migration[5.2] def change remove_column :businesses, :zipcode add_column :businesses, :zip_code, :string, null:false end end <file_sep>class Api::TicketsController < ApplicationController def index @tickets = Ticket.includes(:customer).where("business_id = ?", params[:business_id]) render 'api/tickets/index' end def create @ticket = Ticket.new(ticket_params) @ticket.set_to_unfulfilled! if @ticket.save render 'api/tickets/show' else render json: {:errors => @ticket.errors.full_messages} end end def show @ticket = Ticket.includes(:customer, :status).find_by(id: params[:id]) if @ticket render 'api/tickets/show' else render json: {:errors => ["No record found in db."]} end end def search @tickets = Ticket.search_by_global_scope(params[:business_id], params[:q], params[:s]) render 'api/tickets/index' end def id_search @tickets = Ticket.search_by_id_scope(params[:business_id], params[:q], params[:s]) render 'api/tickets/index' end def customer_search @tickets = Ticket.search_by_customer_scope(params[:business_id], params[:q], params[:s]) render 'api/tickets/index' end def status_tickets page_number = Integer(params[:p]) @tickets = Ticket.status_tickets_by_page_number(params[:business_id], page_number, params[:s]) if @tickets render 'api/tickets/index' else render json: {:errors => ["Invalid parameters"]}, status: 422 end end def notify_customer @ticket = Ticket.find_by(id: params[:ticket_id]) if @ticket customer = Customer.find(@ticket.customer_id) customer.send_notification(@ticket.id) @ticket.change_status_to_notified! render 'api/tickets/show' else render json: {:error => ['No record found']}, status: 422 end end def fulfill_ticket @ticket = Ticket.find_by(id: params[:ticket_id]) if @ticket @ticket.fulfill! render 'api/tickets/show' else render json: {:error => ['No record found']}, status: 422 end end private def ticket_params params.require(:ticket).permit( :customer_id, :status_id, :date_dropped_off, :time_dropped_off, :date_fulfilled, :time_fulfilled, :bag_weight, :grand_total, :ticket_type_id, :delivery_method_id, :business_id, :p ) end end <file_sep>import React from 'react'; import CustomerSearchBar from './customer_search_bar'; import MostFrequentCustomersView from './most_frequent_customers_view'; class ExistingCustomerView extends React.Component{ constructor(props){ super(props) } render(){ return( <div className="existing-customer-view"> <CustomerSearchBar /> <MostFrequentCustomersView /> </div> ) } } export default ExistingCustomerView ;<file_sep>class Change < ActiveRecord::Migration[5.2] def change remove_column :businesses, :longtitude add_column :businesses, :longitude, :decimal, null:false end end <file_sep>json.extract! customer, :id, :first_name, :last_name, :business_id<file_sep>import { RECEIVE_CURRENT_USER } from '../../actions/session_actions'; import { RECEIVE_CURRENT_BUSINESS_ID } from '../../actions/businesses_actions'; const CurrentBusinessIdReducer = (state = null, action) => { switch(action.type){ case RECEIVE_CURRENT_USER: if(action.current_user){ return action.current_user.startup_business_id }else{ return null } case RECEIVE_CURRENT_BUSINESS_ID: return action.id default: return state } } export default CurrentBusinessIdReducer;<file_sep>import React from 'react'; import TicketsView from '../dashboard/tickets_view'; import TicketsControl from '../dashboard/tickets_control'; import TicketSearchBar from '../dashboard/ticket_search_bar'; import TicketView from '../dashboard/ticket_view'; import { ProtectedRoute } from '../../util/route_util'; import { Switch } from 'react-router-dom'; class TicketsViewTab extends React.Component{ constructor(props){ super(props) } render(){ return( <div className="dashboard__main-view"> <TicketSearchBar /> <div className="dashboard__tickets-view-and-control"> <TicketsControl /> <Switch> <ProtectedRoute exact path="/dashboard/tickets" component={TicketsView} /> <ProtectedRoute exact path="/dashboard/tickets/:ticket_id" component={TicketView} /> </Switch> </div> </div> ) } } export default TicketsViewTab;<file_sep>import React from 'react'; import {withRouter} from 'react-router-dom'; import {connect} from 'react-redux'; import NewTicketForm from '../../dashboard/new_ticket_form'; const mapStateToProps = (state) => ({ show_customer: state.entities.show_customer }) class TicketInfo extends React.Component{ constructor(props){ super(props) this.goBack = this.goBack.bind(this) } componentDidMount(){ if(this.props.show_customer == null){ this.props.history.push('/dashboard/new-ticket-s1') } } goBack(){ this.props.history.push('/dashboard/new-ticket-s1') } renderCustomerInfo(){ if(this.props.show_customer){ return( <div className="ticket-info-view__customer-name"> <p>{this.props.show_customer.first_name} {this.props.show_customer.last_name}</p> </div> ) } } render(){ return( <div className="dashboard__main-view dashboard__new-ticket-view"> <h1>New Ticket</h1> <h3>Ticket info</h3> <div className="button__back-button"> <button onClick={this.goBack}>back</button> </div> <div> <div className="ticket-info-view"> {this.renderCustomerInfo()} <NewTicketForm /> </div> </div> </div> ) } } export default withRouter(connect(mapStateToProps, null)(TicketInfo));<file_sep>import React from 'react'; import {AuthRoute, ProtectedRoute} from '../util/route_util'; import LogInPage from './pages/login_page'; import Dashboard from './pages/dashboard'; const App = () => ( <div className="app"> <AuthRoute exact path="/login" component={LogInPage} /> <ProtectedRoute path="/dashboard" component={Dashboard}/> </div> ); export default App; <file_sep>class Api::UsersController < ApplicationController def index @users = User.all render 'api/users/index' end def show @user = User.includes(:settings).find(params[:id]) if @user render 'api/users/show' else render json: {:no_user => "No user found"}, status: 400 end end end <file_sep>import {RECEIVE_CURRENT_USER} from '../actions/session_actions'; const SessionReducer = (state = {current_user: null}, action) => { switch(action.type){ case RECEIVE_CURRENT_USER: return {current_user: action.current_user} default: return state } } export default SessionReducer;<file_sep>import { RECEIVE_SEARCH_TICKETS } from "../../actions/tickets_actions"; const SearchTicketsReducer = (state = [], action) => { switch(action.type){ case RECEIVE_SEARCH_TICKETS: return action.search_tickets default: return state } } export default SearchTicketsReducer;<file_sep>class TicketType < ApplicationRecord validates :type_name, presence:true end<file_sep>import React from 'react'; import {withRouter} from 'react-router-dom'; import {connect} from 'react-redux'; import {logout} from '../../actions/session_actions'; import classNames from 'classnames'; const mapDispatchToProps = (dispatch) => ({ logout: () => dispatch(logout()) }) class Icons extends React.Component{ constructor(props){ super(props) this.toTickets = this.toTickets.bind(this) this.toBusinesses = this.toBusinesses.bind(this) this.handleSignOut = this.handleSignOut.bind(this) } toTickets(){ this.props.history.push('/dashboard/tickets') } toBusinesses(){ this.props.history.push('/dashboard/businesses') } handleSignOut(){ this.props.logout() } render(){ return( <div className="sidebar"> <i className={classNames({ "sidebar__button": true, 'fa-ticket-alt':true, 'fas': true, 'sidebar__button-active': this.props.location.pathname.includes('tickets')})} onClick={this.toTickets}></i> <i className={classNames({ "fas fa-briefcase sidebar__button": true, 'sidebar__button-active': this.props.location.pathname.includes('businesses')})} onClick={this.toBusinesses}></i> <i className="fas fa-power-off sidebar__button" onClick={this.handleSignOut}></i> </div> ) } } export default withRouter(connect(null, mapDispatchToProps)(Icons));<file_sep>class ChangeCustomersColumns < ActiveRecord::Migration[5.2] def change change_column :customers, :phone_number, :string, null:true change_column :customers, :street_address, :string, null:true change_column :customers, :zip_code, :string, null:true add_column :customers, :apt_number, :string, null:true add_index :customers, :email_address, unique:true end end <file_sep>json.extract! @ticket, :id, :business_id, :date_dropped_off, :time_dropped_off, :date_fulfilled, :time_fulfilled, :bag_weight, :grand_total json.customer_first_name @ticket.customer.first_name json.customer_last_name @ticket.customer.last_name json.status @ticket.status.status_name # json.note @ticket.note.text # json.delivery_method @ticket.delivery_method.method_name # json.ticket_type @ticket.ticket_type.type_name <file_sep>class ApplicationController < ActionController::Base protect_from_forgery with: :exception # protect_from_forgery with: :null_session # helper methods available to views helper_method :current_user, :logged_in? private def current_user return nil unless session[:session_token] # return @current_user if defined, else find user by session token @current_user ||= User.includes(:settings).find_by(session_token: session[:session_token]) end def login(user) # create a session token for user and store in cookie session[:session_token] = user.reset_session_token! # store user argument in @current_user instance variable @current_user = user end # modifying user object so, use bang (!) by convention def logout! # change (reset) the current_user's session token current_user.reset_session_token! # set :session_token cookie to nil session[:session_token] = nil # set @current_user instance variable to nil @current_user = nil end def logged_in? !!current_user end end <file_sep>class Api::CustomersController < ApplicationController def index @customers = Customer.where("business_id = ?", params[:business_id]) render 'api/customers/index' end def create @customer = Customer.new(customer_params) if @customer.save render 'api/customers/show' else render json: {:errors => @customer.errors.full_messages} end end def show @customer = Customer.find_by(id: params[:id]) if @customer render 'api/customers/show' else render json: {:errors => ["No record found in db."]} end end def search @customers = Customer.search_by_name_and_email(params[:business_id], params[:q]) render 'api/customers/index' end private def customer_params params.require(:customer).permit( :first_name, :last_name, :email_address, :phone_number, :street_address, :zip_code, :apt_number, :business_id ) end end <file_sep>import { RECEIVE_SEARCH_CUSTOMERS } from '../../actions/customers_actions'; const SearchCustomersReducer = (state = [], action) => { switch(action.type){ case RECEIVE_SEARCH_CUSTOMERS: return action.customers default: return state } } export default SearchCustomersReducer;<file_sep>class ContactInfo < ActiveModel::Validator def validate(record) if record.email_address.blank? && record.phone_number.blank? record.errors[:base] << "Some form of contact information is needed. Email or phone number." end end end class Customer < ApplicationRecord include PgSearch include SendGrid pg_search_scope :name_and_email_scope, :against => [:first_name, :last_name, :email_address], :using => { :tsearch => {:prefix => true} } validates :first_name, :last_name, presence:true validates_with ContactInfo has_many :tickets, class_name: 'Ticket', foreign_key: :customer_id, dependent: :destroy belongs_to :business, class_name: 'Business', foreign_key: :business_id def self.search_by_name_and_email(business_id, query) return Customer.where("business_id = ?", business_id).name_and_email_scope(query) end def send_notification(ticket_id) from = Email.new(email: '<EMAIL>') to = Email.new(email: self.email_address) subject = 'FROM: Hamper - ready for pick up!' content = Content.new(type: 'text/plain', value: "Ticket ID: #{ticket_id}") mail = Mail.new(from, subject, to, content) sg = SendGrid::API.new(api_key: ENV["send_grid_api"]) response = sg.client.mail._('send').post(request_body: mail.to_json) end end<file_sep>import React from 'react'; import Map from '../dashboard/map'; import {fetchBusinesses, setBusinessOnMap} from '../../actions/businesses_actions'; import {connect} from 'react-redux'; import classNames from 'classnames'; const mapStateToProps = (state) => ({ current_user: state.session.current_user, businesses: state.entities.businesses, current_business_id: state.ui.current_business_id, business_on_map: state.ui.business_on_map }) const mapDispathToProps = (dispatch) => ({ fetchBusinesses: (user_id) => dispatch(fetchBusinesses(user_id)), setBusinessOnMap: (business) => dispatch(setBusinessOnMap(business)) }) class SettingsTab extends React.Component{ constructor(props){ super(props) this.handleBusinessChange = this.handleBusinessChange.bind(this) this.renderBusinessesList = this.renderBusinessesList.bind(this) this.renderGoToButton = this.renderGoToButton.bind(this) this.setInitialBusinessOnMap = this.setInitialBusinessOnMap.bind(this) } setInitialBusinessOnMap(businesses){ if (businesses.length > 0) { for(let i = 0; i<businesses.length; i++){ if(businesses[i].id == this.props.current_business_id){ this.props.setBusinessOnMap(businesses[i]) break; } } } } componentDidMount(){ this.props.fetchBusinesses(this.props.current_user.id).then( (response) => this.setInitialBusinessOnMap(response.businesses) ) } handleBusinessChange(e, business){ e.preventDefault() this.props.setBusinessOnMap(business) } renderBusinessesList(){ let businesses = [] this.props.businesses.forEach((business) => { businesses.push( <button className={classNames({ 'button__basic-active': this.props.business_on_map && (this.props.business_on_map.name == business.name), "button__basic-inactive": true })} onClick={(e) => this.handleBusinessChange(e,business)}>{business.name}</button> ) }) return businesses } renderGoToButton() { if (this.props.business_on_map && (this.props.current_business_id != this.props.business_on_map.id)) { return ( <button onClick={this.handleRedirect}>Go to this location</button> ) } } render(){ let business_on_map_name; if(this.props.business_on_map){ business_on_map_name = this.props.business_on_map.name; } return( <div className="dashboard__main-view dashboard__businesses-view"> <div className="businesses__list"> Your businesses {this.renderBusinessesList()} <p>{business_on_map_name}</p> {this.renderGoToButton()} </div> <Map /> </div> ) } } export default connect(mapStateToProps, mapDispathToProps)(SettingsTab);<file_sep>class EditCustomersTable < ActiveRecord::Migration[5.2] def change change_column :customers, :email_address, :string, null:true add_index :customers, :phone_number, unique: true end end <file_sep>class Api::SessionsController < ApplicationController def create @user = User.find_by_credentials(params[:email]) # if user is found, login user and render show template/data for user if @user login(@user) render 'api/users/show' else render json: {:invalid_credentials => ["Invalid Credentials"]}, status: 422 end end def destroy # calls the current_user method within ApplicationController # stores return value in @user @user = current_user if @user logout! render json: {} else render json: {:no_user => ["No user signed in"]}, status: 400 end end end <file_sep>import { combineReducers } from 'redux'; import CurrentBusinessIdReducer from './ui/current_business_id_reducer'; import CurrentTicketStatusReducer from './ui/current_ticket_status_reducer'; import BusinessOnMapReducer from './ui/business_on_map_reducer'; // import CurrentCustomerShowIdReducer from './ui/current_customer_show_id_reducer'; const UIReducer = combineReducers({ current_business_id: CurrentBusinessIdReducer, current_ticket_status: CurrentTicketStatusReducer, business_on_map: BusinessOnMapReducer }) export default UIReducer;<file_sep>json.extract! business, :id, :name, :street_address, :city, :zip_code, :state, :latitude, :longitude, :price_per_pound, :user_id <file_sep>class DeliveryMethod < ApplicationRecord validates :method_name, presence: true end <file_sep>class DryCleaningItem < ApplicationRecord validates :item_name, :business_id, :business_user_id, presence: true end<file_sep>import { RECEIVE_SHOW_TICKET } from '../../actions/tickets_actions'; const ShowTicketReducer = (state = null, action) => { switch(action.type){ case RECEIVE_SHOW_TICKET: return action.ticket default: return state } } export default ShowTicketReducer;<file_sep>class RemoveColumnFromTickets < ActiveRecord::Migration[5.2] def change remove_column :tickets, :note_id end end <file_sep>import React from 'react'; import {withRouter} from 'react-router-dom'; class TicketsViewItem extends React.Component{ constructor(props){ super(props) this.handleTicketSelect = this.handleTicketSelect.bind(this) } handleTicketSelect(e){ e.preventDefault(); this.props.history.push(`/dashboard/tickets/${this.props.ticket.id}`) } render(){ return( <div className="tickets-view__item" onClick={this.handleTicketSelect}> <p>id: {this.props.ticket.id}</p> <p>drop-off date: {this.props.ticket.date_dropped_off}</p> <p>customer: {this.props.ticket.customer_first_name} {this.props.ticket.customer_last_name}</p> </div> ) } } export default withRouter(TicketsViewItem);<file_sep>class Note < ApplicationRecord validates :ticket_id, presence: true end<file_sep># @tickets.each do |ticket| # json.partial! 'api/tickets/ticket', ticket: ticket # end json.array! @tickets do |ticket| json.partial! 'api/tickets/ticket', ticket: ticket end<file_sep>import React from 'react'; import Autocomplete from 'react-autocomplete'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import { fetchCustomers, fetchSearchCustomers, clearSearchCustomers, fetchShowCustomer } from '../../actions/customers_actions'; const mapStateToProps = (state) => ({ customers: state.entities.customers, current_business_id: state.ui.current_business_id, search_customers: state.entities.search_customers }) const mapDispatchToProps = (dispatch) => ({ fetchCustomers: (business_id) => dispatch(fetchCustomers(business_id)), fetchShowCustomer: (customer_id) => dispatch(fetchShowCustomer(customer_id)), fetchSearchCustomers: (business_id, query) => dispatch(fetchSearchCustomers(business_id, query)), clearSearchCustomers: () => dispatch(clearSearchCustomers()) }) class CustomerSearchBar extends React.Component{ constructor(props){ super(props) this.state = { query: '', timer_id: null } this.handleChangeDebounced = this.handleChangeDebounced.bind(this) this.handleSelect = this.handleSelect.bind(this) } handleSelect(value, item){ this.props.clearSearchCustomers() this.props.fetchShowCustomer(item.id).then( () => this.props.history.push('/dashboard/new-ticket-s2') ) } handleChangeDebounced(event) { event.preventDefault() this.setState({ query: event.target.value }) return function () { if (this.state.timer_id) { clearTimeout(this.state.timer_id) } let timer_id = setTimeout(() => { let id = this.props.current_business_id let q = this.state.query if (this.state.query.length > 0) { this.props.fetchSearchCustomers(id,q) } else { this.props.clearSearchCustomers() } this.setState({ timer_id: null }) }, 1000); this.setState({ timer_id: timer_id }) }.bind(this)() } render(){ return( <div className="searchbar customer-search-bar"> <Autocomplete getItemValue={(item) => { return item.first_name }} items={this.props.search_customers} renderItem={(item, isHighlighted) => <div style={{ background: isHighlighted ? 'rgb(223, 223, 223)' : 'white', fontFamily: 'sans-serif', fontWeight: '200', padding: '.5rem .5rem', fontSize: '.9rem' }} key={item.id}> {item.first_name} </div> } value={this.state.query} onChange={this.handleChangeDebounced} onSelect={this.handleSelect} menuStyle={{ background: 'rgba(255, 255, 255, 0.9)', position: 'fixed', overflow: 'auto', maxHeight: '50%', }} wrapperStyle={{ width: "100%" }} inputProps={{ placeholder: "Search..." }} /> </div> ) } } export default withRouter(connect(mapStateToProps, mapDispatchToProps)(CustomerSearchBar));<file_sep>import { createStore, applyMiddleware } from 'redux'; import RootReducer from '../reducers/root_reducer'; import thunk from 'redux-thunk'; /* we need redux-thunk to allow use to write action creators that return a function rather than an action. As a middleware, it intercepts all action creators that are functions. This allows us to delay the dispatch of a given action */ const middlewares = [thunk]; if (process.env.NODE_ENV !== 'production') { // must use 'require' (import only allowed at top of file) const { logger } = require('redux-logger'); middlewares.push(logger); } // applyMiddleware takes in multiple arguments, we can pass in more than 1 middleware const configureStore = (preloadedState = {}) => ( createStore( RootReducer, preloadedState, applyMiddleware(...middlewares) ) ) export default configureStore;<file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) # clean tables User.destroy_all Ticket.destroy_all TicketType.destroy_all Status.destroy_all Note.destroy_all DryCleaningItem.destroy_all DeliveryMethod.destroy_all Customer.destroy_all Business.destroy_all BusinessType.destroy_all Setting.destroy_all # default user user = User.new(first_name: "Omar", last_name: "Torres", email: "<EMAIL>") user.save # business types business_type_1 = BusinessType.new(type_name: "Laundromat", description: "an establishment with washing machines and dryers offering wash & fold services.") business_type_2 = BusinessType.new(type_name: "Dry Cleaners", description: "an establishment offering dry cleaning services.") business_type_3 = BusinessType.new(type_name: "Hybrid", description: "an establishment offering both wash & fold and dry cleaning services.") business_type_1.save business_type_2.save business_type_3.save # default businesses business_1 = Business.new(name:"Your Cleaners", user_id: user.id, business_type_id: business_type_1.id, latitude: 40.7468686, longitude: -73.8820543, zip_code: "11373", street_address: "40-21 Hampton Street", city: "Elmhurst", state: "NY", price_per_pound: 1.20) business_2 = Business.new(name: "<NAME>", user_id: user.id, business_type_id: business_type_2.id, latitude: 40.75113669999999, longitude: -73.87271770000001, zip_code: "11372", street_address: "94-13 37th ave", city: "Jackson Heights", state: "NY", price_per_pound: 1.50 ) business_3 = Business.new(name: "<NAME>", user_id: user.id, business_type_id: business_type_3.id, latitude: 40.7489742, longitude: -73.89048630000002, zip_code: "11372", street_address: "75-12 37th ave", city: "Jackson Height", state: "NY", price_per_pound: 1.10 ) business_1.save business_2.save business_3.save Setting.create(user_id: user.id, startup_business_id: business_1.id) # delivery methods # delivery_method_1 = DeliveryMethod.new(method_name: "Pick-up") # delivery_method_2 = DeliveryMethod.new(method_name: "Drop-off") # delivery_method_1.save # delivery_method_2.save # statuses status_1 = Status.new(status_name: "Unfulfilled", status_description: "Contents have not been delivered to customer.") status_2 = Status.new(status_name: "Notified", status_description: "Contents are ready for pick up, and customer has been notified.") status_3 = Status.new(status_name: "Fulfilled", status_description: "Contents have been delivered to customer.") status_1.save status_2.save status_3.save # ticket types # ticket_type_1 = TicketType.new(type_name: "Laundry Bag") # ticket_type_2 = TicketType.new(type_name: "Dry Cleaning") # ticket_type_3 = TicketType.new(type_name: "Dry Cleaning + Laundry Bag") # ticket_type_1.save # ticket_type_2.save # ticket_type_3.save # customers customer_1 = Customer.new(first_name: "Erik",last_name: "Campos", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "456-323-3233") customer_2 = Customer.new(first_name: "Cesar",last_name: "Garcia", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "482-384-9392") customer_3 = Customer.new(first_name: "Vinny",last_name: "Roca", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "949-312-2121") customer_4 = Customer.new(first_name: "Stephanie",last_name: "Blue", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "019-933-3213") customer_5 = Customer.new(first_name: "Vicky",last_name: "Guerrero", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "999-222-3333") customer_6 = Customer.new(first_name: "John",last_name: "Green", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "929-322-3219") customer_7 = Customer.new(first_name: "Emily",last_name: "Gutierez", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "039-212-2123") customer_8 = Customer.new(first_name: "Rosa",last_name: "Torres", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "111-231-3333") customer_9 = Customer.new(first_name: "Jasmine",last_name: "Torres", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "029-321-3213") customer_10 = Customer.new(first_name: "Levy",last_name: "Rozman", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "920-3213-3213") customer_11 = Customer.new(first_name: "Chris",last_name: "Lew", email_address: "<EMAIL>", business_id: business_1.id, phone_number: "231-321-0922") customer_1.save customer_2.save customer_3.save customer_4.save customer_4.save customer_6.save customer_7.save customer_8.save customer_9.save customer_10.save customer_11.save # Tickets Ticket.create(business_id: business_1.id, customer_id: customer_1.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_1.id, customer_id: customer_2.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_2.id, customer_id: customer_3.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_2.id, customer_id: customer_4.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_3.id, customer_id: customer_5.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_3.id, customer_id: customer_6.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_1.id, customer_id: customer_7.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_1.id, customer_id: customer_8.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_2.id, customer_id: customer_9.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_2.id, customer_id: customer_10.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_3.id, customer_id: customer_11.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_1.id, customer_id: customer_1.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) Ticket.create(business_id: business_1.id, customer_id: customer_2.id, status_id: status_1.id, date_dropped_off: Date.today, time_dropped_off: Time.now, bag_weight: 45, grand_total: 43.30) # change zipcode to string for business table # add city & state column for business table <file_sep>class Business < ApplicationRecord include PgSearch pg_search_scope :name_search, :against => [:name], :using => { :tsearch => {:prefix => true} } validates :name, :user_id, :business_type_id, :longitude, :latitude, :zip_code, :street_address, presence:true has_many :tickets, class_name: 'Ticket', foreign_key: :business_id, dependent: :destroy has_many :customers, class_name: 'Customer', foreign_key: :business_id belongs_to :owner, class_name: 'User', foreign_key: :user_id belongs_to :business_type, class_name: 'BusinessType', foreign_key: :business_type_id end
165a6ac0c18a3f89ca76f16261a54057bbffb3cf
[ "JavaScript", "Ruby" ]
65
JavaScript
torres-omar/hamper
03b76b7a464b3d88affb09e97e51888c78bf7456
85e21326988f5d1264f98a2f4841627449b885c6
refs/heads/master
<file_sep># Example of low-level Python wrapper for rpi_ws281x library. # Author: <NAME> (<EMAIL>), <NAME> (<EMAIL>) # # This is an example of how to use the SWIG-generated _rpi_ws281x module. # You probably don't want to use this unless you are building your own library, # because the SWIG generated module is clunky and verbose. Instead look at the # high level Python port of Adafruit's NeoPixel Arduino library in strandtest.py. # # This code will animate a number of WS281x LEDs displaying rainbow colors. import time import random import _rpi_ws281x as ws blipSize = 12 LED_COUNT = 300 class Blip: def __init__(self, position): self.position = position self.duration = blipSize/2 self.red = 0 self.green = random.randint(16, 128) self.blue = 0 def getOriginalSize(self): if self.duration > (blipSize/4): return ((blipSize/2)-self.duration)+1 else: return self.duration/2 def size(self): s = self.getOriginalSize() m = blipSize/2 return (s*s*s)/(m) def update(self): self.duration -= 1 def isFinished(self): return self.duration == 0 def inRange(self, pos): s = self.size() return (self.position-s) < pos < (self.position+s) def getColour(self, pos): s = self.size() if (self.position-s) < pos < (self.position+s): return (self.green << 16) | (self.red << 8) | self.blue else: return 0 class Zap: def __init__(self, position, red, green, blue, tailLen, speed): self.position = position self.red = red self.green = green self.blue = blue self.tailLen = tailLen self.speed = speed def update(self): self.position -= self.speed def isFinished(self): return self.position <= -self.tailLen def inRange(self, pos): return self.position <= pos < (self.position + self.tailLen) def getColour(self, pos): if self.inRange(pos): attenuation = float(self.tailLen - pos + self.position) / self.tailLen colRed = int(round(self.red * attenuation)) colGreen = int(round(self.green * attenuation)) colBlue = int(round(self.blue * attenuation)) return (colGreen << 16) | (colRed << 8) | colBlue else: return 0 def get_rand_col(): return random.randint(0, 6) * 10 def get_rand_zap(): return Zap(LED_COUNT, get_rand_col(), get_rand_col(), get_rand_col(), random.randint(3, 10), float(random.randint(15, 50)) / 10) def get_rand_blip(): return Blip(random.randint(0, LED_COUNT)) # LED configuration. LED_CHANNEL = 1 LED_FREQ_HZ = 1200000 # Frequency of the LED signal. Should be 800khz or 400khz. LED_DMA_NUM = 10 # DMA channel to use, can be 0-14. LED_GPIO = 18 # GPIO connected to the LED signal line. Must support PWM! LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest LED_INVERT = 0 # Set to 1 to invert the LED signal, good if using NPN # transistor as a 3.3V->5V level converter. Keep at 0 # for a normal/non-inverted signal. # Define colors which will be used by the example. Each color is an unsigned # 32-bit value where the lower 24 bits define the red, green, blue data (each # being 8 bits long). # DOT_COLORS = [ 0x200000, # red # 0x201000, # orange # 0x202000, # yellow # 0x002000, # green # 0x002020, # lightblue # 0x000020, # blue # 0x100010, # purple # 0x200010 ] # pink DOT_COLORS = [0x0000ff, # blue 0x000020, # black 0x000010, # black 0x000008, # black 0x000004, # black 0x000002, # black 0x000001, # black 0x000000, 0x000000, 0x000000] # black # Create a ws2811_t structure from the LED configuration. # Note that this structure will be created on the heap so you need to be careful # that you delete its memory by calling delete_ws2811_t when it's not needed. leds = ws.new_ws2811_t() # Initialize all channels to off for channum in range(2): channel = ws.ws2811_channel_get(leds, channum) ws.ws2811_channel_t_count_set(channel, 0) ws.ws2811_channel_t_gpionum_set(channel, 0) ws.ws2811_channel_t_invert_set(channel, 0) ws.ws2811_channel_t_brightness_set(channel, 0) channel0 = ws.ws2811_channel_get(leds, 0) channel1 = ws.ws2811_channel_get(leds, 1) ws.ws2811_channel_t_count_set(channel0, LED_COUNT) ws.ws2811_channel_t_gpionum_set(channel0, LED_GPIO) ws.ws2811_channel_t_invert_set(channel0, LED_INVERT) ws.ws2811_channel_t_brightness_set(channel0, LED_BRIGHTNESS) ws.ws2811_channel_t_count_set(channel1, LED_COUNT) ws.ws2811_channel_t_gpionum_set(channel1, 13) ws.ws2811_channel_t_invert_set(channel1, LED_INVERT) ws.ws2811_channel_t_brightness_set(channel1, LED_BRIGHTNESS) ws.ws2811_t_freq_set(leds, LED_FREQ_HZ) ws.ws2811_t_dmanum_set(leds, LED_DMA_NUM) # Initialize library with LED configuration. resp = ws.ws2811_init(leds) if resp != ws.WS2811_SUCCESS: message = ws.ws2811_get_return_t_str(resp) raise RuntimeError('ws2811_init failed with code {0} ({1})'.format(resp, message)) zaps1 = [] zaps2 = [] # Wrap following code in a try/finally to ensure cleanup functions are called # after library is initialized. try: offset = 0 while True: # Update each LED color in the buffer. for i in range(LED_COUNT): color = 0 for zap in zaps1: if zap.inRange(i): color |= zap.getColour(i) ws.ws2811_led_set(channel0, LED_COUNT - i, color) color = 0 for zap in zaps2: if zap.inRange(i): color |= zap.getColour(i) ws.ws2811_led_set(channel1, LED_COUNT - i, color) # Pick a color based on LED position and an offset for animation. # color = DOT_COLORS[(i + offset) % len(DOT_COLORS)] # Set the LED color buffer value. # Send the LED color data to the hardware. resp = ws.ws2811_render(leds) if resp != ws.WS2811_SUCCESS: message = ws.ws2811_get_return_t_str(resp) raise RuntimeError('ws2811_render failed with code {0} ({1})'.format(resp, message)) # Delay for a small period of time. #time.sleep(0.01) if random.randint(0, 40) == 0: zaps1.append(get_rand_zap()) if random.randint(0,3) == 0: zaps1.append(get_rand_blip()) if random.randint(0, 40) == 0: zaps2.append(get_rand_zap()) if random.randint(0, 3) == 0: zaps2.append(get_rand_blip()) # Move zaps up the line for z in zaps1: z.update() if z.isFinished(): zaps1.remove(z) for z in zaps2: z.update() if z.isFinished(): zaps2.remove(z) # Increase offset to animate colors moving. Will eventually overflow, which # is fine. offset += 1 finally: # Ensure ws2811_fini is called before the program quits. ws.ws2811_fini(leds) # Example of calling delete function to clean up structure memory. Isn't # strictly necessary at the end of the program execution here, but is good practice. ws.delete_ws2811_t(leds) <file_sep># Halloween Lights Code to control WS281x addressable LEDs that I used to illuminate the outside of my house one Halloween. This code was adapted from a demo to include shooting 'bolts' of light with occaisional green flashes.
f472a7635552ecc89185fccb4f095704e039462c
[ "Markdown", "Python" ]
2
Python
MartinRandall/halloween-lights
28e227d451e0b705ec7348b3cc02a911e8e7bed4
1cbb4fbec1290b135c2124b962012643e187eed8
refs/heads/master
<repo_name>EinsteinSu/PrincessVsMonsterNew<file_sep>/settings.py class Settings(): def __init__(self): self.screen_width = 1200 self.screen_height = 800 self.bg_color = (0, 102, 204) self.princess_speed_factor = 0.5 self.princess_image_path = 'images\elsa.png' self.princess_limit = 3 self.magic_speed_factor = 1 self.magic_allowed = 100 self.magic_image_path = 'images\snow.png' self.monster_speed_factor = 1 self.monster_image_path = 'images\monster_64.png' self.monster_fleet_direction = 1 self.monster_fleet_moving_speed = 10 self.monster_points = 100 self.distance = 1 <file_sep>/princess_vs_monster.py import pygame from game_helper import GameHelper from game_stats import GameStats from settings import Settings from princess import Princess from pygame.sprite import Group from stats_board import StatsBoard def run_game(): pygame.init() settings = Settings() pygame.display.set_caption("Pincess VS Monster") screen = pygame.display.set_mode((settings.screen_width, settings.screen_height)) princess = Princess(settings, screen) magics = Group() monsters = Group() stats = GameStats(settings) statsBoard = StatsBoard(settings, screen, stats) game_helper = GameHelper(settings, screen, stats, princess, monsters, magics, None, statsBoard) game_helper.create_fleet() while True: game_helper.check_events() princess.update() magics.update() game_helper.update_magic() game_helper.update_monster() game_helper.update_screen() run_game() <file_sep>/magic.py import pygame from pygame.sprite import Sprite class Magic(Sprite): def __init__(self, settings, screen, princess): super(Magic, self).__init__() self.screen = screen self.image = pygame.image.load(settings.magic_image_path) self.rect = self.image.get_rect() self.rect.centerx = princess.rect.centerx self.rect.top = princess.rect.top self.x = float(self.rect.x) self.speed_factor = settings.magic_speed_factor def update(self): self.x += self.speed_factor self.rect.x = self.x def blit(self): self.screen.blit(self.image, self.rect) <file_sep>/game_helper.py import sys import pygame from magic import Magic from monster import Monster class GameHelper(): def __init__(self, settings, screen, stats, princess, monsters, magics, button, board): self.settings = settings self.screen = screen self.stats = stats self.princess = princess self.monsters = monsters self.magics = magics self.button = button self.board = board def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYUP: self.check_keyup(event) elif event.type == pygame.KEYDOWN: self.check_keydown(event) def check_keyup(self, event): if event.key == pygame.K_UP: self.princess.moving_up = False if event.key == pygame.K_DOWN: self.princess.moving_down = False if event.key == pygame.K_LEFT: self.princess.moving_left = False if event.key == pygame.K_RIGHT: self.princess.moving_right = False def check_keydown(self, event): if event.key == pygame.K_UP: self.princess.moving_up = True if event.key == pygame.K_DOWN: self.princess.moving_down = True if event.key == pygame.K_LEFT: self.princess.moving_left = True if event.key == pygame.K_RIGHT: self.princess.moving_right = True elif event.key == pygame.K_SPACE: self.use_magic() def update_screen(self): self.screen.fill(self.settings.bg_color) self.princess.blit() for magic in self.magics.sprites(): magic.blit() self.board.show_score() self.monsters.draw(self.screen) pygame.display.flip() def use_magic(self): if len(self.magics) < self.settings.magic_allowed: new_magic = Magic(self.settings, self.screen, self.princess) self.magics.add(new_magic) def update_magic(self): self.magics.update() for magic in self.magics.copy(): if magic.rect.right >= self.settings.screen_width: self.magics.remove(magic) self.check_magic_monster_collisions() def update_monster(self): self.check_monster_fleet_edges() self.monsters.update() if pygame.sprite.spritecollideany(self.princess, self.monsters): print('game over!') def create_fleet(self): monster = Monster(self.settings, self.screen) number_monster_y = self.get_number_monsters_y(monster.rect.height) number_cols = self.get_number_cols(monster.rect.width) for col in range(number_cols): for row in range(number_monster_y): self.create_monster(col, row) def create_monster(self, col_number, row_number): monster = Monster(self.settings, self.screen) monster_height = monster.rect.height monster.y = monster_height + 2 * monster_height * row_number monster_width = monster.rect.width monster.rect.x = self.settings.screen_width - 2 * monster_width * col_number print("monster x: " + str(monster.rect.x)) monster.rect.y = monster.y print("monster y: " + str(monster.rect.y)) self.monsters.add(monster) def get_number_cols(self, monster_width): avaliable_space_x = ( self.settings.screen_width - self.princess.rect.width) - 3 * monster_width - self.settings.distance number_cols = int(avaliable_space_x / (2 * monster_width)) return number_cols def get_number_monsters_y(self, monster_height): avaliable_space_y = self.settings.screen_height - 2 * monster_height number_monsters_y = int(avaliable_space_y / (2 * monster_height)) return number_monsters_y def check_monster_fleet_edges(self): for monster in self.monsters.sprites(): if monster.check_edges(): self.change_monster_fleet_direction() break def change_monster_fleet_direction(self): for monster in self.monsters.sprites(): monster.rect.x -= self.settings.monster_fleet_moving_speed self.settings.monster_fleet_direction *= -1 def check_magic_monster_collisions(self): collisions = pygame.sprite.groupcollide(self.magics, self.monsters, True, True) if collisions: for monster in collisions.values(): self.stats.score += self.settings.monster_points * len(monster) self.board.prep_score() self.check_high_score() if len(self.monsters) == 0: self.stats.level += 1 self.board.prep_level() self.magics.empty() self.create_fleet() # todo: calculate score, create monsters def check_high_score(self): if self.stats.score > self.stats.high_score: self.stats.high_score = self.stats.score self.board.prep_high_score() <file_sep>/game_stats.py class GameStats(): def __init__(self, settings): self.settings = settings self.reset_stats() self.game_active = True def reset_stats(self): self.princess_left = self.settings.princess_limit self.score = 0 self.high_score = 0 self.level = 1 <file_sep>/game_function.py import pygame def update_screen(settings, screen, princess): screen.fill(settings.bg_color) princess.blit() pygame.display.flip()
92026cb0a63683627e6c3b8f3ae23f518a17beac
[ "Python" ]
6
Python
EinsteinSu/PrincessVsMonsterNew
bc705a03ad63eea1ad06e3f12a042267cf5e1bd2
f8402a8edc24573ad063adf660d63d7eb50b5d80
refs/heads/master
<repo_name>emptyland/arduino<file_sep>/HumenSenor/HumenSenor.ino #include <Wire.h> void setup() { Serial.begin(9600); pinMode(3, INPUT); } void loop() { int val = digitalRead(3); Serial.print("val="); Serial.print(val); Serial.print("\n"); delay(100); } <file_sep>/DoubleWheel/DoubleWheel.ino #include <PID_v1.h> #include <Wire.h> #include "I2Cdev.h" #include "MPU6050.h" #include "Kalman.h" #define MOTOR_E1 3 #define MOTOR_M1 2 #define MOTOR_E2 5 #define MOTOR_M2 4 MPU6050 acc; // Create the Kalman instances Kalman kalmanY; Kalman kalmanX; double gyroXangle, compAngleX, kalAngleX; double gyroYangle, compAngleY, kalAngleY; double setPoint = 1.2, output = 0; double halfRange = 0.0; const double kP = 30, kD = 65, kI = 1; const int outputMax = 255, outputMin = -255; const int minPower = 0; uint32_t timer; //Specify the links and initial tuning parameters PID pid(&kalAngleX, &output, &setPoint, kP, kD, kI, DIRECT); void motor(int pwm) { if (pwm > 0) { pwm = (pwm + minPower); if (pwm > 255) pwm = 255; // right digitalWrite(MOTOR_M2, HIGH); analogWrite(MOTOR_E2, pwm); // left digitalWrite(MOTOR_M1, LOW); analogWrite(MOTOR_E1, pwm); } else { pwm = (-pwm + minPower); if (pwm > 255) pwm = 255; // left digitalWrite(MOTOR_M1, HIGH); analogWrite(MOTOR_E1, pwm); // right digitalWrite(MOTOR_M2, LOW); analogWrite(MOTOR_E2, pwm); } } void motorForward(int pwm) { // right digitalWrite(MOTOR_M2, LOW); analogWrite(MOTOR_E2, pwm); // left digitalWrite(MOTOR_M1, HIGH); analogWrite(MOTOR_E1, pwm); } void motorBackward(int pwm) { // left digitalWrite(MOTOR_M1, LOW); analogWrite(MOTOR_E1, pwm); // right digitalWrite(MOTOR_M2, HIGH); analogWrite(MOTOR_E2, pwm); } void motorStop() { // left digitalWrite(MOTOR_E1, LOW); digitalWrite(MOTOR_M1, HIGH); // right digitalWrite(MOTOR_E2, LOW); digitalWrite(MOTOR_M2, HIGH); } void setup() { Serial.begin(115200); Wire.begin(); pinMode(MOTOR_E1, OUTPUT); pinMode(MOTOR_M1, OUTPUT); pinMode(MOTOR_E2, OUTPUT); pinMode(MOTOR_M2, OUTPUT); timer = micros(); acc.initialize(); //turn the PID on //fwdPID.Initialize(); pid.SetMode(AUTOMATIC); pid.SetSampleTime(20); pid.SetOutputLimits(outputMin, outputMax); int16_t ax, ay, az, gx, gy, gz; acc.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); double roll = atan2(ay, az) * RAD_TO_DEG; double pitch = atan(-ax / sqrt(ay * ay + az * az)) * RAD_TO_DEG; kalmanX.setAngle(roll); // Set starting angle kalmanY.setAngle(pitch); gyroXangle = roll; gyroYangle = pitch; compAngleX = roll; compAngleY = pitch; } void loop() { double dt = (double)(micros() - timer) / 1000000; // Calculate delta time timer = micros(); int16_t ax, ay, az, gx, gy, gz; acc.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); double roll = atan2(ay, az) * RAD_TO_DEG; double pitch = atan(-ax / sqrt(ay * ay + az * az)) * RAD_TO_DEG; double gyroXrate = gx / 131.0; // Convert to deg/s double gyroYrate = gy / 131.0; // Convert to deg/s // This fixes the transition problem when the accelerometer angle jumps between -180 and 180 degrees if ((roll < -90 && kalAngleX > 90) || (roll > 90 && kalAngleX < -90)) { kalmanX.setAngle(roll); compAngleX = roll; kalAngleX = roll; gyroXangle = roll; } else kalAngleX = kalmanX.getAngle(roll, gyroXrate, dt); // Calculate the angle using a Kalman filter if (abs(kalAngleX) > 90) gyroYrate = -gyroYrate; // Invert rate, so it fits the restriced accelerometer reading kalAngleY = kalmanY.getAngle(pitch, gyroYrate, dt); gyroXangle += gyroXrate * dt; // Calculate gyro angle without any filter gyroYangle += gyroYrate * dt; //gyroXangle += kalmanX.getRate() * dt; // Calculate gyro angle using the unbiased rate //gyroYangle += kalmanY.getRate() * dt; compAngleX = 0.93 * (compAngleX + gyroXrate * dt) + 0.07 * roll; // Calculate the angle using a Complimentary filter compAngleY = 0.93 * (compAngleY + gyroYrate * dt) + 0.07 * pitch; // Reset the gyro angle when it has drifted too much if (gyroXangle < -180 || gyroXangle > 180) gyroXangle = kalAngleX; if (gyroYangle < -180 || gyroYangle > 180) gyroYangle = kalAngleY; pid.Compute(); if (kalAngleX > setPoint + halfRange < 60) { motor(output); } else if (kalAngleX < setPoint - halfRange > -60) { motor(output); } else { motorStop(); } Serial.print(roll); Serial.print("\t"); Serial.print(kalAngleX); Serial.print("\t"); Serial.print(gyroXangle); Serial.print("\t"); Serial.print(compAngleX); Serial.print("\t"); Serial.print(output); Serial.print("\n"); //delay(30); } <file_sep>/hardware/digistump/avr/libraries/DigisparkRGB/DigisparkRGB.cpp #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> #include "DigisparkRGB.h" #include "Arduino.h" #define set(x) |= (1<<x) #define clr(x) &=~(1<<x) #define inv(x) ^=(1<<x) #define BLUE_CLEAR (pinlevelB &= ~(1 << BLUE)) // map BLUE to PB2 #define GREEN_CLEAR (pinlevelB &= ~(1 << GREEN)) // map BLUE to PB2 #define RED_CLEAR (pinlevelB &= ~(1 << RED)) // map BLUE to PB2 #define PORTB_MASK (1 << PB0) | (1 << PB1) | (1 << PB2) #define BLUE PB2 #define GREEN PB1 #define RED PB0 unsigned char DigisparkPWMcompare[3]; volatile unsigned char DigisparkPWMcompbuff[3]; void DigisparkRGBBegin() { pinMode(2, OUTPUT); pinMode(1, OUTPUT); pinMode(0, OUTPUT); //CLKPR = (1 << CLKPCE); // enable clock prescaler update //CLKPR = 0; // set clock to maximum (= crystal) DigisparkPWMcompare[0] = 0x00;// set default PWM values DigisparkPWMcompare[1] = 0x00;// set default PWM values DigisparkPWMcompare[2] = 0x00;// set default PWM values DigisparkPWMcompbuff[0] = 0x00;// set default PWM values DigisparkPWMcompbuff[1] = 0x00;// set default PWM values DigisparkPWMcompbuff[2] = 0x00;// set default PWM values TIFR = (1 << TOV0); // clear interrupt flag TIMSK = (1 << TOIE0); // enable overflow interrupt TCCR0B = (1 << CS00); // start timer, no prescale sei(); } void DigisparkRGB(int pin,int value){ DigisparkPWMcompbuff[pin] = value; } void DigisparkRGBDelay(int ms) { while (ms) { _delay_ms(1); ms--; } } ISR (TIM0_OVF_vect) { static unsigned char pinlevelB=PORTB_MASK; static unsigned char softcount=0xFF; PORTB = pinlevelB; // update outputs if(++softcount == 0){ // increment modulo 256 counter and update // the compare values only when counter = 0. DigisparkPWMcompare[0] = DigisparkPWMcompbuff[0]; // verbose code for speed DigisparkPWMcompare[1] = DigisparkPWMcompbuff[1]; // verbose code for speed DigisparkPWMcompare[2] = DigisparkPWMcompbuff[2]; // verbose code for speed pinlevelB = PORTB_MASK; // set all port pins high } // clear port pin on compare match (executed on next interrupt) if(DigisparkPWMcompare[0] == softcount) RED_CLEAR; if(DigisparkPWMcompare[1] == softcount) GREEN_CLEAR; if(DigisparkPWMcompare[2] == softcount) BLUE_CLEAR; } <file_sep>/hardware/digistump/sam/libraries/DigiXBetaBonus/Bonus_Encoder_Working/Bonus_Encoder_Working.ino /* Software Debouncing - Mechanical Rotary Encoder */ #define encoder0PinA 9 #define encoder0PinB 10 const int buttonPin = 12; volatile unsigned int encoder0Pos = 0; static boolean rotating=false; int buttonState; // the current reading from the input pin int lastButtonState = LOW; // the previous reading from the input pin long lastDebounceTime = 0; // the last time the output pin was toggled long debounceDelay = 50; // the debounce time; increase if the output flickers void setup() { pinMode(buttonPin, INPUT); digitalWrite(buttonPin, HIGH); pinMode(encoder0PinA, INPUT); digitalWrite(encoder0PinA, HIGH); pinMode(encoder0PinB, INPUT); digitalWrite(encoder0PinB, HIGH); attachInterrupt(encoder0PinA, rotEncoder, CHANGE); SerialUSB.begin (9600); } void rotEncoder(){ rotating=true; // If a signal change (noise or otherwise) is detected // in the rotary encoder, the flag is set to true } void loop() { while(rotating) { delay(2); // When signal changes we wait 2 milliseconds for it to // stabilise before reading (increase this value if there // still bounce issues) if (digitalRead(encoder0PinA) == digitalRead(encoder0PinB)) { encoder0Pos++; } else { encoder0Pos--; } rotating=false; // Reset the flag back to false SerialUSB.println(encoder0Pos); } int reading = digitalRead(buttonPin); // check to see if you just pressed the button // (i.e. the input went from LOW to HIGH), and you've waited // long enough since the last press to ignore any noise: // If the switch changed, due to noise or pressing: if (reading != lastButtonState) { // reset the debouncing timer lastDebounceTime = millis(); SerialUSB.print("Button: "); SerialUSB.println(reading); } if ((millis() - lastDebounceTime) > debounceDelay) { // whatever the reading is at, it's been there for longer // than the debounce delay, so take it as the actual current state: buttonState = reading; } // save the reading. Next time through the loop, // it'll be the lastButtonState: lastButtonState = reading; } <file_sep>/hardware/digistump/avr/libraries/Digispark_Examples/Expander/Expander.ino #include <TinyWireM.h> #define expander 0x20 byte expanderStatus = B11111111; //all off void setup() { TinyWireM.begin(); } void loop() { expanderWrite(0,HIGH); delay(1000); expanderWrite(0,LOW); delay(1000); } void expanderWrite(byte pinNumber, boolean state){ if(state == HIGH) expanderStatus &= ~(1 << pinNumber); else expanderStatus |= (1 << pinNumber); expanderWrite(expanderStatus); } void expanderWrite(byte _data ) { TinyWireM.beginTransmission(expander); TinyWireM.send(_data); TinyWireM.endTransmission(); } <file_sep>/libraries/QS301/qs301.cpp #include <arduino.h> #include "qs301.h" const int QS301Module::kNumBits[11] = { 0x0, // OFF 1, // 0 1 << 9, // 1 1 << 8, // 2 1 << 7, // 3 1 << 6, // 4 1 << 5, // 5 1 << 4, // 6 1 << 3, // 7 1 << 2, // 8 1 << 1, // 9 }; void QS301Module::init(int din, int oe, int stcp, int shcp) { kDin_ = din; kOE_ = oe; kStcp_ = stcp; kShcp_ = shcp; color_ = COLOR_OFF; number_ = NUM_OFF; colon_ = COLON_OFF; pinMode(kDin_, OUTPUT); pinMode(kOE_, OUTPUT); pinMode(kStcp_, OUTPUT); pinMode(kShcp_, OUTPUT); digitalWrite(kDin_, LOW); digitalWrite(kOE_, LOW); digitalWrite(kStcp_, LOW); digitalWrite(kShcp_, LOW); } void QS301Module::setNumber(int number) { int bits; if (number < 0) { number = -1; // off } if (number > 9) { number = -1; // error } number_ = kNumBits[number + 1]; } void QS301Module::flushBits(int bits, int n) { for (int i = 0; i < n; ++i) { digitalWrite(kDin_, (bits >> (n - i - 1)) & 0x1); digitalWrite(kShcp_, HIGH); digitalWrite(kShcp_, LOW); } } void QS301Module::commit() { digitalWrite(kStcp_, HIGH); digitalWrite(kStcp_, LOW); } void QS301Module::flush() { flushBits(color_, 3); flushBits(number_, 10); flushBits(colon_, 3); } <file_sep>/hardware/digistump/avr/libraries/Digispark_Examples/Infrared/Infrared.ino int irPin=2; void setup() { pinMode(irPin,INPUT); pinMode(0,OUTPUT); //Serial.begin(9600); digitalWrite(0,HIGH); //Serial.println("You pressed a button"); delay(1000); digitalWrite(0,LOW); } void loop() { if(pulseIn(irPin,LOW)) { //button pressed delay(100); digitalWrite(0,HIGH); //Serial.println("You pressed a button"); delay(1000); digitalWrite(0,LOW); } } <file_sep>/hardware/digistump/avr/libraries/DigisparkRGB/DigisparkRGB.h /* DigisparkPWM.h - Library for pwm on PB2 on ATTINY85. Created by Digistump Released into the public domain. */ #ifndef DigisparkRGB_h #define DigisparkRGB_h void DigisparkRGBBegin(); void DigisparkRGBDelay(int ms); void DigisparkRGB(int pin,int value); #endif<file_sep>/OutsideStation/OutsideStation.ino #include <dht11.h> #include <Bridge.h> #include <Console.h> #include <FileIO.h> #include <HttpClient.h> #include <Mailbox.h> #include <Process.h> #include <YunClient.h> #include <YunServer.h> YunServer server; dht11 dht; int E1 = 2; int M1 = 3; int GROUND_0 = 5; int GROUND_1 = 4; int DHT11 = 4; void setup() { // put your setup code here, to run once: pinMode(M1, OUTPUT); //pinMode(GROUND_0, INPUT); Serial.begin(9600); Bridge.begin(); server.noListenOnLocalhost(); server.begin(); } void sendFail(YunClient client, int code, String result) { client.print(F("{\"code\": ")); client.print(code); client.print(F(", \"result\": \"")); client.print(result); client.println(F("\"}")); } void sendIntResult(YunClient client, int code, int result) { client.print(F("{\"code\": ")); client.print(code); client.print(F(", \"result\": \"")); client.print(result); client.println(F("\"}")); } void waterPollControl(YunClient client, int number) { if (client.read() != '/') { sendFail(client, 500, "invalid params"); return; } int on = client.parseInt(); if (on == 1 && client.read() != '/') { sendFail(client, 500, "invalid params"); return; } int power = client.parseInt(); switch (number) { case 0: digitalWrite(E1, on); analogWrite(M1, power); sendIntResult(client, 200, on); break; case 1: break; default: sendFail(client, 500, "no more water poll"); break; } } void groundStatus(YunClient client, int number) { switch (number) { case 0: sendIntResult(client, 200, analogRead(GROUND_0)); break; case 1: sendIntResult(client, 200, analogRead(GROUND_1)); break; default: sendFail(client, 500, "no more ground status"); break; } } void envStatus(YunClient client, int number) { int chk = dht.read(DHT11); switch (chk){ case DHTLIB_OK: break; case DHTLIB_ERROR_CHECKSUM: sendFail(client, 500, "DHT11 checksum error."); return; case DHTLIB_ERROR_TIMEOUT: sendFail(client, 500, "DHT11 time out."); return; default: sendFail(client, 500, "DHT11 unknown error."); return; } switch (number) { case 0: sendIntResult(client, 200, dht.temperature); break; case 1: sendIntResult(client, 200, dht.humidity); break; default: sendFail(client, 500, "no more env status"); break; } } void process(YunClient client) { String command = client.readStringUntil('/'); Serial.println(command); if (command.startsWith("GET")) { String method = client.readStringUntil('/'); if (method.startsWith("ground")) { int number = client.parseInt(); groundStatus(client, number); } else if (method.startsWith("env")) { int number = client.parseInt(); envStatus(client, number); } else { sendFail(client, 404, "method not be support!"); } } else if (command.startsWith("PUT")) { String method = client.readStringUntil('/'); if (method.startsWith("water")) { int number = client.parseInt(); waterPollControl(client, number); } else { sendFail(client, 404, "method not be support!"); } } else if (command.startsWith("POST")) { } else { Serial.print(command); Serial.println("not be support!"); sendFail(client, 404, "method not be support!"); } } void loop() { YunClient client = server.accept(); if (client) { process(client); client.stop(); } delay(50); } <file_sep>/libraries/BMA220/bma220.h #ifndef BMA220_H_ #define BMA220_H_ #include <Wire.h> class BMA220 { public: void init (uint8_t range); void getMonitor3(int8_t *ax, int8_t *ay, int8_t *az); int getDivi() { return divi_; } private: int divi_; uint8_t version_[3]; }; #endif // BMA220_H_ <file_sep>/hardware/digistump/sam/libraries/DigiXBetaBonus/Bonus_RGB/Bonus_RGB.ino int RedPin = 5; int GreenPin = 6; int BluePin = 7; void setup() { // put your setup code here, to run once: pinMode(RedPin, OUTPUT); pinMode(GreenPin, OUTPUT); pinMode(BluePin, OUTPUT); } void loop() { randomSeed(analogRead(0)); // put your main code here, to run repeatedly: analogWrite(RedPin,random(255)); analogWrite(GreenPin,random(255)); analogWrite(BluePin,random(255)); delay(500); } <file_sep>/TempClock/TempClock.ino #include "si7021.h" #include "bma220.h" #include "DS1307.h" #include "qs301.h" #include <Wire.h> DS1307 clock; QS301Module qs31; BMA220 acc; Si7021 temp; #define ROUTINE_TIME 0 #define ROUTINE_TEMP 1 #define ROUTINE_HUMIDITY 2 #define ROUTINE_MAX 3 int state = ROUTINE_TIME; void accMontior(int mills) { static unsigned long o_acc_millis = millis(); mills /= 10; while (mills--) { int8_t ax = 0, ay = 0, az = 0; acc.getMonitor3(&ax, &ay, &az); if ((ax > 20 || ay > 20 || az > 30) && millis() - o_acc_millis >= 100) { // Serial.print("X="); // Serial.print(ax); // print the character // Serial.print(" "); // Serial.print("Y="); // Serial.print(ay); // print the character // Serial.print(" "); // Serial.print("Z="); // print the character // Serial.println(az); state = (state + 1) % ROUTINE_MAX; o_acc_millis = millis(); return; } delay(10); } } void clockRoutine() { static unsigned long o_clk_millis = millis(); static int colonCounter = 0; clock.getTime(); // hour qs31.setColor(COLOR_OFF); qs31.setNumber(clock.hour / 10); qs31.setColon(COLON_OFF); qs31.flush(); qs31.setColor(COLOR_OFF); qs31.setNumber(clock.hour % 10); if (millis() - o_clk_millis >= 500) { o_clk_millis = millis(); colonCounter++; } if (colonCounter % 2 == 0) { qs31.setColon(COLON_DOT | COLON_TOP); } else { qs31.setColon(COLON_OFF); } qs31.flush(); // minute qs31.setColor(COLOR_OFF); qs31.setNumber(clock.minute / 10); qs31.setColon(COLON_OFF); qs31.flush(); qs31.setColor(COLOR_OFF); qs31.setNumber(clock.minute % 10); qs31.setColon(COLON_OFF); qs31.flush(); qs31.commit(); accMontior(100); } void tempRoutine(bool isTemp) { double x = 0, y = 0; temp.getMonitor2(&x, &y); int color = 0; if (isTemp) { if (x < 0) { color = COLOR_BLUE; } else { color = COLOR_YELLOW; } } else { color = COLOR_GREEN; } // 12.34 // 1234 // / 1000 = 1 // (/ 100) % 10 // (/ 10) % 10 int value = 0; if (isTemp) { value = abs((int)(x * 100)); } else { value = abs((int)(y * 100)); } // Serial.print("value="); // Serial.print(value); // Serial.print("\n"); qs31.setColor(color); qs31.setNumber(value / 1000); qs31.setColon(COLON_OFF); qs31.flush(); qs31.setColor(color); qs31.setNumber((value / 100) % 10); qs31.setColon(COLON_DOT); qs31.flush(); qs31.setColor(color); qs31.setNumber((value / 10) % 10); qs31.setColon(COLON_OFF); qs31.flush(); qs31.setColor(color); qs31.setNumber(value % 10); qs31.setColon(COLON_OFF); qs31.flush(); qs31.commit(); accMontior(300); } void setup() { qs31.init(8, 7, 6, 5); clock.begin(); acc.init(0); Serial.begin(9600); // clock.second = 0; // clock.minute = 05; // clock.hour = 11; // clock.dayOfMonth = 29; // clock.month = 8; // clock.year = 2015; // clock.setTime(); } void loop() { switch (state) { case ROUTINE_TIME: clockRoutine(); break; case ROUTINE_TEMP: tempRoutine(true); break; case ROUTINE_HUMIDITY: tempRoutine(false); break; } } <file_sep>/libraries/BMA220/bma220.cpp #include "bma220.h" #include <Wire.h> void BMA220::init(uint8_t range) { Wire.begin(); Wire.beginTransmission(0x0A); // address of the accelerometer // range settings Wire.write(0x22); //register address Wire.write(range); //can be set at"0x00""0x01""0x02""0x03", refer to Datashhet on wiki // low pass filter Wire.write(0x20); //register address Wire.write(0x05); //can be set at"0x05""0x04"......"0x01""0x00", refer to Datashhet on wiki Wire.endTransmission(); switch(range) //change the data dealing method based on the range u've set { case 0x00: divi_=16; break; case 0x01: divi_=8; break; case 0x02: divi_=4; break; case 0x03: divi_=2; break; default: //Serial.println("range setting is Wrong,range:from 0to 3.Please check!"); while(1); } } void BMA220::getMonitor3(int8_t *ax, int8_t *ay, int8_t *az) { Wire.beginTransmission(0x0A); // address of the accelerometer // reset the accelerometer Wire.write(0x04); // Y data Wire.endTransmission(); Wire.requestFrom(0x0A,1); // request 6 bytes from slave device #2 while(Wire.available()) // slave may send less than requested { version_[0] = Wire.read(); // receive a byte as characte } *ax=(int8_t)version_[0]>>2; Wire.beginTransmission(0x0A); // address of the accelerometer // reset the accelerometer Wire.write(0x06); // Y data Wire.endTransmission(); Wire.requestFrom(0x0A,1); // request 6 bytes from slave device #2 while(Wire.available()) // slave may send less than requested { version_[1] = Wire.read(); // receive a byte as characte } *ay=(int8_t)version_[1]>>2; Wire.beginTransmission(0x0A); // address of the accelerometer // reset the accelerometer Wire.write(0x08); // Y data Wire.endTransmission(); Wire.requestFrom(0x0A,1); // request 6 bytes from slave device #2 while(Wire.available()) // slave may send less than requested { version_[2] = Wire.read(); // receive a byte as characte } *az=(int8_t)version_[2]>>2; } <file_sep>/libraries/Si7021/si7021.cpp #include "si7021.h" #include <Wire.h> void Si7021::init() { Wire.begin(); Wire.beginTransmission(0x40); Wire.endTransmission(); } void Si7021::getMonitor2(double *temp, double *humidity) { int X0,X1,Y0,Y1,Y2,Y3; double X,Y,X_out,Y_out1,Y_out2; /**发送温度测量命令**/ Wire.beginTransmission(0x40); Wire.write(0xE3); //发送读温度命令 Wire.endTransmission(); /**读取温度数据**/ Wire.requestFrom(0x40,2); //回传数据 if(Wire.available()<=2); { X0 = Wire.read(); X1 = Wire.read(); X0 = X0<<8; X_out = X0+X1; } /**计算并显示温度**/ X=(175.72*X_out)/65536; *temp=X-46.85; /**发送湿度测量命令**/ Wire.beginTransmission(0x40); Wire.write(0xE5); Wire.endTransmission(); /**读取湿度数据**/ Wire.requestFrom(0x40,2); if(Wire.available()<=2); { Y0 = Wire.read(); Y2=Y0/100; Y0=Y0%100; Y1 = Wire.read(); Y_out1 = Y2*25600; Y_out2 = Y0*256+Y1; } /**计算并显示湿度**/ Y_out1 = (125*Y_out1)/65536; Y_out2 = (125*Y_out2)/65536; Y = Y_out1+Y_out2; *humidity=Y-6; } <file_sep>/hardware/digistump/avr/libraries/SoftRcPulseOut/examples/SerialServo/SerialServo.ino // This SoftwareServo library example sketch was initially delivered without any comments. // Below my own comments for SoftRcPulseOut library: by RC Navy (http://p.loussouarn.free.fr) // Controlling the position of 2 servos using the Arduino built-in hardware UART (Arduino Serial object). // This sketch do NOT work with an ATtinyX4 and ATtinyX5 since they do not have a built-in harware UART (no Arduino Serial object). // The command (issued in the Arduino Serial Console or in a Terminal) is: // S=P with: // S=A for Servo1 and S=B for Servo2 // P=Position number x 20° (Possible positions are from 0 to 9 which correspond to from 0° to 180°) // Ex: // A=7 sets Servo1 at 7 x 20 =140° // B=3 sets Servo2 at 3 x 20 =60° #include <SoftRcPulseOut.h> SoftRcPulseOut servo1; SoftRcPulseOut servo2; void setup() { pinMode(13,OUTPUT); servo1.attach(2); servo1.setMaximumPulse(2200); servo2.attach(4); servo2.setMaximumPulse(2200); Serial.begin(9600); Serial.print("Ready"); } void loop() { static int value = 0; static char CurrentServo = 0; if ( Serial.available()) { char ch = Serial.read(); switch(ch) { case 'A': CurrentServo='A'; digitalWrite(13,LOW); break; case 'B': CurrentServo='B'; digitalWrite(13,HIGH); break; case '0' ... '9': value=(ch-'0')*20; if (CurrentServo=='A') { servo1.write(value); } else if (CurrentServo=='B') { servo2.write(value); } break; } } SoftRcPulseOut::refresh(); } <file_sep>/ColorLight/ColorLight.ino #define PIN_RED 0 #define PIN_GREEN 1 #define PIN_BLUE 2 void setup() { //Serial.begin(9600); pinMode(PIN_RED, OUTPUT); pinMode(PIN_GREEN, OUTPUT); pinMode(PIN_BLUE, OUTPUT); pinMode(4, INPUT); //pinMode(0, OUTPUT); } void loop() { int val = digitalRead(4); digitalWrite(PIN_RED, val); digitalWrite(PIN_GREEN, val); digitalWrite(PIN_BLUE, val); } <file_sep>/hardware/digistump/avr/libraries/Digispark_Examples/Rfm12b/Rfm12b.ino // This sketch will send a RFM12b packet that is compatible with the Jeelib and can be picked up by a JeeNode running RFM12 demo sketch //See http://jeelabs.org/2011/06/09/rf12-packet-format-and-design/ //for packet design #define GROUP 212 #define HEADER 17 //433mhz = 1, 868mhz = 2, 915mhz = 3 #define RF12_FREQ 1 #define RF12_NOT_CS() PORTB |= _BV(PB3) #define RF12_CS() PORTB &= ~_BV(PB3) #define MOSI_LOW() PORTB &= ~_BV(PB1) #define MISO_LEVEL() (PINB & _BV(PB0)) #define RF12_TRANSMIT 0xB8 union { unsigned char byte; struct { char ATS_RSSI: 1; //ATS=Antenna tuning circuit detected strong enough RF signal //RSSI=The strength of the incoming signal is above the pre-programmed limit char FFEM: 1; //FIFO is empty char LBD: 1; //Low battery detect, the power supply voltage is below the pre-programmed limit char EXT: 1; //Logic level on interrupt pin (pin 16) changed to low (Cleared after Status Read Command) char WKUP: 1; //Wake-up timer overflow (Cleared after Status Read Command ) char RGUR_FFOV: 1; //RGUR=TX register under run, register over write (Cleared after Status Read Command ) //FFOV=RX FIFO overflow (Cleared after Status Read Command ) char POR: 1; //Power-on reset (Cleared after Status Read Command ) char RGIT_FFIT: 1; //RGIT=TX register is ready to receive the next byte //(Can be cleared by Transmitter Register Write Command) //FFIT=The number of data bits in the RX FIFO has reached the pre-programmed limit //(Can be cleared by any of the FIFO read methods) }bits; } status_H; union { unsigned char byte; struct { char OFFS: 4; //Offset value to be added to the value of the frequency control parameter (Four LSB bits) char OFFS6: 1; //MSB of the measured frequency offset (sign of the offset value) char ATGL: 1; //Toggling in each AFC cycle char CRL: 1; //Clock recovery locked char DQD: 1; //Data quality detector output }bits; } status_L; void setup(){ DDRB = _BV(PB1) | _BV(PB2) | _BV(PB3) | _BV(PB4); // MOSI, SCK, SEL PORTB = _BV(PB3); // deselect RFM12 rf12_init(); } //Some extremely dummy packet payload, just to show it works.. uint8_t data[] = { "TEST" }; void loop(){ rf12_cmd(0x82,0x38); //Enable transciever rf12_send((uint8_t *)&data, sizeof(data)); //wait till the next-to-last byte is sent (the last is the dummy) while (!rf12_read_status_MSB()); rf12_cmd(0x82,0x08); //Disable transciever delay(3000); } static void spi_run_clock () { USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); USICR = _BV(USIWM0) | _BV(USITC); USICR = _BV(USIWM0) | _BV(USITC) | _BV(USICLK); } void rf12_cmd(uint8_t highbyte, uint8_t lowbyte) { RF12_CS(); USIDR = highbyte; spi_run_clock(); USIDR = lowbyte; spi_run_clock(); RF12_NOT_CS(); } void rf12_loop_until_FFIT_RGIT(void) { do { rf12_read_status_MSB(); } while (!status_H.bits.RGIT_FFIT); } /* rf12_read_status_MSB RX Mode: FFIT = The number of data bits in the RX FIFO has reached the pre-programmed limit. Can be cleared by any of the FIFO read methods TX Mode: RGIT = TX register is ready to receive the next byte (Can be cleared by Transmitter Register Write Command) */ uint8_t rf12_read_status_MSB(void) { RF12_CS(); MOSI_LOW(); asm volatile("nop"); if (MISO_LEVEL()) status_H.bits.RGIT_FFIT=1; else status_H.bits.RGIT_FFIT=0; RF12_NOT_CS(); return status_H.bits.RGIT_FFIT; } void rf12_read_status(void) { RF12_CS(); USIDR = 0x00; //Status Read Command spi_run_clock(); status_H.byte = USIDR; USIDR = 0x00; //Status Read Command spi_run_clock(); status_L.byte = USIDR; RF12_NOT_CS(); } void rf12_TX(uint8_t aByte) { //FFIT wird gepollt um zu erkennen ob das FIFO TX //Register bereit ist. //Alternativ ist es auch möglich(wenn verbunden) //den Interrupt Ausgang des RF12 zu pollen: while(INT1_LEVEL()); while (!rf12_read_status_MSB()); rf12_cmd(RF12_TRANSMIT,aByte); } #if RF12_RECEIVE_CODE uint8_t rf12_RX(void) { rf12_loop_until_FFIT_RGIT(); RF12_CS(); USIDR = 0xB0; spi_run_clock(); USIDR = 0x00; spi_run_clock(); RF12_NOT_CS(); return USIDR; } #endif static __inline__ uint16_t _crc16_update(uint16_t __crc, uint8_t __data) { uint8_t __tmp; uint16_t __ret; __asm__ __volatile__ ( "eor %A0,%2" "\n\t" "mov %1,%A0" "\n\t" "swap %1" "\n\t" "eor %1,%A0" "\n\t" "mov __tmp_reg__,%1" "\n\t" "lsr %1" "\n\t" "lsr %1" "\n\t" "eor %1,__tmp_reg__" "\n\t" "mov __tmp_reg__,%1" "\n\t" "lsr %1" "\n\t" "eor %1,__tmp_reg__" "\n\t" "andi %1,0x07" "\n\t" "mov __tmp_reg__,%A0" "\n\t" "mov %A0,%B0" "\n\t" "lsr %1" "\n\t" "ror __tmp_reg__" "\n\t" "ror %1" "\n\t" "mov %B0,__tmp_reg__" "\n\t" "eor %A0,%1" "\n\t" "lsr __tmp_reg__" "\n\t" "ror %1" "\n\t" "eor %B0,__tmp_reg__" "\n\t" "eor %A0,%1" : "=r" (__ret), "=d" (__tmp) : "r" (__data), "0" (__crc) : "r0" ); return __ret; } void rf12_send(const uint8_t* buf, uint8_t cnt) { if (!cnt) return; uint16_t chksum=~0; //See http://jeelabs.org/2011/06/09/rf12-packet-format-and-design/ //http://jeelabs.org/2010/12/07/binary-packet-decoding/ rf12_TX(0xAA); //PREAMBLE rf12_TX(0xAA); //PREAMBLE rf12_TX(0xAA); //PREAMBLE rf12_TX(0x2D); //SYNC HI BYTE rf12_TX(GROUP); //SYNC LOW BYTE (group 210) chksum = _crc16_update(chksum, GROUP); rf12_TX(HEADER); // Header byte chksum = _crc16_update(chksum, HEADER); rf12_TX(cnt); chksum = _crc16_update(chksum, cnt); while (cnt--) { rf12_TX(*buf); chksum = _crc16_update(chksum,*buf++); } rf12_TX(chksum); rf12_TX(chksum>>8); rf12_TX(0xAA); //dummy byte } #if RF12_RECEIVE_CODE //returns 0 if no data is available //returns -1(255) if there is a CRC Error //else, returns number of received byte uint8_t rf12_read(uint8_t* buf, const uint8_t max) { uint16_t checksum=~0; uint16_t received_checksum; uint8_t hdr; hdr=rf12_RX(); checksum = _crc16_update(checksum,hdr); uint8_t len; len=rf12_RX(); checksum = _crc16_update(checksum,len); uint8_t i=len; while (i--) { *buf=rf12_RX(); checksum = _crc16_update(checksum,*buf++); } received_checksum=rf12_RX(); received_checksum=received_checksum<<8; received_checksum |= rf12_RX(); if (received_checksum==checksum) return len; else return -1; } #endif void rf12_init(void) { USICR = _BV(USIWM0); // 3-wire, software clock strobe rf12_cmd(0x80, 0xC7 | (RF12_868MHZ << 4)); // EL (ena TX), EF (ena RX FIFO), 12.0pF rf12_cmd(0xA6,0x40); // 868MHz rf12_cmd(0xC6,0x06); // approx 49.2 Kbps, i.e. 10000/29/(1+6) Kbps rf12_cmd(0x94,0xA2); // VDI,FAST,134kHz,0dBm,-91dBm rf12_cmd(0xC2,0xAC); // AL,!ml,DIG,DQD4 rf12_cmd(0xCA,0x83); // FIFO8,2-SYNC,!ff,DR rf12_cmd(0xCE,0x00 | GROUP); // SYNC=2DXX; rf12_cmd(0xC4,0x83); // @PWR,NO RSTRIC,!st,!fi,OE,EN rf12_cmd(0x98,0x50); // !mp,90kHz,MAX OUT rf12_cmd(0xCC,0x77); // OB1,OB0, LPX,!ddy,DDIT,BW0 rf12_cmd(0xE0,0x00); // NOT USE rf12_cmd(0xC8,0x00); // NOT USE rf12_cmd(0xC0,0x40); // 1.66MHz,2.2V } <file_sep>/hardware/digistump/avr/variants/pro/pins_arduino.h /* pins_arduino.h - Pin definition functions for Arduino Part of Arduino - http://www.arduino.cc/ Copyright (c) 2007 <NAME> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $ */ #ifndef Pins_Arduino_h #define Pins_Arduino_h #define ATTINYX7 1 #include <avr/pgmspace.h> #define NUM_DIGITAL_PINS 14 #define NUM_ANALOG_INPUTS 10 #define analogInputToDigitalPin(p) ((p < 7) ? p+6 : (p ==7) ? 5 : (p==9) ? 4 : (p==10) ? 13 : -1) #define digitalPinHasPWM(p) ((p) == 0 || (p) == 1) #define SS 12 #define MOSI 10 #define MISO 8 #define SCK 11 static const uint8_t SDA = 0; static const uint8_t SCL = 2; //Ax constants cannot be used for digitalRead/digitalWrite/analogWrite functions, only analogRead(). static const uint8_t A4 = NUM_DIGITAL_PINS+9; static const uint8_t A5 = NUM_DIGITAL_PINS+7; static const uint8_t A6 = NUM_DIGITAL_PINS+0; static const uint8_t A7 = NUM_DIGITAL_PINS+1; static const uint8_t A8 = NUM_DIGITAL_PINS+2; static const uint8_t A9 = NUM_DIGITAL_PINS+3; static const uint8_t A10 = NUM_DIGITAL_PINS+4; static const uint8_t A11 = NUM_DIGITAL_PINS+5; static const uint8_t A12 = NUM_DIGITAL_PINS+6; static const uint8_t A13 = NUM_DIGITAL_PINS+10; //---------------------------------------------------------- //---------------------------------------------------------- //Core Configuration (used to be in core_build_options.h) //If Software Serial communications doesn't work, run the TinyTuner sketch provided with the core to give you a calibrated OSCCAL value. //Change the value here with the tuned value. By default this option uses the default value which the compiler will optimise out. #define TUNED_OSCCAL_VALUE OSCCAL //e.g //#define TUNED_OSCCAL_VALUE 0x57 //Choosing not to initialise saves power and flash. 1 = initialise. #define INITIALIZE_ANALOG_TO_DIGITAL_CONVERTER 1 #define INITIALIZE_SECONDARY_TIMERS 0 #define TIMER_TO_USE_FOR_MILLIS 0 #define HAVE_BOOTLOADER 1 /* Where to put the software serial? (Arduino Digital pin numbers) */ //WARNING, if using software, TX is on AIN0, RX is on AIN1. Comparator is favoured to use its interrupt for the RX pin. #define USE_SOFTWARE_SERIAL 0 //Please define the port on which the analog comparator is found. #define ANALOG_COMP_DDR DDRA #define ANALOG_COMP_PORT PORTA #define ANALOG_COMP_PIN PINA #define ANALOG_COMP_AIN0_BIT 6 #define ANALOG_COMP_AIN1_BIT 7 /* Analog reference bit masks. */ // VCC used as analog reference, disconnected from PA0 (AREF) #define DEFAULT (0) // External voltage reference at PA0 (AREF) pin, internal reference turned off #define EXTERNAL (1) // Internal 1.1V voltage reference #define INTERNAL (2) //---------------------------------------------------------- //---------------------------------------------------------- //---------------------------------------------------------- //---------------------------------------------------------- #define digitalPinToPCICR(p) (((p) >= 0 && (p) <= 10) ? (&GIMSK) : ((uint8_t *)NULL)) #define digitalPinToPCICRbit(p) (((p) >= 3 && (p) <= 10) ? 4 : 5) #define digitalPinToPCMSK(p) (((p) >= 3 && (p) <= 10) ? (&PCMSK0) : (((p) >= 0 && (p) <= 2) ? (&PCMSK1) : ((uint8_t *)NULL))) #define digitalPinToPCMSKbit(p) (((p) >= 3 && (p) <= 10) ? (10 - (p)) : (p)) #ifdef ARDUINO_MAIN // On the Arduino board, digital pins are also used // for the analog output (software PWM). Analog input // pins are a separate set. // ATMEL ATTINY167 // // +-\/-+ // RX (D 0) PA0 1| |20 PB0 (D 4) // TX (D 1) PA1 2| |19 PB1 (D 5) // *(D 12) PA2 3| |18 PB2 (D 6) // (D 3) PA3 4| |17 PB3 (D 7)* // AVCC 5| |16 GND // AGND 6| |15 VCC // INT1 (D 11) PA4 7| |14 PB4 (D 8) // (D 13) PA5 8| |13 PB5 (D 9) // (D 10) PA6 9| |12 PB6 (D 2)* INT0 // (D 14) PA7 10| |11 PB7 (D 15) // +----+ // // * indicates PWM pin. // these arrays map port names (e.g. port B) to the // appropriate addresses for various functions (e.g. reading // and writing) const uint16_t PROGMEM port_to_mode_PGM[] = { NOT_A_PORT, (uint16_t)&DDRA, (uint16_t)&DDRB, }; const uint16_t PROGMEM port_to_output_PGM[] = { NOT_A_PORT, (uint16_t)&PORTA, (uint16_t)&PORTB, }; const uint16_t PROGMEM port_to_input_PGM[] = { NOT_A_PORT, (uint16_t)&PINA, (uint16_t)&PINB, }; const uint8_t PROGMEM digital_pin_to_port_PGM[] = { PB, /* 0 */ PB, PB, /* 2 */ PB, /* 3 */ PB, /* 4 */ PA, PA, PA, PA, PA, PA, /* 10 */ PA, PA, PB, /* 15 */ }; const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = { _BV(0), /* 0 */ _BV(1), _BV(2), /* 2 */ _BV(3), /* 3 */ _BV(6), /* 4 */ _BV(7), _BV(0), _BV(1), _BV(2), _BV(3), _BV(4), /* 10 */ _BV(5), _BV(6), _BV(7), }; const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { TIMER1A, TIMER1B, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, }; #endif #endif //Old code, just here for temporary backup until I decide it is not needed. //WARNING, if using software, RX must be on a pin which has a Pin change interrupt <= 7 (e.g. PCINT6, or PCINT1, but not PCINT8) /*#define USE_SOFTWARE_SERIAL 1 //These are set to match Optiboot pins. #define SOFTWARE_SERIAL_PORT PORTB #define SOFTWARE_SERIAL_TX 0 #define SOFTWARE_SERIAL_PIN PINB #define SOFTWARE_SERIAL_RX 1*/<file_sep>/libraries/Si7021/si7021.h #ifndef SI7021_H_ #define SI7021_H_ class Si7021 { public: void init(); void getMonitor2(double *temp, double *humidity); }; #endif // SI7021_H_ <file_sep>/hardware/digistump/avr/libraries/OneWire/examples/Digispark_Example/Digispark_Example.ino #include <OneWire.h> #include <DigiUSB.h> #define DS18S20_ID 0x10 #define DS18B20_ID 0x28 int temp; OneWire ds(5); byte data[12]; byte addr[8]; boolean readTemperature(){ //find a device if (!ds.search(addr)) { ds.reset_search(); return false; } if (OneWire::crc8( addr, 7) != addr[7]) { return false; } if (addr[0] != DS18S20_ID && addr[0] != DS18B20_ID) { return false; } ds.reset(); ds.select(addr); // Start conversion ds.write(0x44, 1); // Wait some time... } boolean getTemperature(){ byte i; byte present = 0; present = ds.reset(); ds.select(addr); // Issue Read scratchpad command ds.write(0xBE); // Receive 9 bytes for ( i = 0; i < 9; i++) { data[i] = ds.read(); } // Calculate temperature value temp = ((( (data[1] << 8) + data[0] )*0.0625)*1.8)+32; return true; } void setup(){ DigiUSB.begin(); DigiUSB.print("Start"); } void loop(){ readTemperature(); DigiUSB.delay(1000); getTemperature(); DigiUSB.println(temp); DigiUSB.delay(1000); } <file_sep>/libraries/QS301/qs301.h #ifndef QS301_H_ #define QS301_H_ #define COLOR_WHITE 0x0 #define COLOR_PURPLE 0x1 // purple #define COLOR_CYAN 0x2 // cyan #define COLOR_BLUE 0x3 #define COLOR_YELLOW 0x4 #define COLOR_RED 0x5 #define COLOR_GREEN 0x6 #define COLOR_OFF 0x7 #define NUM_OFF 0x0 #define COLON_OFF 0x0 #define COLON_DOT 0x2 #define COLON_TOP 0x4 class QS301Module { public: void init(int din, int oe, int stcp, int shcp); void setColor(int color) { color_ = color; } void setNumber(int number); void setColon(int colon) { colon_ = colon; } void flush(); void commit(); private: void flushBits(int bits, int n); int color_; int number_; int colon_; int kDin_; int kOE_; int kStcp_; int kShcp_; static const int kNumBits[11]; }; #endif // QS301_H_ <file_sep>/SoilMontor/SoilMontor.ino #include <SPI.h> #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SH1106.h> #define MAX_INPUT 430 #define OLED_RESET 4 Adafruit_SH1106 display(OLED_RESET); void setup() { // put your setup code here, to run once: Serial.begin(9600); // by default, we'll generate the high voltage from the 3.3v line internally! (neat!) display.begin(SH1106_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64) // init done // Clear the buffer. display.clearDisplay(); display.display(); } // 12 34 void printHumidity(int percent) { Serial.println(percent); display.setTextSize(2); display.setTextColor(WHITE); display.setCursor(0,0); display.write(' '); display.write(' '); char c = (percent / 1000) % 10; display.write(c + '0'); c = (percent / 100) % 10; display.write(c + '0'); display.write('.'); c = (percent / 10) % 10; display.write(c + '0'); c = (percent % 10); display.write(c + '0'); display.write('%'); display.println(); } void drawHumidity(int percent) { display.drawRect(0, 34, 128, 16, WHITE); display.fillRect(0, 34, percent, 16, WHITE); } void loop() { // put your main code here, to run repeatedly: uint32_t input = analogRead(5); Serial.print("Moisture Sensor Value:"); Serial.println(input); delay(200); display.clearDisplay(); printHumidity(input * 10000 / MAX_INPUT); drawHumidity(input * 128 / MAX_INPUT); display.display(); } <file_sep>/hardware/digistump/avr/libraries/Digispark_Examples/Charlieplex/Charlieplex.ino void setup() { // initialize the digital pin as an output. } // the loop routine runs over and over again forever: void loop() { LEDon(0, 1); delay(1000); LEDon(0, 2); delay(1000); LEDon(0, 3); delay(1000); LEDon(0, 4); delay(1000); LEDon(1, 0); delay(1000); LEDon(1, 2); delay(1000); LEDon(1, 3); delay(1000); LEDon(1, 4); delay(1000); LEDon(2, 0); delay(1000); LEDon(2, 1); delay(1000); LEDon(2, 3); delay(1000); LEDon(2, 4); delay(1000); LEDon(3, 0); delay(1000); LEDon(3, 1); delay(1000); LEDon(3, 2); delay(1000); LEDon(3, 4); delay(1000); LEDon(4, 0); delay(1000); LEDon(4, 1); delay(1000); LEDon(4, 2); delay(1000); LEDon(4, 3); delay(1000); } void LEDon(int vin, int gnd) { pinMode(0, INPUT); pinMode(1, INPUT); pinMode(2, INPUT); pinMode(3, INPUT); pinMode(4, INPUT); pinMode(5, INPUT); pinMode(vin, OUTPUT); pinMode(gnd, OUTPUT); digitalWrite(vin, HIGH); digitalWrite(gnd, LOW); } <file_sep>/led/led.ino #define LED_PORT 3 void setup() { pinMode(LED_PORT, OUTPUT); } void loop() { for (int i = 0; i < 256; ++i) { analogWrite(LED_PORT, i); delay(5); } for (int i = 0; i < 256; ++i) { analogWrite(LED_PORT, 255 - i); delay(5); } } <file_sep>/CloudScreen/CloudScreen.ino #include <Adafruit_GFX.h> #include <Adafruit_SSD1351.h> #include <SPI.h> #include <Wire.h> #define SCLK 2 #define MOSI 3 #define DC 4 #define CS 5 #define RST 6 // Color definitions #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF Adafruit_SSD1351 tft = Adafruit_SSD1351(CS, DC, RST); #define RTC2403_Address 0x32 //RTC_Address class RTC2403 { public: enum { RTC_Address = 0x32 }; void Begin() { Wire.begin(); } void Read() { unsigned char date[7]; unsigned char n = 0; Wire.requestFrom(RTC_Address, 7); while (Wire.available()) { date[n++] = Wire.read(); } delayMicroseconds(1); Wire.endTransmission(); for (int i = 0; i < 7; i++) { if (i != 2) date[i] = (((date[i] & 0xf0) >> 4) * 10) + (date[i] & 0x0f); else { date[2] = (date[2] & 0x7f); date[2] = (((date[2] & 0xf0) >> 4) * 10) + (date[2] & 0x0f); } } second_ = date[0]; minute_ = date[1]; hour_ = date[2]; week_ = date[3]; day_ = date[4]; month_ = date[5]; year_ = date[6] + 1994; } void Write() { On(); Wire.beginTransmission(RTC_Address); Wire.write(byte(0));//Set the address for writing Wire.write(byte(second_));//second:59 Wire.write(byte(minute_));//minute:1 Wire.write(mode12_ ? byte(hour_) : byte(hour_) | 0x90);//hour Wire.write(byte(week_));//weekday:Wednesday Wire.write(byte(day_));//day:26th Wire.write(byte(month_));//month:December Wire.write(byte(year_ - 1994));//year:2012 Wire.endTransmission(); Wire.beginTransmission(RTC_Address); Wire.write(0x12); //Set the address for writing Wire.write(byte(0)); Wire.endTransmission(); Off(); } void On() { Wire.beginTransmission(RTC_Address); Wire.write(0x10);//Set the address for writing as 10H Wire.write(0x80);//Set WRTC1=1 Wire.endTransmission(); Wire.beginTransmission(RTC_Address); Wire.write(0x0F);//Set the address for writing as OFH Wire.write(0x84);//Set WRTC2=1,WRTC3=1 Wire.endTransmission(); } void Off() { Wire.beginTransmission(RTC_Address); Wire.write(0x0F); //Set the address for writing as OFH Wire.write(byte(0));//Set WRTC2=0,WRTC3=0 Wire.write(byte(0));//Set WRTC1=0 Wire.endTransmission(); } int year() const { return year_; } int month() const { return month_; } int day() const { return day_; } int hour() const { return hour_; } int minute() const { return minute_; } int second() const { return second_; } int week() const { return week_; } void SetYear(int year) { year_ = year; } void SetMonth(int month) { month_ = month; } void SetDay(int day) { day_ = day; } void SetHour(int hour) { hour_ = hour; } void SetMinute(int minute) { minute_ = minute; } void SetSecond(int second) { second_ = second; } void SetWeek(int week) { week_ = week; } void SetHourMode(bool mode12) { mode12_ = mode12; } private: int year_; int month_; int day_; int hour_; int minute_; int second_; int week_; bool mode12_; }; RTC2403 rtc; void setup() { // put your setup code here, to run once: rtc.Begin(); // rtc.SetYear(2015); // rtc.SetMonth(7); // rtc.SetDay(12); // rtc.SetHour(23 + 6); // rtc.SetMinute(59); // rtc.SetSecond(0); // rtc.SetWeek(0); // rtc.SetHourMode(false); // rtc.Write(); tft.begin(); tft.fillScreen(BLACK); } char n2Char(int n) { return '0' + n; } void printDateTime() { rtc.Read(); char buf[] = {"00:00\n"}; int hour = rtc.hour(); buf[0] = n2Char(hour / 10); buf[1] = n2Char(hour % 10); int minute = rtc.minute(); buf[3] = n2Char(minute / 10); buf[4] = n2Char(minute % 10); tft.setTextSize(4); tft.setTextColor(GREEN); tft.setCursor(0, 0); tft.print(buf); int second = rtc.second(); int with = second / 60.0 * 128.0; //tft.fillRect(0, 64, 128, 12, BLACK); tft.fillRect(0, 64, with, 12, BLUE); if (second == 0) { tft.fillScreen(BLACK); } } void loop() { //tft.fillScreen(BLACK); printDateTime(); delay(400); } <file_sep>/MotorTest/MotorTest.ino #define MOTOR_E1 3 #define MOTOR_M1 2 #define MOTOR_E2 5 #define MOTOR_M2 4 void setup() { Serial.begin(115200); pinMode(MOTOR_E1, OUTPUT); pinMode(MOTOR_M1, OUTPUT); pinMode(MOTOR_E2, OUTPUT); pinMode(MOTOR_M2, OUTPUT); } void loop() { int value; for(value = 0 ; value <= 255; value+=5) { digitalWrite(MOTOR_M1, HIGH); digitalWrite(MOTOR_M2, HIGH); analogWrite(MOTOR_E1, value); //PWM调速 analogWrite(MOTOR_E2, value); //PWM调速 delay(100); } }
6f9d8ed9e3b04c5c22a4c91800af1184a83975f6
[ "C", "C++" ]
26
C++
emptyland/arduino
278cf1189401ba2bcb2d4125e42ac338c20ee4c8
4af3e48c659e4dac89d16cfb466bdd360d11f123
refs/heads/master
<file_sep><?php $lang = array ( // views/main 'main_new_password' => '<PASSWORD>', 'main_new_project' => 'new [PRJ]', 'main_search_results' => 'Search Results', 'main_search_projects' => 'search [PRJS]', 'main_search_passwords' => '<PASSWORD>', 'main_adv_search_title' => 'Advanced search', 'main_search' => 'Search', 'main_search_any_field' => 'Any Field', 'main_search_name' => 'Name', 'main_search_access' => 'Access', 'main_search_username_email'=> 'Username or E-mail', 'main_search_tag' => 'Tag', 'main_search_aaa_all' => 'All', 'main_search_aaa_active' => 'Only active', 'main_search_aaa_archived' => 'Only archived', 'main_search_favorite' => 'Favorite', 'main_search_locked' => 'Locked', 'main_search_file' => 'File', 'main_search_expiry_date' => 'Expiry date', 'main_search_ext_sharing' => 'External sharing', 'main_search_search' => 'Search', 'main_search_adv_help' => 'Advanced Search Help', 'main_show_tree' => 'Show Tree', 'main_hide_tree' => 'Hide Tree', 'main_refresh_tree' => 'Refresh Tree', 'main_filter_tree' => 'Filter Tree', 'main_noprj_welcome_title' => 'Welcome to Team Password Manager', 'main_noprj_welcome_line11' => "<strong>Team Password Manager</strong> helps you manage your organizations' passwords.", 'main_noprj_welcome_line12' => 'each password belongs to a <strong>[PRJ]</strong>.', 'main_noprj_welcome_line21' => 'So, the first thing you might want to do is to create a [PRJ]:', 'main_noprj_welcome_line22' => 'new [PRJ]', 'main_noprj_welcome_line31' => 'If you have 5 minutes, take a look at the help page for a quick summary of Team Password Manager:', 'main_noprj_welcome_line32' => 'help page', 'main_uselector_search' => 'Search Users', // controllers/tree 'c_tree_search_results' => 'Search Results', 'c_tree_recent' => 'Recent', 'c_tree_favorite' => 'Favorite', 'c_tree_active' => 'Active', 'c_tree_all' => 'All', 'c_tree_archived' => 'Archived', 'c_tree_passwords' => 'Passwords', 'c_tree_search_results_prj' => 'Search Results', 'c_tree_recent_prj' => 'Recent', 'c_tree_favorite_prj' => 'Favorite', 'c_tree_active_prj' => 'Active', 'c_tree_archived_prj' => 'Archived', // controllers/pwd 'c_pwd_search_results' => 'Search Results', 'c_pwd_all_pwds' => 'All Passwords', 'c_pwd_favorite_pwds' => 'Favorite Passwords', 'c_pwd_archived_pwds' => 'Archived Passwords', 'c_pwd_recent_pwds' => 'Recent Passwords', 'c_pwd_active_pwds' => 'Active Passwords', 'c_pwd_all' => 'All', 'c_pwd_favorite' => 'Favorite', 'c_pwd_archived' => 'Archived', 'c_pwd_recent' => 'Recent', 'c_pwd_active' => 'Active', 'c_pwd_not_found_title' => 'Password Not Found', 'c_pwd_not_found_desc' => 'This password does not exist or you cannot access it.', 'c_pwd_history_record' => 'History Record', 'c_pwd_view_history_record' => 'View History Record', 'c_pwd_ro_hr' => 'Read Only users cannot view history records.', 'c_pwd_repeat' => 'Repeat', 'c_pwd_expiry_error' => 'The expiry date is not correct. Use the following format: mm-dd-yyyy', 'c_pwd_pwd_exists' => 'this password already exists in this [PRJ].', 'c_pwd_edit_pwd' => 'Edit Password', 'c_pwd_locked_edit' => 'This password is locked. To edit it you need to unlock it.', 'c_pwd_archived_edit' => 'this password cannot be edited because its [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_perm_edit' => 'You do not have the required permission to edit this password.', 'c_pwd_new_pwd' => '<PASSWORD>', 'c_pwd_cannot_create_pwd_ro' => 'Sorry, you cannot create passwords.', 'c_pwd_cannot_create_pwd_prj' => 'you cannot create passwords in this [PRJ], you do not have the required permission to do so.', 'c_pwd_cannot_create_pwd_noprja' => 'the [PRJ] that you are trying to create the password in does not exist, or you do not have access to it, or it is archived.', 'c_pwd_cannot_create_pwd_noprj'=> 'the [PRJ] that you are trying to create the password in does not exist or you do not have access to it.', 'c_pwd_error_saving_pwd' => 'There has been an error saving the password', 'c_pwd_error_csrf_saving' => 'Error: CSRF validation, please try again.', 'c_pwd_edit_pwd_notes' => 'Edit Password Notes', 'c_pwd_locked_notes_edit' => 'This password is locked. To edit its notes you need to unlock it.', 'c_pwd_error_saving_pwd_notes' => 'There has been an error saving the password notes', 'c_pwd_vres_managed_by' => 'Managed by', 'c_pwd_edit_pwd_sec' => 'Edit Password Security', 'c_pwd_edit_pwd_sec_locked' => 'This password is locked. To edit its security you need to unlock it.', 'c_pwd_edit_pwd_sec_archived'=> 'Password security cannot be changed for this password because its [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_edit_pwd_sec_perm' => 'You do not have the required permission to edit the security for this password.', 'c_pwd_edit_pwd_sec_error' => 'There has been an error editing the password security', 'c_pwd_vrel_locking' => 'Locked', 'c_pwd_edit_pwd_locking' => 'Edit Password Locking', 'c_pwd_edit_pwd_locking_locked' => 'This password is locked. To edit its locking status you need to unlock it.', 'c_pwd_edit_pwd_locking_archived' => 'Password locking cannot be changed for this password because its [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_edit_pwd_locking_eshared' => 'Password locking cannot be changed because the password is externally shared. If you want to set it locked you need to first edit external sharing and set it as not externally shared.', 'c_pwd_edit_pwd_locking_perm' => 'You do not have the required permission to edit the locking status of this password.', 'c_pwd_edit_pwd_locking_error' => 'There has been an error editing password locking', 'c_pwd_vrur' => 'Reason', 'c_pwd_unlock_pwd' => '<PASSWORD>', 'm_pwd_notif_unlocked' => 'password unlocked', 'm_pwd_notif_desc' => 'The following user has unlocked the following password', 'm_pwd_notif_user' => 'User', 'm_pwd_notif_reason' => 'Reason', 'm_pwd_notif_why' => 'You are receiving it because you are the password manager of the unlocked password.', 'c_pwd_delete_pwd' => 'Delete Password', 'c_pwd_delete_pwd_locked' => 'This password is locked. To delete it you need to unlock it.', 'c_pwd_delete_pwd_archived' => 'This password cannot be deleted because its [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_delete_pwd_perm' => 'You do not have the required permission to delete this password (you need Manage permission).', 'c_pwd_delete_pwd_error' => 'Error: the password has <strong>NOT</strong> been deleted due to database errors.', 'c_pwd_copy_pwd' => '<PASSWORD>', 'c_pwd_copy_pwd_locked' => 'This password is locked. To copy it you need to unlock it.', 'c_pwd_copy_pwd_dest_archived' => 'the destination [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_copy_pwd_dest_exists' => 'the password already exists in the destination [PRJ].', 'c_pwd_copy_pwd_dest_cannot' => 'you cannot create passwords in the destination [PRJ].', 'c_pwd_copy_pwd_dest_not_found' => 'the destination [PRJ] does not exist or you cannot access it.', 'c_pwd_copy_pwd_copied_error' => 'The password has been copied, but there has been this error doing so', 'c_pwd_copy_pwd_error' => 'There has been an error copying the password', 'c_pwd_copy_pwd_cannot' => 'This password cannot be copied for the following reason', 'c_pwd_copy_pwd_ro' => 'You cannot copy/create passwords, you have a read only role.', 'c_pwd_copy_pwd_nf_pwd_prj' => 'The password/[PRJ] does not exist or you cannot access it.', 'c_pwd_copy_pwd_csrf' => 'The password has NOT been copied (CSRF validation). Please try again.', 'c_pwd_move_pwd' => 'Move Password', 'c_pwd_move_pwd_locked' => 'This password is locked. To move it you need to unlock it.', 'c_pwd_move_pwd_error' => 'There has been an error moving the password', 'c_pwd_move_pwd_cannot' => 'This password cannot be moved for the following reason', 'c_pwd_move_manage' => 'You need manage permission on the password to be able to move it.', 'c_pwd_move_pwd_ro' => 'You cannot move/create passwords, you have a read only role.', 'c_pwd_move_pwd_csrf' => 'The password has NOT been moved (CSRF validation). Please try again.', 'c_pwd_vrd_dup_files' => 'Duplicate files', 'c_pwd_vrd_gen_pwd' => 'Generate new password', 'c_pwd_vrd_dup_custom' => 'Duplicate custom fields', 'c_pwd_dup_pwd' => 'Duplicate Password', 'c_pwd_dup_pwd_locked' => 'This password is locked. To duplicate it you need to unlock it.', 'c_pwd_dup_pwd_archived' => 'This password cannot be duplicated because its [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_dup_pwd_perm' => 'You do not have the required permission to duplicate this password (you need permission to create passwords in this [PRJ]).', 'c_pwd_dup_pwd_error' => 'There has been an error duplicating the password', 'c_pwd_dup_pwd_copy_of' => 'Copy of', 'c_pwd_custom_label' => 'Custom Label', 'c_pwd_custom_type' => 'Custom Type', 'c_pwd_cflabel_empty' => 'The <strong>Label</strong> for this field cannot be empty: <strong>Custom Field', 'c_pwd_cf_config' => 'Custom Fields', 'c_pwd_cf_config_locked' => 'This password is locked. To change its custom fields configuration you need to unlock it.', 'c_pwd_cf_config_archived' => 'the custom fields configuration for the password cannot be changed because its [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_cf_config_perm' => 'You do not have the required permission to change the custom fields configuration of this password (you need permission to manage the password).', 'c_pwd_cf_config_error' => 'There has been an error saving the custom fields configuration', 'c_pwd_vrees' => 'Exernally shared', 'c_pwd_ext_sharing' => 'Edit External Sharing', 'c_pwd_ext_sharing_disab' => 'External sharing is disabled. It needs to be enabled in Settings | External Sharing.', 'c_pwd_ext_sharing_locked' => 'External sharing cannot be changed because the password is locked. If you want to share this password externally you need to edit locking and set it unlocked.', 'c_pwd_ext_sharing_archived'=> 'External sharing for this password cannot be edited because its project is <span class="label label-warning tpm-archived">Archived</span>.', 'c_pwd_ext_sharing_perm' => 'You do not have the required permission to edit external sharing.', 'c_pwd_ext_sharing_error' => 'There has been an error editing external sharing', // views/pwd 'vpwd_edit_title' => 'Edit password data', 'vpwd_edit' => 'Edit', 'vpwd_edit_notes_title' => 'Edit password notes', 'vpwd_edit_notes' => 'Notes', 'vpwd_upload_title' => 'Upload file', 'vpwd_upload' => 'Upload File', 'vpwd_custom_fields_title' => 'Custom fields configuration', 'vpwd_custom_fields' => 'Custom Fields', 'vpwd_edit_security_title' => 'Edit password security', 'vpwd_edit_security' => 'Security', 'vpwd_edit_locking_title' => 'Edit password locking', 'vpwd_edit_locking' => 'Locking', 'vpwd_edit_extsha_title' => 'Edit external sharing', 'vpwd_edit_extsha' => 'Ext. Sharing', 'vpwd_duplicate_title' => 'duplicate password in the [PRJ]', 'vpwd_duplicate' => 'Duplicate', 'vpwd_copy_title' => 'copy password to another [PRJ]', 'vpwd_copy' => 'Copy', 'vpwd_move_title' => 'move password to another [PRJ]', 'vpwd_move' => 'Move', 'vpwd_delete_title' => 'Delete password', 'vpwd_delete' => 'Delete', 'vpwd_other_actions' => 'Other Actions', 'vpwd_no_name' => '(no name)', // In case a password/project has no name (unlikely) 'vpwd_cf_instructions' => 'Enter the labels and types for the custom fields you need. Note: setting a field type to "Do not use custom field" will not delete its data (if the field has any).', 'vpwd_cf_template' => 'Template', 'vpwd_cf_select' => 'Select a template to fill in the fields', 'vpwd_cf_prj_template' => '* [PRJ] template *', 'vpwd_cf_label' => 'Label', 'vpwd_cf_type' => 'Type', 'vpwd_cf_custom_field' => 'Custom Field', 'vpwd_delete_pwd_conf1' => 'Delete this password?', 'vpwd_delete_pwd_conf2' => 'Warning: this action is permanent and cannot be un-done.', 'vpwd_duplicate_btn' => 'Duplicate', 'vpwd_duplicate_new_name' => 'New Name', 'vpwd_duplicate_options' => 'Options', 'vpwd_duplicate_file' => 'file', 'vpwd_duplicate_files' => 'files', 'vpwd_duplicate_inc_files' => 'Include files', 'vpwd_duplicate_gen_pwd' => 'Generate new password(s) for the password field(s)', 'vpwd_duplicate_cf' => 'Duplicate custom fields', 'vpwd_edit_cf_label' => 'CUSTOM FIELDS', 'vpwd_edit_click_gen_pwd' => 'Click to generate password', 'vpwd_edit_del_gen_pwd' => 'You need to delete the current password if you want to generate a new one!', 'vpwd_edit_pwd_generated' => 'Password generated!', 'vpwd_edit_info_saved_enc' => 'this information is saved encrypted', 'vpwd_edit_tags_instruct' => 'Use a comma (,) for new tags, "tab" for selecting from the list', 'vpwd_edit_basic_data_label' => 'BASIC DATA', 'vpwd_edit_access_examples' => 'Examples: http://site, ftp://ip-address, manual login', 'vpwd_edit_expdate_format' => 'Format: mm-dd-yyyy', 'vpwd_share_ext_check' => 'Share externally', 'vpwd_share_ext_notes1' => 'If shared externally, the URL to access this password will be available in the "External Sharing" tab after editing.', 'vpwd_share_ext_notes2' => 'Externally shared passwords have this world link icon next to the star icon, to the right of the password name.', 'vpwd_share_ext_notes3' => 'The following data are shown when accessing a password externally: password name, project name, access, username, e-mail, password, expiry date, custom fields, notes and files.', 'vpwd_locking_check' => 'Lock password', 'vpwd_locking_notes1' => 'Any user who wants to use a locked password will have to unlock it by entering a reason.', 'vpwd_locking_notes2' => 'When a password is unlocked an email message is sent to the password manager with the entered reason.', 'vpwd_locking_notes3' => 'An unlocked password remains unlocked for the rest of the session of the user.', 'vpwd_locking_notes4' => 'Locked passwords have this lock icon (locked/unlocked) next to the star icon, to the right of the password name.', 'vpwd_security_select_pm' => 'Select the Password Manager', 'vpwd_security_managed_by' => 'Managed by', 'vpwd_security_change_pm' => 'Change', 'vpwd_security_pwd_sec' => 'Password Security', 'vpwd_security_pwd_sec_desc'=> '<strong>Set permissions</strong> on this password to individual <strong>users</strong> and/or <strong>groups</strong>', 'vpwd_security_show_with_perm' => 'Show users/groups that have a permission', 'vpwd_security_show_all' => 'Show all users/groups', 'vpwd_security_help_perm' => 'Help on Permissions', 'vpwd_security_users' => 'Users', 'vpwd_security_groups' => 'Groups', 'vpwd_security_members' => 'members', 'vpwd_security_members_in' => 'Members in', 'vpwd_security_ind_not1' => 'Individual permissions cannot be set.', 'vpwd_security_ind_not2' => 'All the users are managers of the [PRJ] of this password and there are no groups.', 'vpwd_sec_help_donotset1' => 'an explicit permission is not set for the user/group.', 'vpwd_sec_help_donotset2' => 'The effective permission for users is calculated based on their membership in groups and the permission set in those groups, or the permission set in the [PRJ] of the password.', 'vpwd_sec_help_donotset3' => 'If no permission is found, no access will be given.', 'vpwd_sec_help_noaccess' => 'the user/group cannot access the password.', 'vpwd_sec_help_read' => 'the user/group can only read password data and download its files.', 'vpwd_sec_help_edit' => 'the user/group can edit the password data and upload files to it (but not manage it).', 'vpwd_sec_help_manage' => 'the user/group has total control over the password.', 'vpwd_sec_help_notes_lbl' => 'Notes', 'vpwd_sec_help_notes1' => 'User permissions have precedence over group permissions.', 'vpwd_sec_help_notes2' => 'A specific password permission takes precedence over the one set in the [PRJ] for its passwords. Exception: [PRJ] managers have total control over the [PRJ] and its passwords and this cannot be overridden in the password.', 'vpwd_sec_help_notes3' => 'Effective permissions on the password for each user are shown on the security tab of the password.', 'vpwd_select_pm_user_role' => '<strong>User</strong> / Role', 'vpwd_select_pm_users' => 'users', 'vpwd_select_pm_not_found' => 'No users found', 'vpwd_listcc_copied' => 'Copied', 'vpwd_listcc_nothing' => 'Nothing to copy!', 'vpwd_listcc_error' => 'Error getting data to copy', 'vpwd_listcc_not_sup' => 'This copy to clipboard method is not supported in this browser', 'vpwd_listcc_copy' => 'Copy to clipboard', 'vpwd_ccall_copy' => 'Copy all the fields to clipboard', 'vpwd_ccnotes_copy' => 'Copy notes to clipboard', 'vpwd_ccall_copied' => 'Copied', 'vpwd_ccnotes_copied' => 'Copied', 'vpwd_list_empty' => 'There are no passwords with this filter or search.', 'vpwd_list_sort_name' => 'Sort by Name', 'vpwd_list_pwd_name' => '<PASSWORD>', 'vpwd_list_sort_prj' => 'sort by [PRJ]', 'vpwd_list_auep' => 'Access / Username / Email / Password', 'vpwd_list_expiry' => 'Expiry', 'vpwd_list_sport_expiry' => 'Sort by Expiry date', 'vpwd_list_updated' => 'Updated', 'vpwd_list_sort_updated' => 'Sort by Update Date', 'vpwd_list_sort_by' => 'Sort by', 'vpwd_filter_expired' => 'Filter Expired', 'vpwd_filter_soon_expire' => 'Filter Soon to Expire', 'vpwd_filter_project' => 'Filter by [CAP_PRJ]', 'vpwd_filter_tag' => 'Filter by Tag', 'vpwd_search_tags' => 'Search tags', 'vpwd_list_locked' => 'Locked', 'vpwd_list_shared_ext' => 'Shared Externally', 'vpwd_list_toggle_fav' => 'Toggle Favorite', 'vpwd_list_enter_reason_locked' => 'Locked: enter reason to unlock', 'vpwd_list_updated_ph' => 'Updated', 'vpwd_list_file' => 'file', 'vpwd_list_files' => 'files', 'vpwd_pwd_deleted' => 'The password has been deleted.', 'vpwd_pwd_deleted_ret_prj' => 'return to the [PRJ] of password', 'vpwd_pwd_deleted_ret_list' => 'Return to the passwords list', 'vpwd_unlock_yes' => 'Unlock Password', 'vpwd_unlock_reason_lbl' => 'Enter reason to unlock', 'vpwd_unlock_reason_note' => 'Note: the password will remain unlocked for the rest of your session', 'vpwd_no_data' => "This password doesn't have any data", 'vpwd_select_in_tree' => 'Select in Tree', 'vpwd_pwd_locked' => 'This password is locked. You need to enter a reason to unlock it.', 'vpwd_pwd_enter_reason' => 'Enter reason to unlock', 'vpwd_tab_data' => 'Data', 'vpwd_tab_notes' => 'Notes', 'vpwd_tab_files' => 'Files', 'vpwd_tab_external_sharing' => 'External Sharing', 'vpwd_tab_ext' => 'Ext', // Same as external sharing but reduced for mobile screens 'vpwd_tab_security' => 'Security', 'vpwd_tab_history' => 'History', 'vpwd_tab_log' => 'Log', 'vpwd_tabs_more' => 'More', 'vpwd_no_notes' => 'There are no notes for this password.', 'vpwd_no_log' => 'There are no log entries for this password.', 'vpwd_managed' => 'Managed', 'vpwd_created' => 'Created', 'vpwd_updated' => 'Updated', 'vpwd_on' => 'on', 'vpwd_by' => 'by', 'vpwd_ext_url' => 'This password can be viewed without signing in Team Password Manager using the following URL', 'vpwd_not_shared_ext' => 'This password is not shared externally.', 'vpwd_ccurl_ext_copied' => 'Copied', 'vpwd_history_description' => 'Whenever the data in the password fields change, the <strong>previous values</strong> are saved in this password history', 'vpwd_history_date_time' => 'Date/Time', 'vpwd_history_user' => 'User', 'vpwd_history_changed_fields' => 'Changed Fields', 'vpwd_history_view_values' => 'View Values', 'vpwd_history_no_history' => 'This password has no history.', 'vpwd_history_only_changed_shown' => 'only the fields that changed are shown', 'vpwd_history_record_not_exist' => 'This history record for this password does not exist.', 'vpwd_files_no_files' => "This password doesn't have any files.", 'vpwd_security_description' => 'Effective permissions on this password are', 'vpwd_security_name' => 'Name', 'vpwd_security_role' => 'Role', 'vpwd_security_permission' => 'Permission', 'vpwd_security_granted_via' => 'Granted Via', 'vpwd_security_error' => 'There has been an error getting security data for this password.', // controllers/prj 'c_prj_in' => 'In', 'c_prj_search_results' => 'Search Results', 'c_prj_favorite_prjs' => 'Favorite [CAP_PRJS]', 'c_prj_archived_prjs' => 'Archived [CAP_PRJS]', 'c_prj_recent_prjs' => 'Recent [CAP_PRJS]', 'c_prj_active_prjs' => 'Active [CAP_PRJS]', 'c_prj_favorite' => 'Favorite', 'c_prj_archived' => 'Archived', 'c_prj_recent' => 'Recent', 'c_prj_active' => 'Active', 'c_prj_not_found_title' => '[PRJ] Not Found', 'c_prj_not_found_desc' => 'This [PRJ] does not exist or you cannot access it.', 'c_prj_prj_exists_level' => 'the [PRJ] alrealdy exists in this level.', 'c_prj_edit_project' => 'edit [PRJ]', 'c_prj_edit_archived' => 'this [PRJ] cannot be edited because it is <span class="label label-warning tpm-archived">Archived</span>', 'c_prj_edit_permission' => 'you do not have the required permission to edit this [PRJ].', 'c_prj_new_project' => 'new [PRJ]', 'c_prj_new_no_more_projects'=> 'sorry, you cannot create any more [PRJS].', 'c_prj_new_free' => 'you are using the <strong>free version</strong>, which only allows you to have <strong>2 users and 5 [PRJS]</strong>, and you already have 5 [PRJS]. You need to add a license to have more users and unlimited [PRJS].', 'c_prj_new_buy' => 'You can buy licenses from the Team Password Manager website', 'c_prj_new_cannot' => 'Sorry, you cannot create [PRJS].', 'c_prj_new_no_access_parent'=> 'you do not have access to the parent [PRJ].', 'c_prj_edit_error' => 'There has been an error saving the [PRJ].', 'c_prj_edit_sec_managed_by' => 'Managed by', 'c_prj_eps' => 'edit [PRJ] security', 'c_prj_eps_archived' => 'the security of this [PRJ] cannot be edited because it is <span class="label label-warning tpm-archived">Archived</span>', 'c_prj_eps_perm' => 'you do not have the required permission to edit the security of this [PRJ] (you need manage permission).', 'c_prj_eps_error_saving' => 'There has been an error saving the security of the [PRJ]', 'c_prj_eps_no_members' => 'There are no members in this group', 'c_prj_delete' => 'delete [PRJ]', 'c_prj_delete_archived' => 'the [PRJ] cannot be deleted because it is <span class="label label-warning tpm-archived">Archived</span>.', 'c_prj_delete_not_leaf' => 'This [PRJ] cannot be deleted because it has [SUBPRJS].', 'c_prj_delete_not_leaf_explain' => 'Currently only [PRJS] at the end of a hierarchy can be deleted.', 'c_prj_delete_perm' => 'you do not have the required permission to delete this [PRJ] (you need manage permission and role Admin, [CAP_PRJ] Manager or IT).', 'c_prj_delete_error' => 'error: the [PRJ] has <strong>NOT</strong> been deleted due to database errors.', 'c_prj_archive' => 'archive [PRJ]', 'c_prj_archive_archived' => 'the [PRJ] is already <span class="label label-warning tpm-archived">Archived</span>.', 'c_prj_archive_perm' => 'you do not have the required permission to archive this [PRJ] (you need manage permission).', 'c_prj_archive_error' => 'there has been an error archiving the [PRJ]', 'c_prj_unarchive' => 'un-archive [PRJ]', 'c_prj_unarchive_unarchived'=> 'the [PRJ] is already <strong>Un-Archived</strong>.', 'c_prj_unarchive_perm' => 'you do not have the required permission to un-archive this [PRJ] (you need manage permission).', 'c_prj_unarchive_error' => 'there has been an error un-archiving the [PRJ]', 'c_prj_cft' => 'Custom fields template for new passwords', 'c_prj_cft_archived' => 'the custom fields template of this [PRJ] cannot be edited because the [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_prj_cft_perm' => 'you do not have the required permission to edit the custom fields template of this [PRJ] (you need manage permission).', 'c_prj_cft_error' => 'There has been an error saving the template', 'c_prj_tree_select_project' => 'select [PRJ]', 'c_prj_tree_root' => 'Root', 'c_prj_tree_all' => 'All', 'c_prj_change_parent' => 'Change Parent', 'c_prj_select_new_parent' => 'Select new parent for', 'c_prj_copy_pwd_select_prj' => 'Select the [PRJ] to copy the password to', 'c_prj_copy_pwd_grayed' => '[PRJS] where you cannot copy passwords to are grayed', 'c_prj_copy_my_pwd' => 'Copy My Password', 'c_prj_move_pwd_select_prj' => 'Select the [PRJ] to move the password to', 'c_prj_move_pwd_grayed' => '[PRJS] where you cannot move passwords to are grayed', 'c_prj_move_my_pwd' => 'Move My Password', 'c_prj_new_pwd_select_prj' => 'Select the [PRJ] to create a new password in', 'c_prj_new_pwd_grayed' => '[PRJS] where you cannot create passwords are grayed', 'c_prj_new_prj_select_prj' => 'Select the parent [PRJ] (or Root) to create a new [PRJ] in', 'c_prj_tree_select_parent_project' => 'select parent [PRJ]', 'c_prj_tree_select_parent_project_importing' => 'Select the parent [PRJ] (or Root) to use for importing', 'c_prj_select_prj_export' => 'Select the [PRJ] (or All) to export passwords from', 'c_prj_select_prj_export_grayed' => '[PRJS] where you cannot export passwords from are grayed', 'c_prj_change_parent_error' => 'There has been an error changing the parent of the [PRJ]', 'c_prj_change_parent_no_access_parent' => 'you do not have access to the chosen new parent, so you cannot change the parent of the [PRJ] to it.', 'c_prj_change_parent_incorrect_parent' => 'Incorrect new parent', 'c_prj_change_parent_perm' => 'you do not have the required permission to change the parent of this [PRJ].', 'c_prj_change_parent_archived' => 'the [PRJ] is archived, its parent cannot be changed.', // views/prj 'vprj_new_pwd_phone' => 'New Pwd', // =new password but reduced for phones 'vprj_new_pwd_title' => 'Create a Password in this [CAP_PRJ]', 'vprj_unarchive' => 'Un-Archive', 'vprj_unarchive_title' => 'Un-Archive this [CAP_PRJ]', 'vprj_new_subprj' => 'new [CAP_SUBPRJ]', 'vprj_edit_title' => 'Edit [PRJ] data', 'vprj_edit' => 'Edit', 'vprj_edit_security' => 'Security', 'vprj_edit_security_title' => 'edit [PRJ] security', 'vprj_cft_title' => 'Custom fields template for new passwords', 'vprj_cft' => 'C.F. Template', 'vprj_archive' => 'Archive', 'vprj_archive_title' => 'Archive this [CAP_PRJ]', 'vprj_delete' => 'Delete', 'vprj_delete_title' => 'Delete this [PRJ] and all its passwords', 'vprj_no_pwd_filter' => 'this [PRJ] has no passwords with the current filter.', 'vprj_no_pwd' => 'this [PRJ] has no passwords.', 'vprj_list_toggle_fav' => 'Toggle Favorite', 'vprj_archived' => 'Archived', // prj main screen 'vprj_tab_passwords' => '<PASSWORD>s', 'vprj_tab_pwds' => 'Pwds', // Same as vprj_tab_passwords but reduced for mobile 'vprj_tab_notes' => 'Notes', 'vprj_tab_files' => 'Files', 'vprj_tab_security' => 'Security', 'vprj_tab_log' => 'Log', 'vprj_search_filter_pwds' => 'Search / Filter Passwords', 'vprj_search' => 'Search', 'vprj_managed' => 'Managed', 'vprj_created' => 'Created', 'vprj_updated' => 'Updated', 'vprj_on' => 'on', 'vprj_by' => 'by', 'vprj_no_notes' => 'There are no notes for this [PRJ].', 'vprj_files_no_files' => "This [PRJ] doesn't have any files.", 'vpr_sec_select_pm' => 'select the [PRJ] manager', 'vprj_sec_set_to' => '[PRJ] security is set to', 'vprj_sec_grant_all' => 'grant all users the following permission', 'vprj_sec_individual' => 'set permissions on this [PRJ] to individual users and/or groups', 'vprj_sec_effective' => 'effective permissions on this [PRJ] are:', 'vprj_sec_name' => 'Name', 'vprj_sec_role' => 'Role', 'vprj_sec_prj_perm' => '[PRJ] permission', 'vprj_sec_pwds_perm' => 'Passwords Permission', 'vprj_sec_granted_via' => 'Granted Via', 'vprj_sec_error' => 'there has been an error obtaining security data for this [PRJ]', 'vprj_log_no_entries' => 'there are no log entries for this [PRJ]', 'vprj_enter_prj_search' => 'enter [PRJ] to search', 'vprj_edit_sec_prj_security' => '[PRJ] security', 'vprj_edit_sec_only_pm_adm' => 'only the [PRJ] manager and admin users have access to this [PRJ]', 'vprj_sec_help_donotset1' => 'an explicit permission is not set for the user/group.', 'vprj_sec_help_donotset2' => 'The effective permission for users is calculated based on their membership in groups and the permission set in those groups.', 'vprj_sec_help_donotset3' => 'If no permission is found, no access will be given.', 'vprj_sec_help_no_access' => 'the user/group cannot access the [PRJ] or any of its passwords.', 'vprj_sec_help_traverse' => 'the user/group can see the [PRJ] name only.', 'vprj_sec_help_read' => 'the user/group can only read [PRJ] data and its passwords.', 'vprj_sec_help_create_pwd' => 'the user/group can read [PRJ] data and create passwords in it.', 'vprj_sec_help_edit_pwd' => 'the user/group can read [PRJ] data and edit the data of its passwords (and also create passwords).', 'vprj_sec_help_manage_pwd' => 'the user/group can read [PRJ] data and manage its passwords (and also create passwords).', 'vprj_sec_help_manage' => 'the user/group has total control over the [PRJ] and its passwords.', 'vprj_sec_help_inherit' => 'the user/group inherits the permission set on the parent [PRJ].', 'vprj_sec_help_notes1' => 'User permissions have precedence over group permissions.', 'vprj_sec_help_notes2' => 'effective permissions on the [PRJ] for each user are shown on the security tab of the [PRJ].', 'vprj_archive_project' => 'archive this [PRJ]?', 'vprj_archive_project_desc' => 'an archived [PRJ] (and its passwords) cannot be changed.', 'vprj_unarchive_project' => 'un-archive this [PRJ]?', 'vprj_del_has_pwd' => 'this [PRJ] has the following number of passwords', 'vprj_del_no_pwd' => "this [PRJ] doesn't have any passwords.", 'vprj_del_confirm_pwds' => 'delete this [PRJ] and all of its passwords?', 'vprj_del_confirm_no_pwds' => 'delete this [PRJ]?', 'vprj_del_warning' => 'Warning: this action is permanent and cannot be un-done.', 'vprj_del_deleted' => 'the [PRJ] has been deleted.', 'vprj_del_goto_list' => 'go to the active [PRJS] list.', 'vprj_cft_instructions' => 'new passwords in this [PRJ] will have the following custom fields', 'vprj_cft_select' => 'Select a global template to fill in the fields', 'vprj_list_empty' => 'there are no [PRJS] with this filter or search.', 'vprj_list_sort_name' => 'Sort by Name', 'vprj_list_sort_managed_by' => 'Sort by Managed by', 'vprj_list_sort_updated' => 'Sort by Update date', 'vprj_list_managed_by' => 'Managed by', 'vprj_list_updated' => 'Updated', // views/files 'vfiles_filename' => 'Filename', 'vfiles_size' => 'Size', 'vfiles_notes' => 'Notes', 'vfiles_updated' => 'Updated', 'vfiles_download' => 'Download', 'vfiles_edit' => 'Edit', 'vfiles_del' => 'Delete', 'vfiles_view' => 'View', // External access 'c_pwde_file_not_exist' => 'The requested file does not exist or you cannot access it.', 'v_pwde_file' => 'File', 'v_pwde_ret_files_list' => 'Return to the password files list', );<file_sep><?php $lang = array ( // Controller 'c_set_ret_lic' => 'Return to licenses', 'c_set_2fa_enabled' => 'Two-factor authentication with Google Authenticator is <strong>enabled</strong>.', 'c_set_2fa_disabled' => 'Two-factor authentication with Google Authenticator is <strong>disabled</strong>.', 'c_set_2fa_enforced' => '<strong>Enforced</strong> on all users.', 'c_set_2fa_not_enforced' => '<strong>NOT enforced</strong> on all users.', 'c_set_smtp_not_configured' => 'SMTP server is not configured. Messages can still be sent but on some systems it may not work.', 'c_set_smtp_configured' => 'SMTP server is configured.', 'c_set_num_ip_blocked' => 'Number of IP addresses being blocked', 'c_set_auto_ip_blocking_disabled' => 'Automatic IP address blocking is <strong>disabled</strong>.', 'c_set_auto_ip_blocking_enabled' => 'Automatic IP address blocking is <strong>enabled</strong>.', 'c_set_ldap_php_not_installed' => 'LDAP PHP support is not installed.', 'c_set_ldap_disabled' => 'LDAP Authentication is disabled.', 'c_set_ldap_enabled' => 'LDAP Authentication is enabled.', 'c_set_timeout_disabled' => 'Timeout is disabled (is managed with PHP ini settings).', 'c_set_timeout_set_to' => 'Timeout is set to', 'c_set_timeout_seconds' => 'seconds', 'c_set_db_not_encrypted' => 'The database configuration parameters in config.php are NOT encrypted.', 'c_set_db_encrypted' => 'The database configuration parameters in config.php are encrypted.', 'c_set_version_checking_manual' => 'Version checking is manual.', 'c_set_api_enabled' => 'API access is enabled.', 'c_set_api_disabled' => 'API access is disabled.', 'c_set_exp_days_remind' => 'Days to remind before expiration', 'c_set_exp_disabled' => 'Disabled', 'c_set_default_template' => 'Default template for new passwords', 'c_set_default_templante_none' => 'none', 'c_set_ext_sha_enabled' => 'External sharing of passwords is enabled.', 'c_set_ext_sha_disabled' => 'External sharing of passwords is disabled.', 'c_set_vcheck_title' => 'Version checker', 'c_set_licenses_title' => 'Licenses', 'c_set_export_import_title' => 'Export and import', 'c_set_email_title' => 'Email', 'c_set_2fa_title' => 'Two-Factor authentication', 'c_set_ipba_title' => 'Automatic IP address blocking', 'c_set_ipb_title' => 'IP address blocking', 'c_set_pgen_title' => 'Password generator', 'c_set_ldap_title' => 'LDAP authentication', 'c_set_timeout_title' => 'Timeout', 'c_set_edb_config_title' => 'Encrypt DB configuration', 'c_set_api_title' => 'API', 'c_set_expiration_title' => 'Password expiration', 'c_set_cft_title' => 'Custom Field Templates', 'c_set_external_sharing_title' => 'External sharing of passwords', 'c_set_languages_title' => 'Languages', 'c_set_license' => 'License', 'c_set_lic_not_found' => 'License not found', 'c_set_lic_not_exist' => 'This license does not exist.', 'c_set_lic_deleted_title' => 'License deleted', 'c_set_lic_deleted_desc' => 'This license has been deleted', 'c_set_lic_not_deleted_title' => 'License not deleted', 'c_set_lic_not_deleted_desc' => 'The license has NOT been deleted. Please try again.', 'c_set_lic_email' => 'E-mail', 'c_set_lic_id' => 'Id', 'c_set_lic_code' => 'Code', 'c_set_lic_already_exists' => 'The license Id already exists.', 'c_set_add_lic' => 'Add a license', 'c_set_su_lic_error_1' => "The license you're trying to add is a 'Support and Updates' license and it must be attached to an existing license.", 'c_set_su_lic_error_2' => "Please click on the 'Attach Support and Updates license' button of an existing license from the licenses list.", 'c_set_lic_added_title' => 'License added', 'c_set_lic_added_desc' => 'This license has been added', 'c_set_lic_added_error' => 'There has been an error adding the license.', 'c_set_lic_data_incorrect' => 'The license data your entered is not correct.', 'c_set_trial_expired' => 'The trial period has expired.', 'c_set_already_trial' => 'This installation has already had a trial license, and another one cannot be applied.', 'c_set_add_lic_csrf_error' => 'There has been a CSRF error adding the license.', 'c_set_attach_su' => 'Attach a Support and Updates License', 'c_set_lic_attached' => 'It has been attached to license', 'c_set_attach_su_error' => 'There has been an error attaching the license.', 'c_set_attach_su_users_mismatch' => "The number of users of the normal license do not match the ones of the license you're trying to attach.", 'c_set_attach_su_not_su' => "The license you're trying to attach is NOT a 'Support and Updates' license.", 'c_set_attach_su_lic_not_exists' => 'This license does not exist or it cannot be attached a Support and Updates license.', 'c_set_export_disabled_title' => 'Exporting is disabled', 'c_set_export_disabled_desc' => 'You cannot export passwords.', 'c_set_return_exp_imp' => 'Return to export/import', 'c_set_export' => 'Export Passwords', 'c_set_export_no_pwd' => "the selected [PRJ] doesn't have any passwords.", 'c_set_export_csrf_error' => 'There has been a CSRF error exporting passwords.', 'c_set_import_disabled_title' => 'Importing is disabled', 'c_set_import_disabled_desc' => 'You cannot import passwords.', 'c_set_import' => 'Import Passwords', 'c_set_import_log' => 'Import Passwords Log', 'c_set_import_log_not_found' => 'Log ID not found or it has no entries', 'c_set_import_folder_missing' => 'The import folder is missing.', 'c_set_import_folder_desc' => 'To import passwords the following folder must exist and <strong>it must be writable</strong>', 'c_set_import_folder_create' => 'Please manually create the import folder, set it writable and execute the import procedure again.', 'c_set_export_import_help' => 'Help on exporting/importing Passwords', 'c_set_import_folder_not_writable' => 'The import folder is not writable.', 'c_set_import_folder_writable_desc' => 'To import passwords the import folder must be writable, your webserver should be able to create files in it.', 'c_set_import_folder_set_writable' => 'Please set it writable and execute the import procedure again.', 'c_set_email_test' => 'Send test email', 'c_set_email_return' => 'Return to email settings', 'c_set_email_test_ok' => 'Your test message has been successfully sent. Please check your inbox for this message to confirm delivery.', 'c_set_email_test_error' => 'There has been an error sending your test message. Please check the email configuration.', 'c_set_email_test_response' => 'This is the response when trying to send the message', 'm_set_email_test_header' => 'Test message from Team Password Manager', 'm_set_email_test_body' => 'This is a test message from your Team Password Manager installation. If you can read this it means that it can send messages.', 'c_set_email_edit' => 'Edit SMTP server configuration', 'c_set_email_edit_error' => 'There has been an error editing the configuration.', 'c_set_email_edit_csrf_error' => 'There has been a CSRF error editing the configuration.', 'c_set_enable_2fa' => 'Enable two-factor authentication', 'c_set_disable_2fa' => 'Disable two-factor authentication', 'c_set_return_2fa' => 'Return to two-factor authentication settings', 'c_set_2fa_already_enabled' => 'Two-factor authentication is already enabled.', 'c_set_2fa_already_disabled' => 'Two-factor authentication is already disabled.', 'c_set_enforce_2fa' => 'Enforce two-factor authentication', 'c_set_stop_enforcing_2fa' => 'Stop enforcing two-factor authentication', 'c_set_2fa_already_enforced' => 'Two-factor authentication is already enforced on all users.', 'c_set_2fa_already_not_enforced'=> 'Two-factor authentication is already NOT enforced on all users.', 'c_set_2fa_not_enabled' => 'Two-factor authentication is not enabled.', 'c_set_blocked_ips' => 'Blocked IP addresses', 'c_set_ip_address' => 'IP address', 'c_set_ip_address_already_exists' => 'The IP address already exists.', 'c_set_new_ip' => 'New IP address to block', 'c_set_ip_added_1' => 'The IP address has been added and access to this installation of Team Password Manager from it is being blocked', 'c_set_ip_added_2' => 'Note that this validation is done at the "Sign in" screen. Users already logged in from this IP address are not being blocked.', 'c_set_new_ip_error' => 'There has been an error saving the IP address.', 'c_set_new_ip_csrf_error' => 'There has been a CSRF error saving the IP address, please try again.', 'c_set_del_ip' => 'Delete Blocked IP address', 'c_set_ip_not_exists' => 'The IP address does not exist.', 'c_set_del_ip_ok' => 'IP address deleted.', 'c_set_del_ip_error' => 'It has not been possible to delete the IP address.', 'c_set_enable_ipba' => 'Enable automatic IP address blocking', 'c_set_disable_ipba' => 'Disable automatic IP address blocking', 'c_set_return_ipba' => 'Return to automatic IP address blocking settings', 'c_set_ipba_already_enabled' => 'Automatic IP address blocking is already enabled.', 'c_set_ipba_already_disabled' => 'Automatic IP address blocking is already disabled.', 'c_set_ipba_disabled' => 'Automatic IP address blocking is disabled. You should enable it if you want to edit its configuration.', 'c_set_ipba_failed_attempts' => 'Failed attempts', 'c_set_ipba_period' => 'Period', 'c_set_ipba_valid_ips' => 'The <strong>Exceptions</strong> field must contain a list of valid IP addresses.', 'c_set_ipba' => 'Edit automatic IP address blocking configuration', 'm_ipb_no_one' => 'No one', 'c_set_ipba_error' => 'There has been an error saving the settings.', 'c_set_ipba_csrf_error' => 'There has been a CSRF error saving the settings.', 'c_set_pgen_min_length' => 'Minimum length', 'c_set_pgen_max_length' => 'Maximum length', 'c_set_pgen_uppercase' => 'Uppercase letters', 'c_set_pgen_lowercase' => 'Lowercase letters', 'c_set_pgen_numbers' => 'Numbers', 'c_set_pgen_symbols' => 'Symbols', 'c_set_pgen_allowed_symbols' => 'Allowed symbols', 'c_set_pgen_min_len_smaller_max' => 'The minimum length must be smaller than the maximum length.', 'c_set_pgen_require_one_group' => 'At least one group of characters must be checked.', 'c_set_pgen_allowed_symbols_only' => 'The Allowed symbols field must only contain symbols: no letters, numbers or spaces.', 'c_set_pgen_allowed_symbols_no_repeated' => 'The Allowed symbols field cannot have repeated symbols.', 'c_set_pgen_edit' => 'Edit password generator configuration', 'c_set_pgen_edit_error' => 'There has been an error saving the configuration.', 'c_set_pgen_edit_csrf_error' => 'There has been a CSRF error saving the configuration.', 'c_set_pgen_return' => 'Return to password generator settings', 'c_set_ldap_enable' => 'Enable LDAP authentication', 'c_set_ldap_disable' => 'Disable LDAP authentication', 'c_set_ldap_edit_server' => 'Edit LDAP server configuration: Server', 'c_set_ldap_edit_server_error' => 'There has been an error saving the server configuration.', 'c_set_ldap_edit_server_csrf_error' => 'There has been a CSRF error saving the server configuration.', 'c_set_ldap_return' => 'Return to LDAP authentication settings', 'c_set_ldap_test' => 'Test LDAP/AD Server Connectivity: Server', 'c_set_ldap_test_error' => 'There has been an error authenticating to the LDAP server with the provided settings', 'c_set_ldap_test_ok' => 'You have been able to correctly authenticate to the LDAP server with the provided settings.', 'c_set_ldap_test_csrf_error' => 'There has been a CSRF error testing the configuration.', 'c_set_timeout_field' => 'Timeout', 'c_set_timeout_edit' => 'Edit Timeout', 'c_set_timeout_edit_csrf_error' => 'There has been a CSRF error saving the timeout.', 'c_set_timeout_return' => 'Return to timeout configuration', 'c_set_vcheck_set_auto' => 'Set automatic version checking', 'c_set_vcheck_set_manual' => 'Set manual version checking', 'c_set_api_enable' => 'Enable API access', 'c_set_api_disable' => 'Disable API access', 'c_set_api_cannot_free' => 'API access cannot be enabled/disabled in the free version.', 'c_set_api_return' => 'Return to API configuration', 'c_set_exp_days_field' => 'Days to remind', 'c_set_exp_edit' => 'Edit password expiration configuration', 'c_set_exp_edit_csrf_error' => 'There has been a CSRF error saving the password expiration configuration.', 'c_set_exp_return' => 'Return to expiration configuration', 'c_set_cft_name' => 'Name', 'c_set_cft_custom_label' => 'Custom Label', 'c_set_cft_custom_type' => 'Custom Type', 'c_set_cft_at_leat_one_field' => 'At least one custom field must be defined.', 'c_set_cft_template_exists' => 'The template already exists.', 'c_set_cft_label_cannot_empty' => 'The <strong>Label</strong> for the following field cannot be empty: Custom Field', 'c_set_cft_add' => 'Add custom fields template', 'c_set_cft_edit' => 'Edit custom fields template', 'c_set_cft_edit_ok' => 'The template has been correctly saved. Template name', 'c_set_cft_return' => 'Return to custom field templates', 'c_set_cft_edit_error' => 'There has been an error saving the template', 'c_set_cft_edit_csrf_error' => 'There has been a CSRF error saving the template.', 'c_set_cft_not_found_title' => 'Template not found', 'c_set_cft_not_found_desc' => 'This template does not exist.', 'c_set_cft_del' => 'Delete custom fields template', 'c_set_cft_del_ok' => 'The template as been deleted.', 'c_set_cft_del_error' => 'It has not been possible to delete the template.', 'c_set_cft_set_default' => 'Set default custom fields template for new passwords', 'c_set_cft_set_default_csrf_error' => 'There has been a CSRF error setting the default template.', 'c_set_cft_set_default_no_templates' => 'There are no custom field templates to choose from.', 'c_set_enable_ext_sha' => 'Enable External Sharing of Passwords', 'c_set_disable_ext_sha' => 'Disable External Sharing of Passwords', 'm_set_not_possible_to_get' => "It's not possible to get information of the latest version from the Team Password Manager website.", 'm_set_latest_version' => 'Your installation of Team Password Manager is running <strong>the latest version available</strong>', 'm_set_theres_a_new_version' => "There's a new version of Team Password Manager. Your installation is running version", 'm_set_latest_version_is' => 'The latest version is', 'm_set_new_version_available' => 'New version available', // Views 'v_set_return' => 'Return to settings overview', // Tabs 'v_set_tabs_overview' => 'Overview', 'v_set_tab_vcheck' => 'Version checker', 'v_set_tab_licenses' => 'Licenses', 'v_set_tab_export_import' => 'Export / import', 'v_set_tab_email' => 'Email', 'v_set_tab_2fa' => 'Two-Factor Auth.', 'v_set_tab_ipb' => 'IP address blocking', 'v_set_tab_pgen' => 'Pwd. generator', 'v_set_tab_ldap' => 'LDAP authentication', 'v_set_tab_timeout' => 'Timeout', 'v_set_tab_edb_config' => 'Encrypt DB Config', 'v_set_tab_api' => 'API', 'v_set_tab_expiration' => 'Expiration', 'v_set_tab_cft' => 'C. Field Templates', 'v_set_tab_external_sharing' => 'External Sharing', 'v_set_tab_languages' => 'Languages', // Overview 'v_set_overview' => 'Settings Overview', 'v_set_set_menu' => 'Settings Menu', 'v_set_lic_free' => "you're using the FREE VERSION of Team Password Manager, which only allows you to have 2 users and 5 [PRJS].", 'v_set_lic_num_licenses' => 'Number of valid licenses', 'v_set_lic_num_users' => 'Total number of named users', 'v_set_version_info_1' => 'This installation of Team Password Manager is running version', 'v_set_version_info_2' => 'released', 'v_set_main_config_file' => 'Main configuration file', 'v_set_all_params' => 'See all the possible parameters for config.php', 'v_set_unlimited' => 'unlimited', // users // Version checker 'v_set_vcheck_check_now' => 'Check version now', 'v_set_vcheck_is_automatic' => 'Version checking is automatic', 'v_set_vcheck_is_manual' => 'Version checking is manual', 'v_set_vcheck_automatic_desc' => 'Version checking is configured to be executed every time an "Admin" or "IT" user signs in. In case a newer version is available, a note will appear on the footer, on the right hand side. You can always run a version check manually using the "Check version now" button above.', 'v_set_vcheck_manual_desc' => 'Version checking is configured to be executed manually using the "Check version now" button above.', 'v_set_vcheck_change_to_manual' => 'Change to manual version checking', 'v_set_vcheck_change_to_automatic' => 'Change to automatic version checking', 'v_set_vcheck_more_info' => 'More information on Team Password Manager versions', 'v_set_vcheck_url' => 'URL that the software uses to check the version', 'v_set_vcheck_changelog' => 'Change log', 'v_set_vcheck_download' => 'Download', 'v_set_vcheck_upgrade' => 'How to upgrade', 'v_set_vcheck_proxy_set' => 'Proxy settings', 'v_set_vcheck_proxy_desc' => 'If your installation of Team Password Manager accesses the Internet through a Proxy, you may set the following parameters in <code>config.php</code> so that the version checker works properly', 'v_set_example' => 'Example', 'v_set_vcheck_proxy_desc_2' => 'If a proxy is used, VCHECK_PROXY_HOST and VCHECK_PROXY_PORT are required. VCHECK_PROXY_LOGIN and VCHECK_PROXY_PWD are optional.', 'v_set_vcheck_proxy_current' => 'The current values for these parameters are', 'v_set_not_defined' => 'not defined', 'v_set_vcheck_set_auto_question' => 'Set version checking to automatic?', 'v_set_vcheck_set_auto_question_desc' => 'Version checking will be executed automatically every time an "Admin" or "IT" user signs in. In case a newer version is available, a note will appear on the footer, on the right hand side.', 'v_set_vcheck_set_manual_question' => 'Set version checking to manual?', 'v_set_vcheck_set_manual_question_desc' => 'Version checking will have to be executed manually by clicking on the "Check version now" button.', // Licenses 'v_set_lic_you_have' => 'You have the following licenses', 'v_set_lic_type' => 'Type', 'v_set_lic_eic' => 'E-mail / Id / Code', 'v_set_lic_email' => 'E-mail', 'v_set_lic_id' => 'Id', 'v_set_lic_code' => 'Code', 'v_set_lic_no_users' => 'No. Users', 'v_set_lic_limit' => 'Limit', 'v_set_lic_status' => 'Status', 'v_set_lic_actions' => 'Actions', 'v_set_lic_valid' => 'Valid', 'v_set_lic_not_valid' => 'Not valid', 'v_set_lic_forever' => 'Forever', 'm_set_lic_year' => 'year', 'm_set_lic_years' => 'years', 'm_set_lic_unl_years' => 'Unlimited years', 'm_set_lic_num_users_not_match' => 'Error: the number of users do not match', 'v_set_lic_normal' => 'Normal', 'v_set_lic_upgrade_to_unlimited' => 'Upgrade to unlimited', 'v_set_lic_free_user' => 'Free user', 'v_set_lic_trial' => 'Trial', 'v_set_lic_su' => 'Support and updates', 'v_set_lic_delete' => 'Delete', 'v_set_lic_attach_su' => 'Attach a Support and Updates License', 'v_set_lic_date_current_version' => 'Date this version of Team Password Manager was released', 'v_set_lic_date_updates_covered' => 'Date until this license covers updates', 'v_set_lic_you_should_attach_su' => 'You should attach a Support and Updates license to cover this version.', 'v_set_lic_buy_su' => 'Buy a support and updates license', 'v_set_lic_limit_desc' => '<strong>Limit</strong> = For "Normal licenses", the date when the support/updates end. For "Support and updates licenses", the period. For "Trial licenses", the expiry date.', 'v_set_lic_need_more_users' => 'If you need more users you can buy licenses from the Team Password Manager website', 'v_set_lic_notification_approaching' => 'For each license, approaching the support and updates date, you will receive an email to optionally renew support and updates.', 'v_set_lic_using_free' => 'you are using the <strong>free version</strong>, which only allows you to have <strong>2 users and 5 [PRJS]</strong>. You need to add a license to have more users and [PRJS].', 'v_set_lic_can_buy' => 'You can buy licenses from the Team Password Manager website', 'v_set_lic_if_you_have' => 'If you have a license, click the button below to add it.', 'v_set_lic_delete_question' => 'Delete this license?', 'v_set_lic_received' => 'You should have received the license data by e-mail. Please enter these data below', 'v_set_lic_add_btn' => 'Add license', 'v_set_lic_attach_btn' => 'Attach license', 'v_lic_su_desc_1' => 'A Support and Updates license extends the support and updates date for the license', 'v_lic_su_desc_2' => "<strong>Note:</strong> This license currently has a Support and Updates license attached to. The one you're adding now will replace the current one.", // Export/import 'v_set_exp_imp_title' => 'Export / Import Passwords', 'v_set_exp_imp_desc' => 'Export or import passwords to and from CSV files', 'v_set_ei_help_link' => 'help', 'v_set_imp_sel_file' => 'Select the file that contains the passwords to import', 'v_set_imp_csv_ext' => 'CSV extension', 'v_set_imp_select_parent' => 'select a parent [PRJ] (optional)', 'v_set_imp_select_parent_btn' => 'Select a parent [PRJ]', 'v_set_imp_current_parent' => 'Currently selected', 'v_set_imp_root' => '(root)', 'v_set_imp_not_access_selected' => '(you do not have access to the selected [PRJ])', 'v_set_imp_parent_desc' => 'New [PRJS] created in the import process will have this one as parent.', 'v_set_imp_process_desc' => "When you click 'Upload and Import', the choosen file will be uploaded to the import folder and the import process will be executed. When it's over you'll be taken to another screen with the import results.", 'v_set_imp_upl_btn' => 'Upload and Import', 'v_set_imp_outcome' => 'The import process has finished with the following outcome', 'v_set_imp_num_prj_created' => 'Number of [PRJS] created', 'v_set_imp_num_imported' => 'Number of passwords imported', 'v_set_imp_log_id' => 'The import has been logged with ID', 'v_set_imp_download_log' => 'Download import log', 'v_set_imp_file_deleted' => 'For security reasons, the uploaded file has been deleted from the import folder.', 'v_set_imp_file_not_deleted' => "It hasn't been possible to delete the uploaded file from the import folder. For security reasons it's advised that you delete it manually.", 'v_set_exp_all' => 'All', // referring to projects 'v_set_exp_sel_prj' => 'select a [PRJ] to export passwords from', 'v_set_exp_not_locked' => 'Note: *locked* passwords are not fully exported (only their name and project are exported).', 'v_set_exp_process_desc' => "When you click 'Export' a CSV (Comma Separated Values) file will be downloaded with the passwords", 'v_set_exp_process_btn' => 'Export', // Email 'v_set_email_title' => 'Email Configuration', 'v_set_email_desc_1' => 'Team Password Manager uses email to send password reset and notification messages to its users.', 'v_set_email_desc_2' => 'It can send messages using an SMTP email server (preferred option) or directly (using PHP mail() function) if no server is configured.', 'v_set_email_current_config' => 'The current email configuration is', 'v_set_email_test' => 'Send test email (to yourself)', 'v_set_email_smtp_host' => 'SMTP Host', 'v_set_email_smtp_host_blank' => 'Leave blank to delete SMTP configuration', 'v_set_email_tls_ssl' => 'TLS/SSL Encryption', 'v_set_email_tls_ssl_none' => 'none', 'v_set_email_smtp_port' => 'SMTP Port', 'v_set_email_smtp_user' => 'SMTP User', 'v_set_email_smtp_pwd' => 'SMTP Password', 'v_set_email_smtp_user_sender' => 'Use the SMTP User as the email sender (otherwise it will use the email of the user). If selected, the SMTP User must be an email address.', 'v_set_email_typical_config' => 'Configuration values for typical email services', 'v_set_email_your_email' => 'your e-mail address, like', 'v_set_email_your_pwd' => '<PASSWORD>', 'v_set_email_enc_note' => '* Important: All these data are saved encrypted', // 2FA 'v_set_2fa_title' => 'Two-Factor Authentication with Google Authenticator Configuration', 'v_set_2fa_user_enable' => 'To enable two-factor authentication for a user, the user must select "My Account" and click on "Enable Two-Factor Authentication".', 'v_set_2fa_exempt_enforcement' => 'Admin/IT user exempt from two-factor authentication enforcement', 'v_set_2fa_can_stop_enforcing' => 'You can stop enforcing two-factor authentication on all users by clicking on this button', 'v_set_2fa_can_enforce' => 'You can enforce two-factor authentication on all users by clicking on this button', 'v_set_2fa_can_disble' => 'Two-Factor Authentication can be disabled globally (for all users).', 'v_set_2fa_enable_question' => 'Enable two-factor authentication?', 'v_set_2fa_disable_question' => 'Disable two-factor authentication?', 'v_set_2fa_disable_desc' => 'Users will be able to sign-in, but without two-factor authentication.', 'v_set_2fa_enforce_question' => 'Enforce two-factor authentication on all users?', 'v_set_2fa_enforce_desc' => 'Users that have not enabled two-factor authentication will be forced to do so the next time they sign in.', 'v_set_2fa_user_exempt' => 'Admin/IT user exempt', 'v_set_2fa_stop_enforcing_question' => 'Stop enforcing two-factor authentication on all users?', // IP Blocking 'v_set_ipb_tab_blocked' => 'Blocked IP Addresses', 'v_set_ipb_tab_blocked_phone' => 'Blocked IPs', 'v_set_ipb_tab_auto' => 'Automatic Blocking Settings', 'v_set_ipb_tab_auto_phone' => 'Automatic Blocking', 'v_set_ipb_title' => 'IP Adress Blocking Configuration', 'v_set_your_ip' => 'Your IP address', 'v_set_ipb_listed' => 'The IP addresses listed here cannot access this installation of Team Password Manager.', 'v_set_ipb_note_blocking' => 'Note that blocking validation is done only at the "Sign in" screen, so users already logged in when an address is added will not be blocked.', 'v_set_ipb_no_ips_filter' => 'There are no IPs with this filter or search.', 'v_set_ipb_all_ips' => 'All IPs', 'v_set_ipb_search_results' => 'Search results', 'v_set_ipb_filter_type' => 'Filter by Type', 'v_set_ipb_filter_type_manual' => 'Manual', 'v_set_ipb_filter_type_auto' => 'Automatic', 'v_set_ipb_sort_ip' => 'Sort by IP Address', 'v_set_ipb_sort_type' => 'Sort by Type', 'v_set_ipb_sort_creator' => 'Sort by Creator', 'v_set_ipb_sort_dtm' => 'Sort by Date / Time', 'v_set_ipb_field_ip' => 'IP Address', 'v_set_ipb_field_type' => 'Type', 'v_set_ipb_field_creator' => 'Creator', 'v_set_ipb_field_dtm' => 'Date/Time', 'v_set_ipb_delete_btn' => 'Delete', 'v_set_ipb_return' => 'Return to blocked IPs list', 'v_set_ipb_new_btn' => 'New IP to block', 'v_set_ipb_search_btn' => 'Search IPs', 'v_set_ipb_enter_ip' => 'Enter the IP address to be blocked. Effect is immediate after saving.', 'v_set_ipb_valid_ipv46' => 'Valid IPv4 or IPv6 address', 'v_set_ipb_del_question' => 'Delete this IP address?', 'v_set_ipba_current_config' => 'Current configuration', 'v_set_ipba_rule' => 'Rule', 'v_set_ipba_rule_desc' => 'An IP address will be blocked if users fail to sign from it these number of failed attempts in this period.', 'v_set_ipba_exceptions' => 'Exceptions', 'v_set_ipba_who_notify' => 'Who to notify', 'v_set_ipba_rule_failed_attempts' => 'Failed attempts', 'v_set_ipba_rule_period' => 'Period (seconds)', 'v_set_ipba_desc' => 'Automatic IP address blocking allows Team Password Manager to block IP addresses from which users fail to sign in X times in Y seconds. (X and Y are configurable).', 'm_ipb_none' => 'None', 'm_ipb_no_one' => 'No one', 'v_set_ipba_rule_failed_attempts_help' => 'Number of failed sign in attempts to trigger the IP block (3-999)', 'v_set_ipba_rule_period_help' => 'Seconds to trigger the IP block if the number of failed attempts is reached (10-999)', 'v_set_ipba_exceptions_help' => 'IP addresses to exclude from the automatic blocking. Separate by comma. Example: 1.2.3.4, 5.6.7.8', 'v_set_ipba_who_notify_help' => 'Admin/IT user to notify of the block by e-mail (the user must be active at the time of notification)', 'v_set_ipba_enable_question' => 'Enable automatic IP address blocking?', 'v_set_ipba_disable_question' => 'Disable automatic IP address blocking?', 'v_set_ipba_disable_desc' => 'Currently automatically blocked IP addresses will remain blocked.', // Password generator 'v_set_pgen_title' => 'Password Generator Configuration', 'v_set_pgen_desc' => 'The password generator allows the user to generate random strong passwords when editing a password.', 'v_set_pgen_uses_config' => 'It uses the following configuration', 'v_set_pgen_min_len' => 'Minimum length', 'v_set_pgen_max_len' => 'Maximum length', 'v_set_pgen_ucase' => 'Uppercase letters', 'v_set_pgen_lcase' => 'Lowercase letters', 'v_set_pgen_num' => 'Numbers', 'v_set_pgen_sym' => 'Symbols', 'v_set_pgen_allowed_sym' => 'Allowed symbols', 'v_set_pgen_test' => 'Password Generator Test', 'v_set_pgen_gen10' => 'Generate 10 passwords using the above configuration', 'v_set_pgen_generated' => 'Generated passwords', 'v_set_pgen_edit_desc' => 'You should check at least one group of characters (uppercase letters, lowercase letters, numbers or symbols)', 'v_set_pgen_min' => 'Min', 'v_set_pgen_max' => 'Max', 'v_set_pgen_only_sym' => 'Only symbols, no letters, numbers or spaces', // LDAP auth 'v_set_ldap_title' => 'LDAP Authentication Configuration', 'v_set_ldap_desc' => 'LDAP authentication allows users of Team Password Manager to be authenticated against a Lightweight Directory Access Protocol (LDAP) or Active Directory (AD) server.', 'v_set_ldap_site_link' => 'Click here to read the document explaining LDAP authentication in Team Password Manager.', 'v_set_ldap_not_installed' => 'LDAP PHP support is not installed. If you need to use LDAP Authentication you need to install LDAP for PHP.', 'v_set_ldap_url' => 'Please check the following URL', 'v_set_ldap_upto3' => 'Up to 3 LDAP/AD servers can be defined', 'v_set_ldap_edit_server_btn' => 'Edit LDAP/AD server configuration', 'v_set_ldap_test_server_btn' => 'Test LDAP/AD server connectivity', 'v_set_ldap_field_server' => 'LDAP/AD Server', 'v_set_ldap_field_port' => 'LDAP Port', 'v_set_ldap_field_ssl' => 'SSL Connectivity', 'v_set_ldap_field_prot' => 'Protocol version', 'v_set_ldap_ssl_ldaps' => 'Use SSL (ldaps)', 'v_set_ldap_ssl_tls' => 'Use TLS (only for protocol version 3)', 'v_set_ldap_ssl_no_ssl' => 'No SSL connectivity', 'v_set_ldap_std_port' => 'Standard LDAP port (389, 636 for SSL)', 'v_set_ldap_server_not_defined' => 'Not defined', 'v_set_ldap_field_server_help_1' => 'The DNS name or IP address of the server(s). Examples: ldap.mydomain.com, 192.168.0.10', 'v_set_ldap_field_server_help_2' => 'Put backup servers separated by spaces. Example: 192.168.0.10 192.168.0.11', 'v_set_ldap_field_server_help_3' => 'Leave blank to delete server configuration', 'v_set_ldap_port_help' => 'If empty, it will use the standard LDAP port (389, 636 for SSL)', 'v_set_ldap_prot_help' => 'Use protocol version 3 whenever possible, 2 is provided for legacy systems and not recommended', 'v_set_ldap_important_enc' => 'Important: All these data are saved encrypted', 'v_set_ldap_enable_question' => 'Enable LDAP authentication?', 'v_set_ldap_disable_question' => 'Disable LDAP authentication?', 'v_set_ldap_test_desc' => 'Using this form you can try to authenticate to your LDAP/AD server to test the server connection.', 'v_set_ldap_test_imp' => 'Important: the values entered here are not saved anywhere, this is only for testing.', 'v_set_ldap_login_dn_username' => 'Login DN / Username', 'v_set_ldap_anonymous' => 'Anonymous', 'v_set_ldap_server_settings' => 'Server settings', 'v_set_ldap_test_btn' => 'Test authentication', // Timeout 'v_set_timeout_title' => 'Timeout Configuration', 'v_set_timeout_desc' => 'This setting is used to define how long an inactive user session lasts. It affects all users the same way.', 'v_set_timeout_ini_title' => 'PHP ini settings that affect timeout', 'c_set_timeout_until_browser_closed' => 'Until the browser is closed', 'v_set_timeout_gc_maxlifetime' => "Specifies the number of seconds after which data will be seen as garbage and cleaned up. This setting is often used as a timeout for inactive user sessions, but since it uses PHP's garbage collector you can't rely on it for an exact timeout. This is why Team Password Manager implements it own session timeout. This setting should be at least as large as the one you specify in the timeout field.", 'v_set_timeout_cookie_lifetime' => 'Defines how long a session will last, inactive or not. If 0 it means "until the browser is closed". It should be 0 if you intend to manage the timeout with the timeout setting in Team Password Manager.', 'v_set_timeout_set_cookie_lifetime_0' => 'You should set this setting to 0.', 'v_set_timeout_field_help_1' => 'Set to 0 to disable timeout (and manage it with PHP ini settings).', 'v_set_timeout_field_help_2' => 'Less than 60 seconds is considered 0.', // Encrypt DB config 'v_set_edb_title' => 'Encrypt DB Configuration in config.php', 'v_set_edb_inst_to_encrypt' => 'If you want to encrypt them, do the following in the <strong>config.php</strong> file', 'v_set_edb_inst_to_not_encrypt' => 'If you want to use them in plain text (unencrypted), do the following in the <strong>config.php</strong> file', 'v_set_edb_enter_instruction' => 'Enter the following instruction', 'v_set_edb_enter_next' => 'Next, enter the following instructions', 'v_set_edb_set_unencrypted' => 'Set the following constants to their unencrypted values', 'v_set_edb_example' => 'Example (actual values not shown for security)', 'v_set_edb_example_hostname' => 'THE DB HOSTNAME NORMALLY localhost', 'v_set_edb_example_username' => 'THE DB USERNAME', 'v_set_edb_example_pwd' => '<PASSWORD>', 'v_set_edb_example_db' => 'THE TEAM PASSWORD MANAGER DATABASE', 'v_set_edb_example_port' => 'THE SPECIFIC PORT THE DB USES', // API 'v_set_api_title' => 'API Configuration', 'v_set_api_desc' => "Team Password Manager's <strong>application programming interface (API)</strong> allows other applications to interact with objects of the software (passwords, projects and others) programmatically.", 'v_set_api_available' => 'Available API versions', 'v_set_api_doc' => 'Documentation', 'v_set_api_v3_note' => 'Note: <strong>API v3 is deprecated</strong> and will not be available in future versions of Team Password Manager. Please use v4 for new projects and convert current projects to v4.', 'v_set_api_hash_hmac_note' => 'Note: the hash_hmac() function required for HMAC Authentication is not installed, you will not be able to authenticate using HMAC.', 'v_set_api_sha256_note' => 'Note: the sha256 hash algorithm required for HMAC Authentication is not installed, you will not be able to authenticate using HMAC.', 'v_set_api_free' => 'API access cannot be enabled in the free version.', 'v_set_api_enable_question' => 'Enable API access?', 'v_set_api_disable_question' => 'Disable API access?', // External sharing 'v_set_ext_sha_title' => 'External Sharing of Passwords Configuration', 'v_set_ext_sha_desc_1' => 'External sharing of passwords allows some passwords to be viewed by users that are not registered in Team Password Manager using a special URL. Note that not all the passwords are externally shared by default. External sharing of a password must be configured for each password that needs to be shared externally.', 'v_set_ext_sha_desc_2' => 'This setting allows you to enable or disable this feature.', 'v_set_ext_sha_enable_question' => 'Enable External Sharing of Passwords?', 'v_set_ext_sha_disable_question' => 'Disable External Sharing of Passwords?', // Expiration 'm_notif_expiry_date' => 'Expiry date', 'm_notif_expired_or_today' => 'The following passwords have expired or expire today', 'm_notif_expire_soon' => 'The following passwords will expire soon', 'm_notif_expired_or_soon' => 'expired or soon to expire passwords', // email subject: careful about accents 'v_set_exp_title' => 'Password Expiration Configuration', 'v_set_exp_days' => 'Days to remind before expiration', 'v_set_exp_days_disabled' => 'Disabled', 'v_set_exp_will' => 'This setting will', 'v_set_exp_desc_1' => 'Show the following label next to the expiry date for those passwords that will expire in X days or less', 'v_set_exp_desc_2' => 'If <code>genexp</code> is being run regularly, send a notification email to the password manager and its [PRJ] manager reminding them that the password will expire soon.', 'v_set_exp_genexp_title' => 'genexp: how to send expiration notifications by email', 'v_set_exp_genexp_desc' => 'If you want that password managers and [PRJ] managers receive regular notifications of password expirations or expiration reminders by email you should setup <code>genexp</code> to execute daily.', 'v_set_exp_genexp_location' => '<code>genexp</code> is located at the following address for your installation', 'v_set_exp_genexp_cron_1' => 'If running Linux you can setup a daily cron job to execute <code>curl</code> to open this address. To do so, edit the crontab configuration file with <code>sudo crontab -e</code> and enter the following line', 'v_set_exp_genexp_cron_2' => 'This will setup <code>genexp</code> to be executed at 6:00 AM every day.', 'v_set_exp_genexp_more_info' => 'For more information please read the following document', 'v_set_exp_days_field' => 'Days to remind', 'v_set_exp_days_field_help' => 'Set to 0 to disable expiration reminders', // Custom Field Templates 'v_set_cft_none' => 'none', 'v_set_cft_default_lbl' => 'Default template for new passwords', 'v_set_cft_set_default' => 'Set default template', 'v_set_cft_title' => 'Custom Field Templates', 'v_set_cft_templates' => 'Templates', 'v_set_cft_no_templates_search' => 'There are no templates with the current search terms.', 'v_set_cft_no_templates' => 'There are no templates.', 'v_set_cft_new_template' => 'New template', 'v_set_cft_search_templates' => 'Search templates', 'v_set_cft_sort_name' => 'Sort by Name', 'v_set_cft_sort_updated' => 'Sort by Update date', 'v_set_cft_name' => 'Name', 'v_set_cft_fields' => 'Fields', 'v_set_cft_updated' => 'Updated', 'v_set_cft_edit' => 'Edit', 'v_set_cft_delete' => 'Delete', 'v_set_cft_default' => 'default', 'v_set_cft_delete_question' => 'Delete this custom fields template?', 'v_set_cft_edit_desc' => 'Enter the labels and types for the custom fields of the template. <strong>At least one field must be defined</strong>.', 'v_set_cft_template_name' => 'Template name', 'v_set_cft_label' => 'Label', 'v_set_cft_type' => 'Type', 'v_set_cft_custom_field' => 'Custom Field', 'v_set_cft_select_template' => 'Select a template (or none)', // Languages 'v_set_lang_help' => 'Click here to read the document that explains how languages work in Team Password Manager.', 'v_set_lang_version' => 'Language version', 'v_set_lang_version_note' => 'The language files version - <code>lang_files_version</code> value in <code>config_lang.php</code> - must match this version.', 'v_set_lang_default' => 'Default language', 'v_set_lang_default_note' => "You can set the default language in <code>config.php</code> with the following instruction: <code>define('TPM_DEFAULT_LANG', 'XX');</code>, where <code>XX</code> is the language code.", 'v_set_lang_available' => 'Available Languages', 'v_set_lang_available_note' => 'This installation of Team Password Manager has the following languages', 'v_set_lang_v' => 'v.', // version 'v_set_lang_incorrect_version' => 'incorrect version', );<file_sep><?php // Defines the folder where the application files (system folder, wmm folder, and config.php file) are located. // This is useful if you want to put the application files outside the webroot. // // Example: // webroot: /var/www/domain/public.html => must contain index.php, folder.php, css folder and import folder // app files: /var/www/domain => define('APP_FOLDER' , '/var/www/domain') and place the system folder, the wmm folder, and the config.php file in this folder // // Leave blank ('') to use the default folder (the same as index.php) define('APP_FOLDER' , '');<file_sep><?php $lang = array ( // controllers/groups 'c_groups_not_exist' => 'The group does not exist.', 'c_groups_del' => 'Delete Group', 'c_groups_del_deleted' => 'Group deleted.', 'c_groups_del_cannot' => 'You cannot delete this group.', 'c_groups_delug' => 'Delete User from Group', 'c_groups_delug_cannot_yourself' => 'You cannot delete yourself from this group.', 'c_groups_delug_cannot' => 'You cannot delete users from this group.', 'c_groups_user_not_exist' => 'The user does not exist.', 'c_groups_ug_not_exist' => 'The user or group does not exist.', 'c_groups_delug_done' => 'The user has been deleted from the group.', 'c_groups_delug_error' => 'There has been an error deleting the user from the group.', 'c_groups_return_group' => 'Return to group', 'c_groups_addug' => 'Add User to Group', 'c_groups_addug_error' => 'It has not been possible to add the user to the group due to a database error.', 'c_groups_addug_csrf_error' => 'CSRF error, please try again.', 'c_groups_addug_no_more_users' => 'There are no more users to add to the group.', 'c_groups_addug_cannot' => 'You cannot add users to this group.', 'field_name' => 'Name', 'c_groups_group_exists' => 'This group already exists.', 'c_groups_edit_group' => 'Edit Group', 'c_groups_edit_group_error' => 'There has been an error saving the group data.', 'c_groups_edit_group_csrf_error' => 'There has been a CSRF error saving the group data.', 'c_groups_edit_group_cannot' => 'You cannot edit this group.', 'c_groups_new_group' => 'New Group', 'c_groups_new_group_error' => 'There has been an error adding the group.', 'c_groups_new_group_csrf_error' => 'There has been a CSRF error adding the group.', // views/users 'tab_users' => 'Users', 'tab_groups' => 'Groups', 'v_groups_created_on' => 'Created on', 'v_groups_by' => 'By', 'v_groups_updated_on' => 'Updated on', 'v_groups_return_list' => 'Return to groups list', 'v_groups_sort_name' => 'Sort by Name', 'v_groups_sort_num_users' => 'Sort by Number of users', 'v_groups_num_users' => 'N&ordm; Users', 'v_groups_sidebar_all' => 'All Groups', 'v_groups_sidebar_search' => 'Search Results', 'v_groups_btn_new_group' => 'New Group', 'v_groups_btn_search_groups' => 'Search Groups', 'v_groups_btn_edit' => 'Edit', 'v_groups_btn_delete' => 'Delete', 'v_groups_choose_user' => 'Choose the user to add to the group (only <span class="label label-success" style="font-weight:normal">Active</span> users are shown)', 'v_groups_no_groups_filter' => 'There are no groups with this filter or search.', 'v_groups_del_confirm' => 'Delete this group?', 'v_groups_delug_confirm' => 'Delete the user from the group?', );<file_sep><?php $lang = array ( // controllers/mysettings 'c_myset_export_mypwd' => 'Export My Passwords', 'c_myset_export_no_pwd' => "You don't have any passwords in My Passwords section.", 'c_myset_return' => 'Return to My Settings', 'c_myset_import_mypwd' => 'Import My Passwords', 'c_myset_import_mypwd_log' => 'Import My Passwords Log', 'c_myset_import_mypwd_log_id_ko' => 'Log ID not found or it has no entries.', 'c_myset_import_folder_missing' => 'The import folder is missing.', 'c_myset_import_folder_desc' => 'To import passwords the following folder must exist and <strong>it must be writable</strong>', 'c_myset_import_folder_create' => 'Please manually create the import folder, set it writable and execute the import procedure again.', 'c_myset_export_import_help' => 'Help on exporting/importing My Passwords', 'c_myset_import_folder_not_writable' => 'The import folder is not writable.', 'c_myset_import_folder_writable_desc' => 'To import passwords the import folder must be writable, your webserver should be able to create files in it.', 'c_myset_import_folder_set_writable' => 'Please set it writable and execute the import procedure again.', 'c_myset_incorrect_verification' => 'Incorrect verificaton.', 'c_myset_incorrect_pwd' => 'Your Password is not correct.', 'c_myset_verification' => 'Verification', 'c_myset_delete_all_mypwd' => 'Delete All My Passwords', 'c_myset_delete_all_mypwd_done' => 'All My Passwords have been deleted.', 'c_myset_delete_all_mypwd_error' => 'There has been an error deleting all My Passwords', 'c_myset_delete_all_mypwd_csrf_error' => 'There has been a CSRF error deleting all My Passwords. Please try again.', // views/my_settings 'v_myset_my_account' => 'My Account', // = v_users_my_account 'v_myset_my_settings' => 'My Settings', // = v_users_my_settings 'v_myset_my_passwords' => 'My Passwords', // = v_users_my_passwords 'v_myset_export_all_mypwd' => 'Export All My Passwords (direct export)', 'v_myset_del_mypwd_confirm' => 'Delete all of My Passwords?', 'v_myset_del_mypwd_warning' => 'Warning: this action is permanent and cannot be un-done.', 'v_myset_del_mypwd_enter_delete' => 'Enter DELETE', 'v_myset_enter_pwd' => 'Enter your Password', 'v_myset_import_outcome' => 'The import process has finished with the following outcome', 'v_myset_import_num_imported' => 'Number of my passwords imported', 'v_myset_import_log_id' => 'The import has been logged with ID', 'v_myset_import_download_log' => 'Download import log', 'v_myset_import_file_deleted' => 'For security reasons, the uploaded file has been deleted from the import folder.', 'v_myset_import_file_not_deleted' => "It hasn't been possible to delete the uploaded file from the import folder. For security reasons it's advised that you delete it manually.", 'v_myset_import_select_file' => 'Select the file that contains the password entries to import to My Passwords (CSV extension)', 'v_myset_upload_import' => 'Upload and Import', 'v_myset_export_import_full_help' => 'Read the full help on importing my password entries', 'v_myset_import_explain' => "When you click 'Upload and Import', the selected file will be uploaded to the import folder and the import process will be executed. When it's over you'll be taken to another screen with the import results.", 'v_myset_import_d1' => 'This file must be a CSV (Comma-separated values) file with the following properties', 'v_myset_import_d2' => 'Each value must be enclosed in double quotes (") and separated by a comma (,).', 'v_myset_import_d3' => 'The file must be UTF-8 encoded.', 'v_myset_import_d4' => 'Each line on the file must be a password entry with the following fields', 'v_myset_import_d5' => '<PASSWORD>', 'v_myset_import_d6' => 'Optional: Access information (unencrypted)', 'v_myset_import_d7' => 'Optional: Username (unencrypted)', 'v_myset_import_d8' => 'Optional: E-mail (unencrypted)', 'v_myset_import_d9' => 'Optional: Password (unencrypted)', 'v_myset_import_d10' => 'Optional: Notes', 'v_myset_import_d11' => 'Optional: Tags (separated by comma)', 'v_myset_import_d12' => 'The file extension must be csv.', ); <file_sep><?php $lang = array ( 'c_log_title' => 'Activity Log', 'v_log_date_time' => 'Date / Time', 'v_log_ip_addr' => 'IP Addr.', 'v_log_user' => 'User', 'v_log_action' => 'Action', 'v_log_related_prj_pwd' => '<PASSWORD> [PRJ] / password', 'v_log_related_pwd' => '<PASSWORD> Password', 'v_log_additional_data' => 'Additional Data', 'v_log_origin' => 'Origin', 'v_log_no_entries' => 'There are no log entries with the current filter.', 'v_log_filter' => 'Filter', 'v_log_clear_filter' => 'Clear Values and Hide Filter', 'v_log_filter_date' => 'Date', 'v_log_filter_date_always' => 'Always', 'v_log_filter_date_today' => 'Today', 'v_log_filter_date_yesterday' => 'Yesterday', 'v_log_filter_date_this_month' => 'This month', 'v_log_filter_date_prev_month' => 'Previous month', 'v_log_filter_date_this_year' => 'This year', 'v_log_filter_date_prev_year' => 'Previous year', 'v_log_origin_web' => 'Web', 'v_log_origin_api' => 'API', 'v_log_users_all' => 'All', 'v_log_actions_all' => 'All', 'v_log_origins_all' => 'All', // Actions 'v_log_a_view_password' => 'View password data', 'v_log_a_view_project' => 'View [PRJ]', 'v_log_a_login_successful' => 'Login successful', 'v_log_a_login_failed' => 'Login failed', 'v_log_a_logout' => 'Logout', 'v_log_a_password_reset' => 'Password reset (user)', 'v_log_a_show_password' => '<PASSWORD>', 'v_log_a_view_project_log' => 'View [PRJ] log', 'v_log_a_view_log' => 'View log', 'v_log_a_view_passwords_list' => 'View passwords list', 'v_log_a_add_password' => '<PASSWORD>', 'v_log_a_edit_password' => '<PASSWORD>', 'v_log_a_edit_password_notes' => 'Edit password notes', 'v_log_a_delete_password' => '<PASSWORD>', 'v_log_a_copy_password' => '<PASSWORD>', 'v_log_a_move_password' => '<PASSWORD>', 'v_log_a_view_user_log' => 'View user log', 'v_log_a_view_users' => 'View users', 'v_log_a_view_user' => 'View user', 'v_log_a_edit_user' => 'Edit user', 'v_log_a_add_user' => 'Add user', 'v_log_a_delete_user' => 'Delete user', 'v_log_a_change_user_password' => '<PASSWORD>', 'v_log_a_change_user_language' => 'Change user language', 'v_log_a_view_my_account' => 'View my account', 'v_log_a_edit_my_account' => 'Edit my account', 'v_log_a_change_my_password' => '<PASSWORD>', 'v_log_a_change_my_language' => 'Change my language', 'v_log_a_view_help' => 'View help', 'v_log_a_view_export_import_help' => 'View export/import help', 'v_log_a_view_my_export_import_help' => 'View my passwords export/import help', 'v_log_a_view_advsearch_help' => 'View advanced search help', 'v_log_a_view_settings' => 'View settings', 'v_log_a_add_license' => 'Add license', 'v_log_a_delete_license' => 'Delete license', 'v_log_a_change_editing_policy' => 'Change editing policy', 'v_log_a_export_passwords' => 'Export passwords', 'v_log_a_export_my_passwords' => 'Export my passwords', 'v_log_a_import_passwords' => 'Import passwords', 'v_log_a_import_my_passwords' => 'Import my passwords', 'v_log_a_delete_import_log' => 'Delete import log', 'v_log_a_delete_my_import_log' => 'Delete my import log', 'v_log_a_view_projects_list' => 'View [PRJS] list', 'v_log_a_add_project' => 'Add [PRJ]', 'v_log_a_edit_project' => 'Edit [PRJ]', 'v_log_a_archive_project' => 'Archive [PRJ]', 'v_log_a_unarchive_project' => 'Un-archive [PRJ]', 'v_log_a_delete_project' => 'Delete [PRJ]', 'v_log_a_delete_user_from_group' => 'Delete user from group', 'v_log_a_add_user_to_group' => 'Add user to group', 'v_log_a_activate_user' => 'Activate user', 'v_log_a_deactivate_user' => 'Deactivate user', 'v_log_a_view_groups' => 'View groups', 'v_log_a_view_group' => 'View group', 'v_log_a_delete_group' => 'Delete group', 'v_log_a_edit_group' => 'Edit group', 'v_log_a_add_group' => 'Add group', 'v_log_a_filter_log' => 'Filter log', 'v_log_a_import_demo_content_begin' => 'Import demo content begin', 'v_log_a_import_demo_content_end' => 'Import demo content end', 'v_log_a_send_test_email' => 'Send test email', 'v_log_a_enable_two_factor_auth' => 'Enable two-factor authentication', 'v_log_a_disable_two_factor_auth' => 'Disable two-factor authentication', 'v_log_a_disable_two_factor_auth_act' => 'Disable two-factor authentication for my account', 'v_log_a_enable_two_factor_auth_act' => 'Enable two-factor authentication for my account', 'v_log_a_installation_successful' => 'Installation successful', 'v_log_a_upgrade_successful' => 'Upgrade successful', 'v_log_a_int_upgrade_successful' => 'Intermediate upgrade successful', 'v_log_a_decrypted_aue' => 'Decrypt Access, Username, Email (upgrade to 4.50.100)', 'v_log_a_disable_two_factor_auth_usr' => 'Disable two-factor authentication for a user', 'v_log_a_blocked_ip_trying_access' => 'Blocked IP trying access', 'v_log_a_add_ip_to_block' => 'Add IP address to block', 'v_log_a_delete_blocked_ip' => 'Delete Blocked IP Address', 'v_log_a_enforce_2fa' => 'Enforce two-factor authentication on all users', 'v_log_a_stop_enforce_2fa' => 'Stop enforcing two-factor authentication on all users', 'v_log_a_change_pgen_config' => 'Change password generator configuration', 'v_log_a_change_email_config' => 'Change email configuration', 'v_log_a_enable_auto_ip_blocking' => 'Enable automatic IP address blocking', 'v_log_a_disable_auto_ip_blocking' => 'Disable automatic IP address blocking', 'v_log_a_edit_ipba_settings' => 'Edit automatic IP address blocking settings', 'v_log_a_block_ip_automatically' => 'Block IP address automatically', 'v_log_a_sent_ipba_notification' => 'Sent automatically blocked IP notification', 'v_log_a_set_prj_favorite' => 'Set the [PRJ] as favorite', 'v_log_a_unset_prj_favorite' => 'Set the [PRJ] as not favorite', 'v_log_a_set_pwd_favorite' => 'Set the password as favorite', 'v_log_a_unset_pwd_favorite' => 'Set the password as not favorite', 'v_log_a_copy_to_clipboard' => 'Copy password to clipboard', 'v_log_a_upload_file' => 'Upload file', 'v_log_a_download_file' => 'Download file', 'v_log_a_download_file_error' => 'Download file error', 'v_log_a_download_file_external' => 'Download file (external)', 'v_log_a_delete_file' => 'Delete file', 'v_log_a_edit_file_notes' => 'Edit file notes', 'v_log_a_enable_ldap_authentication' => 'Enable LDAP authentication', 'v_log_a_disable_ldap_authentication' => 'Disable LDAP authentication', 'v_log_a_edit_ldap_config' => 'Edit LDAP authentication configuration', 'v_log_a_test_ldap' => 'Test LDAP server connectivity', 'v_log_a_add_user_ldap' => 'Add user (LDAP/AD)', 'v_log_a_ldap_authenticate_ok' => 'LDAP authentication successful', 'v_log_a_ldap_authenticate_ko' => 'LDAP authentication failed', 'v_log_a_cnv_normal' => 'Convert the user to a normal (not LDAP) user', 'v_log_a_cnv_ldap' => 'Convert the user to an LDAP user', 'v_log_a_ldap_search' => 'LDAP search to import users', 'v_log_a_import_user_ldap' => 'Add user (LDAP import)', 'v_log_a_set_timeout' => 'Set timeout', 'v_log_a_edit_password_security' => '<PASSWORD>', 'v_log_a_check_version' =>'Check latest version', 'v_log_a_configure_version_checking' => 'Configure version checking', 'v_log_a_password_shown' => 'Password shown (Show password or Copy password to clipboard)', 'v_log_a_view_mypasswords_list' => 'View my passwords list', 'v_log_a_mycopy_to_clipboard' => 'Copy my password to clipboard', 'v_log_a_show_mypassword' => 'Show my password', 'v_log_a_view_mypassword' => 'View my password', 'v_log_a_delete_mypassword' => 'Delete my password', 'v_log_a_add_mypassword' => 'Add my password', 'v_log_a_edit_mypassword' => 'Edit my password', 'v_log_a_edit_custom_fields' => 'Edit custom fields configuration', 'v_log_a_view_history_record' => 'View password history record', 'v_log_a_attach_su_license' => 'Attach Support and Updates license', 'v_log_a_enable_api_access' => 'Enable API access', 'v_log_a_disable_api_access' => 'Disable API access', 'v_log_a_unauthorized_api_request' => 'Unauthorized API Request', 'v_log_a_count_projects_list' => 'Count number of [PRJS]', 'v_log_a_count_passwords_list' => 'Count number of passwords', 'v_log_a_generate_password' => '<PASSWORD>', 'v_log_a_count_passwords_project' => 'Count the passwords of a [PRJ]', 'v_log_a_count_users' => 'Count number of users', 'v_log_a_count_groups' => 'Count number of groups', 'v_log_a_renew_api_keys' => 'Renew API Keys', 'v_log_a_renew_api_keys_api_only_user' => 'Renew API Keys (API only user)', 'v_log_a_gen_exp_notif' => 'Generate expiration notifications', 'v_log_a_send_notifications_email' => 'Send notifications by email', 'v_log_a_edit_expiration_configuration' => 'Edit expiration configuration', 'v_log_a_add_cf_template' => 'Add custom fields template', 'v_log_a_edit_cf_template' => 'Edit custom fields template', 'v_log_a_delete_cf_template' => 'Delete custom fields template', 'v_log_a_edit_cftemplate_new_pwd' => 'Edit custom fields template for new passwords', 'v_log_a_edit_password_locking' => 'Edit password locking', 'v_log_a_unlock_reason' => 'Unlock password', 'v_log_a_copy_mypassword' => 'Copy my password to a [PRJ]', 'v_log_a_move_mypassword' => 'Move my password to a [PRJ]', 'v_log_a_get_version' => 'Get version', 'v_log_a_count_mypasswords_list' => 'Count number of my passwords', 'v_log_a_delete_all_my_passwords' => 'Delete all my passwords', 'v_log_a_enable_external_sharing' => 'Enable external sharing', 'v_log_a_disable_external_sharing' => 'Disable external sharing', 'v_log_a_edit_external_sharing' => 'Edit external sharing', 'v_log_a_view_password_external' => 'View password (external)', 'v_log_a_show_password_external' => 'Show password (external)', 'v_log_a_copy_to_clipboard_external' => 'Copy password to clipboard (external)', 'v_log_a_view_file' => 'View file notes', 'v_log_a_view_file_external' => 'View file (external)', 'v_log_a_edit_project_security' => 'Edit [PRJ] security', 'v_log_a_filter_tree' => 'Filter tree', 'v_log_a_change_parent' => 'Change parent', 'v_log_a_list_subprojects' => 'List [SUBPRJS]', 'v_log_a_export' => 'Export', 'v_log_a_set_api_only_user' => 'Set user as API only', 'v_log_a_unset_api_only_user' => 'Unset user as API only', 'v_log_a_view_user_api_keys' => 'View user API keys (API only user)', 'v_log_a_view_eula' => 'View EULA', 'v_log_a_delete_data' => 'Delete data (for importing demo content)', // model 'm_log_not_logged' => 'not logged', // ip address (in demo) 'm_log_duplicated_from' => 'Duplicated from', // password 'm_log_copied_from' => 'Copied from', // password 'm_log_moved_from' => 'Moved from', // password 'm_log_no_name' => 'no name', );<file_sep><?php $lang = array ( // controllers/files 'c_files_file_not_found' => 'File not found or no access', 'c_files_files_notes_title' => 'File Notes', 'c_files_upload_title' => 'Upload File', 'c_files_unknown_entity' => 'Unknown entity. pp_type=', 'c_files_pwd_prj_not_exist' => 'this password/[PRJ] does not exist or you cannot access it.', 'c_files_pwd_not_exist' => 'The password does not exist or you cannot access it.', 'c_files_prj_not_exist' => 'the [PRJ] does not exist or you cannot access it.', 'c_files_upload_pwd_archived' => 'You cannot upload files to this password because its [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_files_upload_pwd_perm' => 'You cannot upload files to this password (you need to have Edit data or Manage permission).', 'c_files_upload_prj_archived' => 'You cannot upload files to this [PRJ] because it is <span class="label label-warning tpm-archived">Archived</span>.', 'c_files_upload_prj_perm' => 'You cannot upload files to this [PRJ] (you need to have Manage permission).', 'c_files_upload_cannot_create_folder' => 'Could not create folder, please check permissions on the uploads folder. The file could not be uploaded.', 'c_files_upload_max_size_exceeded' => 'Maximum file size exceeded.', 'c_files_upload_undefined_error' => 'Undefined error.', 'c_files_upload_error_saving_db' => 'Error saving the file information to the database.', 'c_files_upload_error_encrypting_file' => 'Error encrypting the file.', 'c_files_upload_error_del_original' => 'Error deleting the original file. Check the permissions of the uploads folder.', 'c_files_tpm_file_not_exists' => 'This file does not exist or you cannot access it.', 'c_files_del' => 'Delete File', 'c_files_del_cannot_del' => 'You cannot delete this file.', 'c_files_del_error' => 'There has been an error deleting the file', 'c_files_error_csrf' => 'Error: CSRF validation, please try again.', 'c_files_edit_notes' => 'Edit File Notes', 'c_files_edit_notes_perm' => 'You cannot edit this file notes.', 'c_files_edit_notes_error' => 'There has been an error saving the file notes', // model 'm_files_dwn_error' => 'Error decrypting / downloading', 'm_files_error_folder' => 'Error in folder', 'm_files_error_folder_not_exist'=> 'Error in folder (does not exist or cannot be accessed)', 'm_files_upload_folder_missing' => 'The uploads folder is missing', 'm_files_upload_folder_must_exist' => 'to upload files to passwords or [PRJS] the uploads folder must exist and it must be writable.', 'm_files_upload_check_config' => 'Please check the config.php file.', 'm_files_upload_folder_not_writable' => 'The uploads folder is not writable', 'm_files_upload_folder_must_writable' => 'to upload files to passwords or [PRJS] the uploads folder must be writable.', 'm_files_upload_folder_set_writable' => 'Please set it writable.', // views/files 'vfiles_del_confirm' => 'Delete the file?', 'vfiles_del_warning' => 'Warning: this action is permanent and cannot be un-done.', 'vfiles_upload_file' => 'File', 'vfiles_max_file_size' => 'Maximum file size', 'vfiles_upload_notes' => 'Notes', 'vfiles_upload' => 'Upload', 'vfiles_upload_formdata' => 'A browser that supports FormData is needed to do file uploads in Team Password Manager', 'vfiles_upload_not_selected' => 'You did not select a file to upload', 'vfiles_upload_uploaded' => 'uploaded', 'vfiles_upload_encrypting' => 'Encrypting file - please wait', 'vfiles_upload_failed' => 'Upload Failed', 'vfiles_upload_aborted' => 'Upload Aborted', 'vfiles_upload_alert_max' => 'The size of the selected file is greater than the maximum allowed. Please select another file.', 'vfiles_upload_uploading' => 'Uploading file, do not close this window', 'vfiles_upload_uploading_encrypting' => 'Uploading and encrypting file', 'vfiles_view' => 'View', ); <file_sep><?php $lang = array ( // controllers/users 'c_users_title' => 'Users', // plural 'c_users_user_title' => 'User', // singular 'c_users_num_active' => 'Number of <strong>active</strong> users', 'c_users_total_create' => 'Total number of active users allowed by your license(s)', 'c_users_left' => 'Number of users left', 'c_users_cannot_more' => 'You cannot create more users with your current license(s).', 'c_users_need_more' => 'If you need more users you should click the following link to purchase additional licenses from the Team Password Manager website:', 'c_users_more_than_allowed' => 'You have more active users that the number allowed by your licenses(s). Until this situation is corrected you cannot use Team Password Manager.', 'c_users_two_options' => 'You have 2 options', 'c_users_del_dea_num' => 'Delete or deactivate the following number of users', 'c_users_increase' => 'Increase the number of maximum active users with a new license. Click the following link to purchase additional licenses from the Team Password Manager website:', 'c_users_view_user' => 'View User', 'c_users_user_not_exists' => 'The selected user does not exist.', 'c_users_renew_api_keys' => 'Renew API Keys', 'c_users_api_keys_renewed' => 'The user\'s HMAC API Keys have been renewed. From now the user must use these new keys to authenticate API calls using HMAC.', 'c_users_return_to_user' => 'Return to user', 'c_users_error_renewing_api_keys' => 'There has been an error renewing the API Keys', 'c_users_error_renewing_api_csrf' => 'There has been a CSRF error renewing the API Keys', 'field_username' => 'Username', 'field_email' => 'E-mail address', 'field_ldap_server' => 'LDAP/AD server', 'field_login_dn' => 'Login DN', 'field_name' => 'Name', 'field_role' => 'Role', 'field_language' => 'Language', 'field_pwd' => '<PASSWORD>', 'field_repeat_pwd' => '<PASSWORD>', 'field_new_pwd' => '<PASSWORD>', 'field_repeat_new_pwd' => '<PASSWORD>', 'field_cur_pwd' => '<PASSWORD>', 'c_users_ildap_dn_username' => 'Login DN / Username', 'c_users_ildap_anon' => 'Anonymous', 'c_users_ildap_base_dn' => 'Base DN', 'c_users_ildap_filter' => 'Filter', 'c_users_ildap_name_1' => 'Name 1', 'c_users_ildap_name_2' => 'Name 2', 'c_users_ildap_size_limit' => 'Size limit', 'val_username_exists' => 'The username already exists.', 'val_username_invalid_chars' => 'The username contains invalid characters.', 'val_email_exists' => 'The e-mail address already exists.', 'val_it_users_cannot_mg_admins' => 'IT users cannot manage (add, edit, change password, deactivate, delete, ...) Admin users', 'val_it_users_cannot_mg_admins_title' => 'IT users cannot manage Admin users', 'c_users_edit_user' => 'Edit User', 'c_users_edit_user_error' => 'There has been an error saving the user information.', 'c_users_edit_user_csrf_error' => 'There has been a CSRF error saving the user information.', 'c_users_new_user' => 'New User', 'c_users_cannot_add_user' => 'You cannot add new users.', 'c_users_max_users_reached' => 'The maximum number of active users has been reached', 'c_users_click_to_purchase' => 'Click here to purchase more users', 'c_users_add_user_error' => 'There has been an error adding the user', 'c_users_add_user_csrf_error' => 'There has been a CSRF error adding the user.', 'c_users_new_user_all_options' => 'New User - All the Options', 'c_users_new_ldap_user' => 'New LDAP/AD User', 'c_users_cpwd' => 'Change user password', 'c_users_cpwd_cannot_ldap' => 'You cannot change the password of an LDAP/AD user.', 'c_users_cpwd_ok' => 'Password changed correctly.', 'c_users_cpwd_error' => 'There has been an error changing the password.', 'c_users_cpwd_csrf_error' => 'There has been a CSRF error changing the password.', 'c_users_clang' => 'Change Language', 'c_users_clang_error' => 'There has been an error changing the language.', 'c_users_clang_csrf_error' => 'There has been a CSRF error changing the language.', 'c_users_default_language' => 'Default language', 'c_users_del' => 'Delete User', 'c_users_del_not_yourself' => '<strong>You cannot delete yourself</strong>. Please choose another user.', 'c_users_del_ok' => 'User deleted.', 'c_users_del_user_from_group' => 'Delete User from Group', 'c_users_del_user_from_group_cannot' => 'You cannot delete this group for this user.', 'c_users_del_user_from_group_no_group' => 'The selected group does not exist.', 'c_users_del_user_from_group_no_ug' => 'The selected user or group does not exist.', 'c_users_del_user_from_group_ok' => 'The user has been deleted from the group', 'c_users_del_user_from_group_error' => 'There has been an error deleting the user from the group', 'c_users_add_user_to_group' => 'Add User to Group', 'c_users_add_user_to_group_db_error' => 'It has not been possible to add the user to the group due to a database error.', 'c_users_add_user_to_group_cannot' => 'You cannot add the user to the group.', 'c_users_add_user_to_group_csrf_error' => 'There has been a CSRF error.', 'c_users_add_user_to_group_no_groups' => 'There are no groups to add the user to.', 'c_users_set_api_only' => 'Set API Only User', 'c_users_set_api_only_already_api' => 'This user is already an API only user', 'c_users_set_api_only_not_yourself' => '<strong>You cannot set yourself as an API only user</strong>. Please choose another user.', 'c_users_unset_api_only' => 'Unset API Only User', 'c_users_unset_api_only_already' => 'This user is already a not API only user', 'c_users_unset_api_only_not_yourself' => '<strong>You cannot unset yourself as an API only user</strong>. Please choose another user.', 'c_users_activate' => 'Activate User', 'c_users_activate_not_yourself' => '<strong>You cannot activate yourself</strong>. Please choose another user.', 'c_users_activate_cannot_more' => 'You cannot activate more users.', 'c_users_deactivate' => 'Deactivate User', 'c_users_deactivate_not_yourself' => '<strong>You cannot deactivate yourself</strong>. Please choose another user.', 'c_users_disable_2fa' => 'Disable Two-Factor Authentication', 'c_users_disable_2fa_disabled_all' => 'Two-factor authentication is already disabled for all users.', 'c_users_disable_2fa_not_enabled' => "This user doesn't have two-factor authentication enabled.", 'c_users_disable_2fa_ok' => 'Two-factor authentication has been disabled for this user.', 'c_users_change_john' => 'Change <NAME>', 'c_users_change_john_impossible' => 'In this demo, user <NAME> cannot be edited, deleted, deactivated or have his password changed.', 'c_users_cnv_normal' => 'Convert to Normal (not LDAP) User', 'c_users_cnv_normal_already' => 'The user is already a normal (not LDAP) user', 'c_users_cnv_ldap' => 'Convert to LDAP User', 'c_users_cnv_ldap_already' => 'The user is already an LDAP user', 'c_users_import_step_1' => 'Import LDAP Users. Step 1: data for getting the users', 'c_users_import_step_2_import' => 'Import LDAP Users. Step 2: select the users to import', 'c_users_import_step_2_debug' => 'Import LDAP Users. Step 2: debug fetched data', 'c_users_import_ldap_title' => 'Import LDAP Users', 'c_users_imported_ldap_title' => 'Imported LDAP Users', 'c_users_import_ldap_error_getting' => 'There has been an error getting the import data', 'c_users_import_ldap_csrf_error' => 'There has been a CSRF error. Please try again.', // views/users 'tab_users' => 'Users', 'tab_groups' => 'Groups', 'v_users_btn_new_user' => 'New User', 'v_users_btn_new_user_options' => 'New User Options', 'v_users_btn_search_users' => 'Search Users', 'v_users_btn_new_user_desc' => 'Create a normal user.', 'v_users_btn_new_ldap_user' => 'New LDAP User', 'v_users_btn_new_ldap_user_desc'=> 'Create a LDAP/AD user by manually entering the user DN.', 'v_users_btn_import_ldap_users' => 'Import LDAP Users', 'v_users_btn_import_ldap_users_desc' => 'Create one or more LDAP/AD users by importing them from the LDAP/AD server.', 'v_users_num_groups' => 'N&ordm; Groups', 'v_users_state' => 'State', // Responsive headers 'v_users_lhs_name' => 'Name', 'v_users_lhs_username' => 'Username', 'v_users_lhs_email' => 'E-mail', 'v_users_lhs_role' => 'Role', 'v_users_lhs_state' => 'State', 'v_users_sort_by_name' => 'Sort by Name', 'v_users_sort_by_username' => 'Sort by Username', 'v_users_sort_by_email' => 'Sort by E-mail', 'v_users_sort_by_role' => 'Sort by Role', 'v_users_sort_by_state' => 'Sort by State', // Labels 'lbl_inactive' => 'Inactive', 'lbl_active' => 'Active', 'lbl_2fa' => '2FA', 'lbl_api_only' => 'API-Only', 'lbl_ldap' => 'LDAP', 'v_users_list_invalid_hash' => 'Attention: this user has an invalid hash value and will not be able to sign in. This is most probably caused by someone tampering the database. To correct this situation you need to edit the user.', 'v_users_uinfo_invalid_hash' => 'Attention: your user has an invalid hash value and will not be able to sign in the next time. This is most probably caused by someone tampering the database. Please inform an Admin user.', 'v_users_uinfo_invalid_hash_edit' => 'Attention: this user has an invalid hash value and will not be able to sign in. This is most probably caused by someone tampering the database. To correct this situation save the information, paying special attention to the <strong>username</strong> and <strong>role</strong> fields.', 'v_users_list_invalid_hash_edit' => 'Edit the user', 'v_users_sidebar_all' => 'All users', 'v_users_sidebar_api_only' => 'API only users', 'v_users_sidebar_search_results' => 'Search results', 'v_users_sidebar_filter_state' => 'Filter by State', 'v_users_sidebar_filter_role' => 'Filter by Role', 'v_users_sidebar_filter_ldap_server' => 'Filter by LDAP/AD Server', 'v_users_sidebar_filter_group' => 'Filter by Group', 'v_users_sidebar_server' => 'Server', 'v_users_no_users_filter' => 'There are no users with this filter or search.', 'v_users_roles_desc_admin' => 'can do anything', 'v_users_roles_desc_pm' => 'like normal users and also create/delete [PRJS]', 'v_users_roles_desc_normal' => 'work with passwords and [PRJS], but not create/delete [PRJS]', 'v_users_roles_desc_ro' => 'only read passwords on assigned [PRJS]', 'v_users_roles_desc_it' => 'like a [PRJ] manager plus access to Users/Groups, Log and Settings', 'v_users_cannot_create_new_users' => 'You cannot create new users', 'v_users_return_list' => 'Return to users list', 'v_users_return_my_acct' => 'Return to my account', 'v_users_del_user_from_group' => 'Delete the user from the group', 'v_users_add_user_to_group' => 'Add the User to a Group', 'v_users_about_roles' => 'About roles', 'v_users_ldap_disabled' => 'Note: LDAP/AD authentication is disabled', 'v_users_btn_edit' => 'Edit', 'v_users_btn_cpwd' => 'Change Password', 'v_users_btn_cnv_normal' => 'Convert to Normal (not LDAP) User', 'v_users_btn_cnv_ldap' => 'Convert to LDAP User', 'v_users_btn_unset_api_only' => 'Unset as API only User', 'v_users_btn_set_api_only' => 'Set as API only User', 'v_users_btn_deactivate' => 'Deactivate', 'v_users_btn_activate' => 'Activate', 'v_users_btn_del' => 'Delete', 'v_users_btn_disable_2fa' => 'Disable Two-Factor Authentication', 'v_users_btn_enable_2fa' => 'Enable Two-Factor Authentication', 'v_users_btn_enable_2fa_mobile' => 'Enable 2FA', 'v_users_tab_data' => 'Data', 'v_users_tab_2fa' => 'Two-Factor Authentication', 'v_users_tab_2fa_mobile' => '2FA', 'v_users_tab_log' => 'Log', 'v_users_tab_api_keys' => 'API Keys', 'v_users_tab_passwords' => '<PASSWORD>', 'v_users_last_signed_in' => 'Last Signed in', 'v_users_last_api_request' => 'Last API request', 'v_users_created_on' => 'Created on', 'v_users_by' => 'By', 'v_users_updated_on' => 'Updated on', 'v_users_access_prjs' => 'this user has access to the following [PRJS]', 'v_users_access_no_prj' => "this user doesn't have access to any [PRJ].", 'v_users_access_all_prj' => 'this user is an <strong>Admin</strong> user and has access to all of the [PRJS].', 'v_users_access_prjs_error' => 'here has been an error fetching the list of [PRJS] that this user has access to.', 'v_users_access_pwds' => 'This user has access to the following passwords', 'v_users_access_no_pwd' => "This user doesn't have access to any password.", 'v_users_access_all_pwd' => 'This user is an <strong>Admin</strong> user and has access to all the passwords.', 'v_users_access_pwd_error' => 'There has been an error fetching the list of passwords that this user has access to.', 'v_users_api_keys_not_api_only' => 'This user is not an API only user. The HMAC API Keys can be found on the user account.', 'v_users_hash_hmac_not_installed' => 'Note: the hash_hmac() function required for HMAC Authentication is not installed, you will not be able to authenticate using HMAC', 'v_users_sha256_not_installed' => 'Note: the sha256 hash algorithm required for HMAC Authentication is not installed, you will not be able to authenticate using HMAC', 'v_users_api_keys_lbl' => 'HMAC Authentication API Keys', 'v_users_public_key' => 'Public Key', 'v_users_private_key' => 'Private Key', 'v_users_renew_api_keys' => 'Renew API Keys', 'v_users_renew_api_keys_not_api_only' => 'This user is not an API only user. To renew the HMAC API Keys for the user, the user should sign in and check the "API Keys" tab in "My Account".', 'v_users_renew_api_keys_question' => 'Do you want to renew the HMAC API Keys?', 'v_users_renew_api_keys_warning1' => 'Warning: this action is permanent and cannot be un-done.', 'v_users_renew_api_keys_warning2' => 'Renewing the API Keys will prevent HMAC authentication from current applications.', 'v_users_no_log_entries' => 'There are no log entries for this user.', 'v_users_edit_enter_pwd' => 'Enter your Password', 'v_users_edit_sec_verif' => 'Security verification', 'v_users_dn_instructions' => 'Distinguished Name or Username of the user in the LDAP/AD server.', 'v_users_my_account' => 'My Account', 'v_users_my_settings' => 'My Settings', 'v_users_my_passwords' => '<PASSWORD>', 'v_users_activate_user_confirm' => 'Activate this user?', 'v_users_deactivate_user_confirm' => 'Deactivate this user?', 'v_users_deactivate_note' => 'An inactive user cannot sign in to Team Password Manager.', 'v_users_del_confirm' => 'Delete this user?', 'v_users_del_from_grp' => 'Delete from Group', 'v_users_delg_confirm' => 'Delete the user from the group?', 'v_users_add_to_group' => 'Add to Group', 'v_users_qr_code' => 'QR Code', 'v_users_cannot_qr' => 'The QR code cannot be generated because the PHP GD extension is not installed, but you can setup Google Authenticator with the Account Name and Secret Key below', 'v_users_ga_account_name' => 'Account Name', 'v_users_ga_secret_key' => 'Secret Key', 'v_users_btn_renew_secret_key' => 'Renew Secret Key', 'v_users_api_only_confirm' => 'Set this user as an API only user?', 'v_users_api_only_desc' => 'An API only user cannot sign in to Team Password Manager, can only access Team Password Manager via the API.', 'v_users_api_disabled_note' => 'Note: API access is disabled', 'v_users_unset_api_only_confirm' => 'Unset this user as an API only user?', 'v_users_unset_api_only_desc' => 'The user will be able to sign in to Team Password Manager, as well as access Team Password Manager via the API.', 'v_users_cnv_normal_desc_1' => 'This action will delete the <strong>Login DN</strong> of the user.', 'v_users_cnv_normal_desc_2' => 'The user will then be able to sign in using the password stored in the Team Password Manager database.', 'v_users_cnv_normal_desc_3' => '<strong>* Important: </strong>you should set the password for this user using the "Change password" button after converting the user to a normal user.', 'v_users_cnv_normal_confirm' => 'Convert this user to a normal (not LDAP) user?', 'v_users_cnv_ldap_enter' => 'To be able for this user to use LDAP authentication you should enter the following data', 'v_users_pwd_8_chars' => '8 characters minimum', 'v_users_disable_2fa_confirm' => 'Disable Two-Factor Authentication for this user?', 'v_users_disable_2fa_confirm_self' => 'Disable Two-Factor Authentication?', 'v_users_disable_2fa_confirm_self_desc' => 'You will be able to sign in but without two-factor authentication.', 'v_users_ga_generated_token' => 'Generated Token', 'v_users_ga_generated_token_desc' => 'Generated by Google Authenticator every 30 seconds', 'v_users_2fa_required' => 'It is required that you enable two-factor authentication for your user before you continue. If you need assistance please contact the administrator.', 'v_users_enable_2fa_instr_1' => 'Enter your current password for verification.', 'v_users_enable_2fa_instr_2' => 'On your smartphone, open <strong>Google Authenticator</strong>, tap the <strong>plus (+) button</strong> to Add a Token, and select <strong>Time Based</strong>.', 'v_users_enable_2fa_instr_3' => 'Scan the <strong>QR Code</strong> with your Google Authenticator device. If your device does not have a camera you can enter the <strong>Account Name</strong> and <strong>Secret Key</strong> manually.', 'v_users_enable_2fa_instr_4' => 'Enter the 6-digit Token that Google Authenticator generates every 30 seconds.', 'v_users_enable_2fa_instr_5' => 'Click on "Enable two-factor authentication".', 'v_users_new_will_be_active' => 'will be <span class="label label-success" style="font-weight:normal">Active</span>', 'v_users_ildap_search_filter' => 'Search Filter', 'v_users_ildap_attr_username' => 'Attribute: Username', 'v_users_ildap_attr_email' => 'Attribute: E-mail', 'v_users_ildap_attr_name_1' => 'Attribute: Name 1', 'v_users_ildap_attr_name_2' => 'Attribute: Name 2', 'v_users_ildap_debug_mode' => 'Debug Mode', 'v_users_ildap_save_config' => 'Save Configuration', 'v_users_ilu_data_instr' => 'Enter the following data to search users in your LDAP/AD server', 'v_users_ildap_attr_username_help' => "If a username can't be assigned, the e-mail will be used", 'v_users_ildap_attr_name_2_help' => 'The name of the imported user will be: Name 1 + Name 2', 'v_users_ildap_size_limit_help' => 'Number of entries to fetch from the LDAP server. Note that this limit cannot override server-side preset limit.', 'v_users_ildap_role_help' => 'Role to be assigned to the imported users', 'v_users_ildap_debug_mode_help' => 'Will not import users, just output debug data to the screen', 'v_users_ildap_save_config_help' => 'Will save the data from this form to the database (encrypted)', 'v_users_ildap_goto_step_2' => 'Step 2: get users from the LDAP server', 'v_users_ldap_entries_found' => 'Number of entries found', 'v_users_ldap_entries_can_be_imported' => 'Number of entries that can be imported', 'v_users_ldap_import_error_lbl' => 'There has been the following error', 'v_users_ldap_import_cannot' => 'Users cannot be imported.', 'v_users_ldap_change_settings' => 'Change the settings and try again', 'v_users_ldap_no_entries_found' => 'There are no entries with the provided data. You might want to change the "Search filter" or "Base DN".', 'v_users_ldap_no_users_found' => 'There are no users with the provided data. You might want to change the "Search filter" or "Base DN".', 'v_users_ldap_users_imported' => 'Number of users imported', 'v_users_ldap_no_users_created' => 'No users have been created.', 'v_users_ldap_no_users_selected'=> 'No users were selected.', 'v_users_import_more_ldap' => 'Import more LDAP Users', 'v_users_ldap_using_data' => 'Using the following data', 'v_users_ldap_change_ret_1' => 'change - return to step 1', 'v_users_ildap_anon_conn' => 'Anonymous connection', 'v_users_ldap_attributes' => 'Attributes', 'v_users_ldap_entry_is_user' => 'This entry is a user and can be imported', 'v_users_ldap_entry_cannot_be_imported' => 'This entry cannot be imported', 'v_users_ldap_no_dn_email' => 'No DN or email for entry', 'v_users_ldap_dn' => 'DN', 'v_users_ldap_max_import' => 'Maximum number of users that can be imported', 'v_users_ldap_select' => 'Select', 'v_users_ldap_exists' => 'exists', 'v_users_ldap_import_selected' => 'Import selected users', 'v_users_ldap_import_num_users_found' => 'Number of users found', 'v_users_ldap_import_num_users_exist' => 'Number of users that already exist', 'v_users_ldap_import_select_users' => 'Select the users you wish to import', 'v_users_ldap_import_cannot_select' => 'You cannot select any user because all of them already exist in Team Password Manager.', // controllers/user_info 'c_uinfo_edit_my_account' => 'Edit my account', 'c_uinfo_edit_my_account_error' => 'There has been an error saving the data.', 'c_uinfo_edit_my_account_csrf_error' => 'There has been a CSRF error saving the data.', 'c_uinfo_cpwd_cur_pwd_not_ok' => 'The Current Password is not correct.', 'c_uinfo_cpwd' => 'Change my password', 'c_uinfo_cpwd_cannot_ldap' => 'You cannot change your password because you are an LDAP/AD user.', 'c_uinfo_cpwd_ok' => 'Password changed correctly.', 'c_uinfo_cpwd_error' => 'There has been an error changing the password.', 'c_uinfo_cpwd_csrf_error' => 'There has been a CSRF error changing the password.', 'c_uinfo_clang' => 'Change my language', 'c_uinfo_clang_error' => 'There has been an error changing the language.', 'c_uinfo_clang_csrf_error' => 'There has been a CSRF error changing the language.', 'c_uinfo_2fa_disable_ok' => 'Two-factor authentication has been disabled.', 'c_uinfo_2fa_disable_error' => 'There has been an error disabling two-factor authentication.', 'c_uinfo_2fa_disable_csrf_error' => 'There has been a CSRF error disabling two-factor authentication.', 'c_uinfo_2fa_disable_already' => 'Two-factor authentication is already disabled.', 'c_uinfo_error_qr' => 'Error generating the QR code', 'c_uinfo_token_not_valid' => 'The Generated Token is not valid.', 'c_uinfo_key_not_valid' => 'The Secret Key is not valid.', 'c_uinfo_renew_2fa' => 'Renew Two-Factor Authentication', 'c_uinfo_2fa_is_disabled' => 'Two-factor authentication is disabled', 'c_uinfo_2fa_disabled_admin' => 'Two-factor authentication has been disabled by the administrator.', 'c_uinfo_e2fa_error_gen_key' => 'There has been an error generating the Secret Key.', 'c_uinfo_e2fa_ok' => 'Two-factor authentication has been enabled.', 'c_uinfo_e2fa_error' => 'There has been an error enabling two-factor authentication.', 'c_uinfo_e2fa_csfr_error' => 'There has been a CSFR error enabling two-factor authentication.', 'c_users_renew_api_keys_ok' => 'Your HMAC API Keys have been renewed. From now on you have to use these new keys to authenticate your API calls using HMAC.', 'm_usr_lang_not_set' => 'Not set, using the default language', 'm_user_lang_no_desc' => 'No description', );<file_sep><?php $lang = array ( // Help 'c_help_title' => 'Help', 'v_help_intro' => 'Introduction', 'v_help_intro_1' => "<strong>Team Password Manager</strong> helps you manage your organizations' passwords. Each password belongs to a <strong>[PRJ]</strong>.", 'v_help_intro_2' => 'You can see the passwords and [PRJS] by clicking on the Home option on the top menu.', 'v_help_role_1' => 'Your role', 'v_help_role_2' => 'Every user of Team Password Manager has a role. Yours is', 'v_help_role' => 'With this role, you can', 'v_help_adm_1' => 'As an Administrator you have access to all the options of Team Password Manager. You can', 'v_help_adm_2' => 'Create passwords inside any [PRJ]', 'v_help_adm_3' => 'Create [PRJS] and manage its security', 'v_help_adm_4' => 'Manage (edit, delete, copy, move, etc.) any password', 'v_help_adm_5' => 'Manage (edit, delete, archive, etc.) any [PRJ] or archived [PRJ]', 'v_help_adm_6' => 'Create and manage users', 'v_help_adm_7' => 'Create and manage groups of users', 'v_help_adm_8' => 'Manage settings', 'v_help_adm_9' => 'Export or import passwords', 'v_help_adm_10' => 'View the activity log of any password, [PRJ] or user', 'v_help_adm_11' => 'View the general activity log', 'v_help_pm_1' => 'Create passwords inside the [PRJS] that <strong>you have the proper permission to</strong>', 'v_help_pm_2' => 'Create [PRJS] and manage its security', 'v_help_pm_3' => 'View the passwords of the [PRJS] that <strong>you have proper permission to</strong> and manage its passwords (if you have the proper permission)', 'v_help_pm_4' => 'View and manage the [PRJS] that <strong>you have proper permission to</strong>', 'v_help_pm_5' => 'View the activity log of the passwords you have access to and for the [PRJS] you manage', 'v_help_it_1' => 'Export passwords you have access to or import passwords', 'v_help_it_2' => 'View the activity log for any password or [PRJ] you have access to, or any user', 'v_help_ro_1' => 'As a Read only user, you can only read passwords created by other users.', 'v_help_normal_1' => 'Create passwords inside the [PRJS] that <strong>you have permission to</strong>', 'v_help_normal_2' => 'View the passwords of the [PRJS] that <strong>you have permission to</strong> and manage its passwords (if you have the proper permission)', 'v_help_normal_3' => 'View the [PRJS] or archived [PRJS] that <strong>you have permission to</strong>', 'v_help_normal_4' => 'Manage (but not delete) the [PRJS] that <strong>you have permission to</strong>', 'v_help_normal_5' => 'View the activity log of the passwords you have access to and of the [PRJS] you manage', 'v_help_my_account' => 'Also, you can always change your E-mail address, name and/or password on the My Account screen', 'v_help_prj_1' => '[PRJ] security', 'v_help_prj_2' => 'A [PRJ] is "owned" or "managed by" the user that created it. Only Administrators, [CAP_PRJ] Managers or IT users can create them.', 'v_help_prj_3' => 'A [PRJ] can be granted specific permissions to all the users, or to only specific users or groups of users.', 'v_help_prj_4' => 'The manager of a [PRJ] (or any Administrator) can manage (edit, delete, copy, move, etc.) any password in the [PRJ].', 'v_help_prj_5' => 'The manager of a [PRJ] (or any Administrator) can manage (edit, delete, etc.) or archive/un-archive the [PRJ], except for normal users, who cannot delete the [PRJ].', 'v_help_arch_1' => 'archived [PRJS]', 'v_help_arch_2' => '[PRJS] no longer used can be archived.', 'v_help_arch_3' => 'An archived [PRJ] cannot be modified (edited or deleted) and no passwords can be added to it or deleted from it.', 'v_help_arch_4' => 'To archive a [PRJ] (you can only do it if you are an Administrator or manager the [PRJ]) click on the "Archive" button on the [PRJ] screen. You can also un-archive a [PRJ] (and it will become active again) by clicking on the "Un-Archive" button on its screen.', // Advanced Search Help 'c_help_adv_title' => 'Advanced Search Help', 'v_help_adv_desc_1' => 'When searching for <strong>passwords</strong> in Team Password Manager you can use special <strong>operators</strong> that can help you refine your results. Search operators are special words that allow you to find passwords quickly and accurately. You can use search operators in the main passwords list search box, in the passwords search box inside a [PRJ] and in my passwords list search box.', 'v_help_adv_desc_2' => 'In the main passwords list search box and in my passwords list search box you can also use an advanced search form by clicking on the dropdown box at the right of the search box.', 'v_help_adv_desc_3' => 'Here you have the list of password search operators in Team Password Manager', 'v_help_adv_operator' => 'Operator', 'v_help_adv_definition' => 'Definition', 'v_help_adv_example' => 'Example', 'v_help_adv_use_in' => 'Use in', 'v_help_adv_string' => 'string', 'v_help_adv_main' => 'main', 'v_help_adv_main_desc' => 'main passwords list search box', 'v_help_adv_project' => '[PRJ]', 'v_help_adv_project_desc' => 'passwords search box inside a [PRJ]', 'v_help_adv_my' => 'my', 'v_help_adv_my_desc' => 'my passwords list search box', 'v_help_adv_or' => 'or', 'v_help_adv_equiv_no_operator' => 'equivalent to using no operator', 'v_help_adv_my_prj' => 'my project', 'v_help_adv_use_shown' => 'Use as shown', 'v_help_adv_def_any' => 'Search passwords that have the string in the following fields: name, notes, access, username, email, all custom fields and tags', 'v_help_adv_def_basic' => 'Search passwords that have the string in the following fields: name, notes, access, username and email', 'v_help_adv_def_custom' => 'Search passwords that have the string in any of the custom fields', 'v_help_adv_def_name' => 'Search passwords that have the string in the name field', 'v_help_adv_def_notes' => 'Search passwords that have the string in the notes field', 'v_help_adv_def_access' => 'Search passwords that have the string in the access field', 'v_help_adv_def_username' => 'Search passwords that have the string in the username field', 'v_help_adv_def_email' => 'Search passwords that have the string in the e-mail field', 'v_help_adv_def_username_email' => 'Search passwords that have the string in the username OR e-mail field', 'v_help_adv_def_in' => 'Search passwords that their [PRJ] name matches string', 'v_help_adv_def_tag' => 'Search passwords that have a tag that matches the string', 'v_help_adv_def_file' => 'Search passwords that have files that their name or notes (the file notes, not the password notes) matches string. See also: has:file', 'v_help_adv_def_has_file' => 'Search passwords that have one or more files. See also: file:string', 'v_help_adv_def_has_expiry' => 'Search passwords that have an expiry date', 'v_help_adv_def_has_external' => 'Search passwords that are shared externally', 'v_help_adv_def_is_active' => 'Search only active (not archived) passwords', 'v_help_adv_def_is_archived' => 'Search only archived passwords', 'v_help_adv_def_is_favorite' => 'Search only favorite passwords (of the user that does the search)', 'v_help_adv_def_is_locked' => 'Search only locked passwords', 'v_help_adv_notes' => 'Notes', 'v_help_adv_notes_1' => 'Search is always case and accent insensitive.', 'v_help_adv_notes_2' => 'If the string being searched is composed of more than one word, the search will match if all the words are found. Example: name:"new api" will find passwords with the following names: "This is a new password that uses the api" and "APIs for new service".', 'v_help_adv_notes_3' => 'You can combine operators to perform an AND search. Example: file:.pdf is:favorite (search my favorite passwords that have pdf files).', 'v_help_adv_notes_4' => 'Use "" to group words in the same operator. Example: name:"server ftp"', 'v_help_adv_notes_5' => "By default, searches are performed with beginning and ending wildcards. In SQL it's like this: LIKE '%string%'. This will search any text that contains any part of string. If you want to search for an exact match you can use [ and/or ]. Example: username:[root] will search for passwords that have root (and only root) as username. You can use both [ ] (exact match), only [ (strings that begin with) or only ] (strings that end with). Example: email:[info@ will search for passwords that begin with info@ in the email field.", // Export / import 'c_help_ei_title' => 'Export/Import Passwords Help', 'v_help_exp_title' => 'Exporting passwords', 'v_help_exp_desc_1' => '<strong>Team Password Manager</strong> lets <strong>Admin/IT</strong> users export all passwords (or passwords from a selected [PRJ]) to a CSV (Comma-separated Values) file.', 'v_help_exp_desc_2' => 'This file will contain the following information for each password', 'v_help_exp_prj_name' => '[PRJ] name', 'v_help_exp_pwd_name' => '<PASSWORD>', 'v_help_exp_access' => 'Access information', 'v_help_exp_username' => 'Username', 'v_help_exp_email' => 'E-mail', 'v_help_exp_pwd' => '<PASSWORD> (unencrypted)', 'v_help_exp_notes' => 'Notes', 'v_help_exp_tags' => 'Tags (separated by comma)', 'v_help_exp_cfnames' => 'Custom fields names (separated by comma)', 'v_help_exp_cf1' => 'Custom field 1 (unencrypted)', 'v_help_exp_cf10' => 'Custom field 10 (unencrypted)', 'v_help_exp_edate' => 'Expiry date', 'v_help_exp_edate_format' => 'format', 'v_help_exp_edate_formatmdy' => 'mm-dd-yyyy', 'v_help_exp_sorted' => 'the passwords are sorted by [PRJ] name and password name.', 'v_help_exp_enclosed' => 'Each value is enclosed in double quotes (") and separated by a comma (,). The file is UTF-8 encoded.', 'v_help_exp_double_quotes' => 'Double quotes (") are encoded as \" and backslashes (\) as \\\\.', 'v_help_exp_click' => 'Click here to export passwords', 'v_help_imp_title' => 'Importing passwords', 'v_help_imp_desc_1' => '<strong>Team Password Manager</strong> lets <strong>Admin/IT</strong> users import passwords from a CSV (Comma-separated Values) file. This file must have the following properties', 'v_help_imp_desc_2' => 'Each value must be enclosed in double quotes (") and separated by a comma (,).', 'v_help_imp_desc_3' => 'The file must be UTF-8 encoded.', 'v_help_imp_desc_4' => 'Each line on the file must be a password with the following fields', 'v_help_imp_optional' => 'Optional', 'v_help_imp_desc_5' => 'There must be no field headers (if they exist they will be imported as normal passwords).', 'v_help_imp_desc_6' => 'The file extension must be csv.', 'v_help_imp_desc_7' => 'If a field contains a double quote ("), a backslash must be prepended to it: \". So, for instance, the text "inside quotes", would have to be written like this in the csv file: ...,"<strong>\"inside quotes\"</strong>",...', 'v_help_imp_desc_8' => 'Likewise, if a field contains a backslash (\), another backslash must be prepended to it: \\\\.', 'v_help_imp_sample_1' => 'Sample file', 'v_help_imp_sample_2' => 'this sample file contains 2 [PRJS] ("Software" and "Hardware") and 2 passwords in each', // Do not translate "Software" and "Hardware" 'v_help_imp_how_1' => 'How the import process works', 'v_help_imp_how_2' => 'First, the file with the passwords to import is uploaded to the server.', 'v_help_imp_how_3' => "The import process will then read the file line by line and will look for the '[PRJ] name' from each line in the database. If the [PRJ] exists, it will import the password in the existing [PRJ]. If the [PRJ] doesn't exist it will be created (and then the password imported to the new [PRJ]).", 'v_help_imp_how_4' => "[PRJS] created by the import process will have 'Grant access to this [PRJ] to the following users and/or groups.' as their security setting (and no user or group checked).", 'v_help_imp_how_5' => 'if the password name already exists in the [PRJ], it will not be imported.', 'v_help_imp_how_6' => 'as you can see, the information in the database is not overwritten, only new [PRJS] or passwords are imported.', 'v_help_imp_how_7' => 'During the process, the main log is updated detailing what has happened in each line. You can download this as a log file at the end.', 'v_help_imp_how_8' => 'At the end of the process, the uploaded file will be deleted (for security reasons).', 'v_help_imp_other_1' => 'Other requirements', 'v_help_imp_other_2' => "For the import process to work, a folder called 'import' must exist in the root folder of Team Password Manager. Also, this folder must be writable. The import process will prompt the user to create this folder if it doesn't exist.", 'v_help_imp_click' => 'Click here to import passwords', // Export/Import My Passwords Help 'c_help_eimy_title' => 'Export/Import My Passwords Help', 'v_help_exp_my_title' => 'Exporting My Passwords', 'v_help_exp_my_desc_1' => '<strong>Team Password Manager</strong> lets users export all the passwords from the "My Passwords" section to a CSV (Comma-separated Values) file.', 'v_help_exp_my_sorted' => 'The passwords are sorted by password name.', 'v_help_exp_my_click' => 'Click here to export all of my passwords', 'v_help_imp_my_title' => 'Importing My Passwords', 'v_help_imp_my_desc_1' => '<strong>Team Password Manager</strong> lets users import passwords to the "My Passwords" section from a CSV (Comma-separated Values) file. This file must have the following properties', 'v_help_imp_my_sample_2' => 'This sample file contains 4 passwords', 'v_help_imp_my_how_3' => 'If the password name already exists, it will not be imported.', 'v_help_imp_my_how_4' => 'As you can see, the information in the database is not overwritten, only new passwords are imported.', 'v_help_imp_my_click' => 'Click here to import my passwords', );<file_sep><?php $lang = array ( // Language to use in headers of html pages (<html lang="XX">) // See: https://www.w3.org/International/questions/qa-html-language-declarations.en 'html_lang' => 'en', // Locale for the datepicker component // See all the locales here: /css/js/datepicker/js/locales 'datepicker_locale' => 'en', 'datepicker_weekstart' => 0, // 0=Sunday, 1=Monday, etc. 'prj' => 'project', 'cap_prj' => 'Project', // cap=1st letter capitalized 'prjs' => 'projects', 'cap_prjs' => 'Projects', 'subprj' => 'subproject', 'cap_subprj' => 'Subproject', 'subprjs' => 'subprojects', 'cap_subprjs' => 'Subprojects', 'cap_pwds' => 'Passwords', 'cap_pwd' => '<PASSWORD>', 'cancel' => 'Cancel', 'ok' => 'Ok', 'save' => 'Save', 'no' => 'No', 'yes' => 'Yes', 'tpm_required' => 'required', 'show' => 'Show', 'hide' => 'Hide', 'tag' => 'Tag', 'tags' => 'Tags', 'in' => 'in', 'pwd_name' => 'Name', 'pwd_access' => 'Access', 'pwd_username' => 'Username', 'pwd_email' => 'E-mail', 'repeat_pwd' => '<PASSWORD>', 'pwd_expiry_date' => 'Expiry date', 'pwd_notes' => 'Notes', 'pwd_expires_today' => 'Expires today', 'pwd_expired' => 'Expired', 'pwd_will_expire_soon' => 'Will expire soon', 'pwd_expired_or_today' => 'Expired or expires today', 'cf_do_not_use' => 'Do not use custom field', 'cf_text' => 'Text', 'cf_enc_text' => 'Encrypted text', 'cf_email' => 'E-mail', 'cf_pwd' => '<PASSWORD>', 'cf_notes' => 'Notes', 'cf_enc_notes' => 'Encrypted notes', 'you' => 'you', 'inactive' => 'Inactive', 'deleted_user' => 'deleted user', // pwd permissions 'PWD_PERM_DO_NOT_SET' => '(Do not set)', 'PWD_PERM_READ' => 'Read', 'PWD_PERM_EDIT' => 'Edit data', 'PWD_PERM_MANAGE' => 'Manage', 'PWD_PERM_NO_ACCESS' => 'No access', // prj permissions 'PRJ_PERM_DO_NOT_SET' => '(Do not set)', 'PRJ_PERM_ACCESS_TRAVERSE' => 'Traverse', 'PRJ_PERM_ACCESS_READ' => 'Read', 'PRJ_PERM_ACCESS_CREATE_PWD'=> 'Read / Create passwords', 'PRJ_PERM_ACCESS_EDIT_PWD' => 'Read / Edit passwords data', 'PRJ_PERM_ACCESS_MANAGE_PWD'=> 'Read / Manage passwords', 'PRJ_PERM_MANAGE' => 'Manage', 'PRJ_PERM_INHERIT' => 'Inherit from parent', 'PRJ_PERM_NO_ACCESS' => 'No access', 'Normal user' => 'Normal user', 'Admin' => 'Admin', 'Project manager' => '[PRJ] manager', 'Read only' => 'Read only', 'IT' => 'IT', 'total_rows' => 'Total rows', 'prj_name' => 'Name', 'prj_notes' => 'Notes', 'error' => 'Error', 'errors' => 'Errors', // Top menu 'menu_home' => 'Home', 'menu_user_groups' => 'Users / Groups', 'menu_log' => 'Log', 'menu_settings' => 'Settings', 'menu_my_passwords' => 'My Passwords', 'menu_logout' => 'Logout', // Free version 'free_line_1' => "you're using the FREE VERSION of Team Password Manager, which only allows you to have 2 users and 5 [PRJS].", 'free_line_2' => 'click here for more users and [PRJS]', // Footer 'footer_eula' => 'EULA and other licenses', 'footer_help' => 'Help', 'footer_search_help' => 'Advanced Search Help', // Demo 'demo_desc' => 'This is a <strong>demo</strong> of <strong>Team Password Manager</strong>. Data is reset everyday at 02:00 AM (PDT / GMT - 7).', 'demo_feedback' => 'Any feedback is greatly appreciated', 'demo_download' => 'Download Team Password Manager and install it on your own server', // File sizes 'bytes' => 'Bytes', 'kb' => 'Kb', 'mb' => 'Mb', 'gb' => 'Gb', 'tb' => 'Tb', 'sort_by' => 'Sort by', 'user' => 'User', 'group' => 'Group', 'users' => 'Users', 'groups' => 'Groups', 'deleted' => 'deleted', 'examples' => 'Examples', 'required_fields' => 'required fields', 'server' => 'Server', 'not_defined' => 'not defined', 'instructions' => 'Instructions', 'protocol' => 'Protocol', 'page_not_exist' => 'This page does not exist or you cannot access it.', 'main_large_msg_default_btn'=> 'Ok', 'main_edit_modal_cancel' => 'Cancel', 'main_edit_modal_save' => 'Save', // Form validation // IMPORTANT NOTE: USE "" INSTEAD OF '' IN THE DESCRIPTION OF THESE STRINGS 'form_validation_required' => "The %s field is required.", 'form_validation_isset' => "The %s field must have a value.", 'form_validation_valid_email'=> "The %s field must contain a valid email address.", 'form_validation_valid_emails'=> "The %s field must contain all valid email addresses.", 'form_validation_valid_url' => "The %s field must contain a valid URL.", 'form_validation_valid_ip' => "The %s field must contain a valid IP.", 'form_validation_min_length' => "The %s field must be at least %s characters in length.", 'form_validation_max_length' => "The %s field can not exceed %s characters in length.", 'form_validation_exact_length'=> "The %s field must be exactly %s characters in length.", 'form_validation_alpha' => "The %s field may only contain alphabetical characters.", 'form_validation_alpha_numeric'=> "The %s field may only contain alpha-numeric characters.", 'form_validation_alpha_dash' => "The %s field may only contain alpha-numeric characters, underscores, and dashes.", 'form_validation_numeric' => "The %s field must contain only numbers.", 'form_validation_is_numeric' => "The %s field must contain only numeric characters.", 'form_validation_integer' => "The %s field must contain an integer.", 'form_validation_regex_match'=> "The %s field is not in the correct format.", 'form_validation_matches' => "The %s field does not match the %s field.", 'form_validation_is_unique' => "The %s field must contain a unique value.", 'form_validation_is_natural' => "The %s field must contain only positive numbers.", 'form_validation_is_natural_no_zero' => "The %s field must contain a number greater than zero.", 'form_validation_decimal' => "The %s field must contain a decimal number.", 'form_validation_less_than' => "The %s field must contain a number less than %s.", 'form_validation_greater_than'=> "The %s field must contain a number greater than %s.", // Running conditions 'm_ac_mcrypt_not_installed' => 'The Mcrypt PHP library is not installed.', 'm_ac_mbstring_not_installed' => 'The Multibyte String (mbstring) library is not installed.', 'm_ac_mysqli_not_installed' => 'The mysqli extension is not installed.', 'm_ac_db_not_set' => 'The database connection parameters are not set.', 'm_ac_tables_missing' => 'Some or all of the database tables are missing. You probably need to execute the install or upgrade procedure.', 'm_ac_execute_upgrade' => 'You need to execute the upgrade procedure', 'm_ac_cannot_run' => 'Team Password Manager cannot run due to the following errors', 'm_ac_contact_admin' => 'Please contact your systems administrator.', 'm_ac_db_ko' => 'Database is not set or cannot be accessed. Check database configuration.', // Notifications 'tpm_notification' => 'TPM Notification', 'automated_message' => 'This is an automated message from Team Password Manager.', );<file_sep><?php // Set these database parameters before installing Team Password Manager on heroku if (getenv("ENCRYPT_DB_CONFIG") == "1") { //echo "ENCRYPT_DB_CONFIG is ON"; define('ENCRYPT_DB_CONFIG', 1); $server = getenv("CONFIG_HOSTNAME"); $username = getenv("CONFIG_USERNAME"); $password = getenv("CONFIG_PASSWORD"); $db = getenv("CONFIG_DATABASE"); } else { //echo "ENCRYPT_DB_CONFIG is OFF"; $url = parse_url(getenv("CLEARDB_DATABASE_URL")); $server = $url["host"]; $username = $url["user"]; $password = $url["pass"]; $db = substr($url["path"], 1); } // MySQL Database server define('CONFIG_HOSTNAME', $server); // User that accesses the database server, that should have all privileges on the database CONFIG_DATABASE define('CONFIG_USERNAME', $username); // User password define('CONFIG_PASSWORD', $<PASSWORD>); // Database for Team Password Manager. You must manually create it before installing Team Password Manager define('CONFIG_DATABASE', $db); // Default language of the installation. // The user can change this language. // Defaults to "en" if not used. //define('TPM_DEFAULT_LANG', 'en'); // Uploads folder. You can set it in two ways: // 1. With an absolute path. Example: /var/www/domain/uploads/ // 2. With a relative path (relative to index.php). Example: ./uploads/ // Must be accessible and writable by the web server // Define with or without trailing slash // Defaults to ./uploads/, uncomment the following line to change this default value: //define('UPLOADS_FOLDER' , './uploads/'); // For other parameters read: http://teampasswordmanager.com/docs/all-parameters-config-php/<file_sep><?php // Language configuration file // For more information see: http://teampasswordmanager.com/docs/languages/ $lang = array ( // Version of the language files, it should match the one in the software (see Settings | Languages) 'lang_files_version' => 2, // Description of the language 'lang_description' => 'English', );<file_sep><?php $lang = array ( // Controllers/models 'c_install_title' => 'Install', 'c_install_session_data_expired' => 'Session data expired', 'c_install_try_again' => 'Please try again', 'c_install_username' => 'Username', 'c_install_email' => 'E-mail address', 'c_install_pwd' => '<PASSWORD>', 'c_install_repeat_pwd' => '<PASSWORD>', 'c_install_name' => 'Name', 'c_install_eula_agreement' => 'EULA Agreement', 'c_install_username_invalid' => 'The username contains invalid characters.', 'm_install_incorrect_version' => "Incorrect version. This indicates that the index.php file doesn't match the rest of the software. Debug info", 'm_install_php_version_56' => 'PHP version must be 5.6.0 or greater, now is', 'm_install_always_populate_raw_post_data' => 'The always_populate_raw_post_data parameter in php.ini must be -1. Set always_populate_raw_post_data=-1 in php.ini and restart the web server.', 'm_install_db_not_set_config' => 'The database connection parameters are not set. You must set them in config.php.', 'm_install_tables_exist' => 'Some or all of the tables of the database already exist. Choose an empty database and set it in config.php.', 'm_install_db_not_correctly' => 'The database is not correctly set in config.php (it does not exist or cannot be accessed).', 'm_install_problem_testing_db' => 'Problem testing database operations (normally due to incorrect database privileges, but could be other another issue). This operation has failed', 'm_install_cannot_install' => 'Team Password Manager cannot be installed due to the following errors', 'm_install_cannot_upgrade' => 'Team Password Manager cannot be upgraded due to the following errors', 'm_install_correct_execute' => 'Please correct them and execute the installation procedure again.', 'm_install_correct_execute_upgrade' => 'Please correct them and execute the upgrade procedure again.', 'm_install_error_creating_table' => 'Error creating table', 'm_install_verify_priv_table' => 'Verify that the database user has enough privileges to create the table.', 'm_install_error_creating_tables' => 'Error creating tables. Check that the database user has table creation privileges.', 'm_install_error_options' => 'Error writing options table. Check that the database user has insert privileges.', 'm_install_error_roles' => 'Error writing roles table. Check that the database user has insert privileges.', 'm_install_error_ekey' => 'Error creating encryption key. Check that the database user has insert privileges.', 'm_install_error_admin' => 'Error creating the admin user', 'm_install_exception_admin' => 'Error creating the admin user. Check that the database user has insert privileges.', 'm_install_errors_during_install' => 'The following errors have occurred during install', 'm_install_correct_support' => 'Please correct them (or contact support) and execute the installation procedure again.', 'm_install_error_inserting_counters' => 'Error inserting counters', 'c_upgrade_title' => 'Upgrade', 'c_upgrade_incorrect_user' => 'The user entered is not an admin/IT user or incorrect username or password.', 'm_install_tpm_uptodate' => 'Team Password Manager is up to date. No upgrading is required.', 'm_install_table_not_exists' => 'This table does not exist', 'm_install_keyphp_not_exists' => 'key.php file does not exist', 'm_install_db_not_found' => 'Database not found.', 'm_install_upgrading_smaller' => "The version you are upgrading to is smaller than the one that's installed.", 'm_install_upgrading_smaller_to' => 'Upgrading to', 'm_install_upgrading_smaller_from' => 'Installed', 'm_install_enc_key_not_defined' => 'Encryption key not defined (key.php missing or Encryption key not set).', 'm_install_errors_upgrading' => 'There have been errors upgrading, in query or process', 'm_install_contact_support' => 'Please contact support.', 'm_install_upgrade_stopped' => 'Upgrade stopped. Please contact support.', 'm_install_failed_query' => 'Failed query', 'c_upgrade_admin_it_username' => 'Admin/IT username', 'c_upgrade_admin_it_email' => 'Admin/IT email', // Views 'v_install_v' => 'v.', // for version, eg v. xxx 'v_install_enter_data' => 'Enter the data for the <strong>admin user</strong> of Team Password Manager (<strong>all of the fields are required</strong>)', 'v_install_8cm' => '8 characters minimum', 'v_install_agree_eula' => 'I agree to the End User License Agreement', 'v_install_submit_data' => 'Submit data to complete installation', 'v_install_tpm_installed_ok' => 'Team Password Manager has been installed correctly.', 'v_install_tpm_installed_del_files' => 'We advise you to delete the following files from your Team Password Manager folder: install.txt, eula.txt and upgrade.txt.', 'v_install_tpm_installed_lic' => 'If you have purchased a license you will be able to register it by going to the Settings | Licenses menu after signing in.', 'v_install_tpm_installed_maysignin' => 'You may now login to Team Password Manager with the user created in the previous step', 'v_install_tpm_installed_signin' => 'Team Password Manager Sign In', 'v_upgrade_ok' => 'Team Password Manager has been upgraded correctly to version', 'v_upgrade_keyphp_not_needed' => 'The key.php file is no longer required in this new version, so it is advised that you delete it. You should delete it manually.', 'v_upgrade_old_hashing_system' => 'You have upgraded an old version of Team Password Manager that used an old system for hashing the passwords from users. As a result, the rest of the users will have to reset password to be able to gain access to Team Password Manager.', 'v_upgrade_btn' => 'Upgrade', 'v_upgrade_process_desc' => 'This process will upgrade your installation of Team Password Manager', 'v_upgrade_from_version' => 'From version', 'v_upgrade_to_version' => 'To version', 'v_upgrade_expired_note_1' => '<strong>Note:</strong> the following licenses have expired the support and updates period', 'v_upgrade_expired_note_2' => 'To be able to use these licenses with the version you are about to upgrade you will need to attach a "Support and Updates" license to each one of them. You can do this after upgrading.', 'v_upgrade_purchase_su' => 'Purchase "Support and Updates" licenses', 'v_upgrade_more_information' => 'More information', 'v_upgrade_backup_note' => 'Upgrading Team Password Manager can make changes to the database structure (and sometimes data), so we advise that you make a backup copy of the database. See here how to make a backup of the database', 'v_upgrade_enter_adminit_desc' => 'Enter an Admin or IT username and password and click the "Upgrade" button to proceed.', );<file_sep># teampasswordmgr-heroku Team Password Manager (v7.73.146) for Heroku [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) <file_sep><?php $lang = array ( // Controllers 'c_login_sign_in_title' => 'Sign In', 'c_login_session_expired' => 'Sign in session expired, please try again', 'c_login_username_pwd_incorrect' => 'The username or password you entered is incorrect', 'c_login_auth_code_not_valid' => 'Authentication code not valid', 'c_login_session_expired' => 'Session expired, try again', 'c_login_email' => 'E-mail address', 'c_login_new_pwd' => '<PASSWORD>', 'c_login_repeat_new_pwd' => '<PASSWORD>', 'c_login_reset_email_1' => 'An email message has been sent to the provided address with instructions on how to reset your password.', 'c_login_reset_email_2' => "Please check your email client. Check your spam folder if you don't find the message in you inbox folder.", 'c_login_reset_failed_1' => 'There has been an error sending the email message to the provided address.', 'c_login_contact_admin' => 'Please contact your administrator.', 'm_usr_reset_msg_1' => 'This message is sent from your installation of Team Password Manager, on your request to reset your password. ', 'm_usr_reset_msg_2' => "Click the following link or copy and paste it on your browser's address bar to reset your password: ", 'c_login_pwd_reset' => '<PASSWORD>', 'c_login_reset_in_ldap_server' => 'You should reset your password in the LDAP server.', 'c_login_enter_2fa_code' => 'enter 2FA code', 'c_login_pwd_reset_error' => 'There has been an error resetting your password.', 'c_login_pwd_reset_ok' => 'You password has been reset, you may now sign in with your new password.', // Views 'v_login_sign_in_lbl' => 'Sign In', 'v_login_sign_in_btn' => 'Sign In', 'v_login_username' => 'Username', 'v_login_password' => '<PASSWORD>', 'v_login_forgot_pwd' => 'Forgot your password?', 'v_login_free_line_1' => 'This is the FREE VERSION of Team Password Manager', 'v_login_free_line_2' => 'click here to get MORE than 2 users and 5 [PRJS]!', 'v_login_auth_code' => 'Authentication code', 'v_login_authenticate' => 'Authenticate', 'v_login_back_sign_in' => 'Back to Sign In', 'v_login_forgot_pwd_enter_email' => "Enter your email address and you'll receive instructions on how to reset your password", 'v_login_submit' => 'Submit', 'v_login_forgot_pwd_enter_data' => 'Enter the following data to reset your password', 'v_login_8charsmin' => '8 chars. min.', 'v_login_required' => 'required', // Automatic IP blocking 'm_ipb_notif_header' => 'TPM Notification: IP address automatically blocked', // Careful with accents, etc. 'm_ipb_ip_added' => 'This IP address has been automatically added to the list of blocked IPs', 'm_ipb_failed_attempts' => 'Number of failed sign in attempts', 'm_ipb_period' => 'Period (seconds)', 'm_ipb_automated_message' => 'This is an automated message from Team Password Manager.', );<file_sep><?php $lang = array ( // Language to use in headers of html pages (<html lang="XX">) // See: https://www.w3.org/International/questions/qa-html-language-declarations.en 'html_lang' => 'en', // = general_lang.php 'nojs_activate_js' => 'Activate Javascript', 'nojs_explanation' => '<strong>Team Password Manager</strong> only runs on browsers that have Javascript enabled. Please activate Javascript in your browser.', 'nojs_goto_tpm' => 'Go to Team Password Manager' );<file_sep><?php $lang = array ( // controllers/mypwd 'c_mypwd_invalid_pek_title' => 'My Passwords: invalid Personal Encryption Key', 'c_mypwd_invalid_pek_desc' => 'Your Personal Encryption Key is not valid. Please contact support.', 'c_mypwd' => 'My Password', 'c_mypwd_not_found_title' => 'Password not found', 'c_mypwd_not_found_desc' => 'This password does not exist or you cannot access it.', 'c_mypwd_pwd_exists' => 'The password already exists.', 'c_mypwd_new' => 'New Password', 'c_mypwd_edit' => 'Edit My Password', 'c_mypwd_edit_error' => 'There has been an error saving the password', 'c_mypwd_edit_csrf_error' => 'There has been a CSRF error saving the password, please try again.', 'c_mypwd_return' => 'Return to my password', 'c_mypwd_del' => 'Delete My Password', 'c_mypwd_del_ok' => 'The password has been deleted.', 'c_mypwd_del_error' => 'There has been an error deleting the password.', 'c_mypwd_del_csrf_error' => 'There has been a CSRF error deleting the password, please try again.', 'c_mypwd_goto_pwd' => 'Go to the password', 'c_mypwd_copy_archived' => 'the destination [PRJ] is <span class="label label-warning tpm-archived">Archived</span>.', 'c_mypwd_copy_exists' => 'the password already exists in the destination [PRJ].', 'c_mypwd_copy_cannot' => 'you cannot create passwords in the destination [PRJ].', 'c_mypwd_copy_prj_not_exists' => 'the destination [PRJ] does not exist or you cannot access it.', 'c_mypwd_copy' => 'Copy My Password', 'c_mypwd_copy_cannot_reason' => 'This password cannot be copied for the following reason', 'c_mypwd_copy_error' => 'There has been an error copying the password', 'c_mypwd_copy_ro' => 'You cannot copy/create passwords, you have a read only role.', 'c_mypwd_copy_csrf_error' => 'The password has NOT been copied (CSRF validation), please try again.', 'c_mypwd_copy_ok_error' => 'The password has been copied, but there has been this error doing so', 'c_mypwd_copy_pwd_prj_not_exist' => 'The password/[PRJ] does not exist or you cannot access it.', 'c_mypwd_move' => 'Move My Password', 'c_mypwd_move_cannot_reason' => 'This password cannot be moved for the following reason', 'c_mypwd_move_error' => 'There has been an error moving the password', 'c_mypwd_move_ro' => 'You cannot move/create passwords, you have a read only role.', 'c_mypwd_move_csrf_error' => 'The password has NOT been moved (CSRF validation), please try again.', 'c_mypwd_move_ok_error' => 'The password has been moved, but there has been this error doing so', // views/mypwd 'v_mypwd_my_account' => 'My Account', // = v_users_my_account 'v_mypwd_my_settings' => 'My Settings', // = v_users_my_settings 'v_mypwd_my_passwords' => 'My Passwords', // = v_users_my_passwords 'v_mypwd_return_list' => 'Return to my passwords list', 'v_mypwd_edit_btn' => 'Edit', 'v_mypwd_copy_btn' => 'Copy', 'v_mypwd_move_btn' => 'Move', 'v_mypwd_del_btn' => 'Delete', 'v_mypwd_edit_title' => 'Edit password data', 'v_mypwd_copy_title' => 'copy password to a [PRJ]', 'v_mypwd_move_title' => 'move password to a [PRJ]', 'v_mypwd_del_title' => 'Delete password', 'v_mypwd_data' => 'Data', 'v_mypwd_no_data' => "This password doesn't have any data", 'v_mypwd_no_notes' => 'There are no notes for this password.', 'v_mypwd_created_on' => 'Created on', 'v_mypwd_updated_on' => 'Updated on', 'v_mypwd_by' => 'By', 'v_mypwd_ccall_copied' => 'Copied', 'v_mypwd_ccall_nothing' => 'Nothing to copy!', 'v_mypwd_ccall_error' => 'Error getting data to copy', 'v_mypwd_cc_copied' => 'Copied', 'v_mypwd_cc_nothing' => 'Nothing to copy!', 'v_mypwd_cc_error' => 'Error getting data to copy', 'v_mypwd_cc_not_supported' => 'This copy to clipboard method is not supported in this browser', 'v_mypwd_ccall' => 'Copy all the fields to clipboard', 'v_mypwd_cc' => 'Copy to clipboard', 'v_mypwd_ccnotes' => 'Copy notes to clipboard', 'v_mypwd_ccnotes_copied' => 'Copied', 'v_mypwd_ccnotes_nothing' => 'Nothing to copy!', 'v_mypwd_ccnotes_error' => 'Error getting data to copy', 'v_mypwd_sort_by_name' => 'Sort by Name', 'v_mypwd_list_auep' => 'Access / Username / Email / Password', 'v_mypwd_sort_by_updated' => 'Sort by Update Date', 'v_mypwd_updated' => 'Updated', 'v_mypwd_list_updated_ph' => 'Updated', 'v_mypwd_list_empty' => 'There are no passwords with this filter or search.', 'v_mypwd_sidebar_all_pwds' => 'All Passwords', 'v_mypwd_sidebar_search_res' => 'Search Results', 'v_mypwd_sidebar_filter_tag' => 'Filter by Tag', 'v_mypwd_sidebar_search_tags' => 'Search tags', 'v_mypwd_new_pwd' => '<PASSWORD>', 'v_mypwd_new_pwd_phone' => 'New', 'v_mypwd_search' => 'Search My Passwords', 'v_mypwd_search_phone' => 'Search', 'v_mypwd_adv_search_title' => 'Advanced search', 'v_mypwd_search_adv' => 'Search', 'v_mypwd_adv_help' => 'Advanced Search Help', 'v_mypwd_adv_search_any' => 'Any Field', 'v_mypwd_adv_search_username_email' => 'Username or E-mail', 'v_mypwd_adv_search_tag' => 'Tag', 'v_mypwd_edit_info_saved_enc' => 'this information is saved encrypted', 'v_mypwd_edit_tags_instruct' => 'Use a comma (,) for new tags, "tab" for selecting from the list', 'v_mypwd_edit_access_examples' => 'Examples: http://site, ftp://ip-address, manual login', 'v_mypwd_edit_click_gen_pwd' => 'Click to generate password', 'v_mypwd_edit_del_gen_pwd' => 'You need to delete the current password if you want to generate a new one!', 'v_mypwd_edit_pwd_generated' => '<PASSWORD>!', 'v_mypwd_del_confirm' => 'Delete this password?', 'v_mypwd_del_warning' => 'Warning: this action is permanent and cannot be un-done.', );
50184d319e12c65fb3fac48f1f0e6ae98c999ba7
[ "Markdown", "PHP" ]
17
PHP
CRMified/teampasswordmgr-heroku
82d8a3aae2133c457e0eec7fb57808a5afe08024
c42efbe9af32acaa63a81d47b3a7c1e0c7bfd123
refs/heads/master
<file_sep># #WEBSITE MONITORING TOOL# # DESCRIPTION This script will monitor Service Level Indicators (SLI) of a list of websites. Two SLIs will be monitored: SUCCESSFUL RESPONSE and FAST RESPONSE. - SUCCESSFUL RESPONSE - Responses with HTTP status code >= 200 and <= 499; - FAST RESPONSE - HTTP requests that are responded in 100ms or less. For a list of website url's a get request will be made every 5 seconds. Each SLI will compared with the given Service Level Objective (SLO). # REQUIREMENTS - Python 2.7 # INSTALLATION - Clone project or copy the websitemonitor.py and website_monitoring_tool.py files to the same folder # EXECUTION - First create a text file with website urls and their respective Service Level Objectives with the following format: <url>;<successful response SLO>;<fast response SLO> - url must be a string with a http format - the other 2 must be doubles >= 0.0 and <=100.0 - Open the terminal and execute: python website_monitoring_tool.py <text file with website urls and SLOs> - If every thing went well you will see the message: 'Monitoring has started!' # USAGE While the script is running you will see a simple option menu: Menu: s - Show Status r - Save Report q - Exit Choice: When you type and enter one of those options, the following will happen: s - Will be displayed on the terminal the current SLI the SLO and the STATUS (if SLI >= SLO GOOD will be displayed otherwise BAD); r - The same output seen on terminal when s is selected will be save on a text file called report.txt; q - The aplication will stop. # DEVELOPMENT CONSIDERATIONS This application was writen using Python for 3 reasons: 1 - It is very simple and powerful programming language; 2 - It is the programming language that lately I have used the most. 3 - I had few time to concept and build the application. Once I was asked to build a long-running application with user interaction and with some network tasks I decided to use multithreading. It allows the user to get partial reports while the application keep making requests and make HTTP requests over Internet without 'blocking' the application. All threads was created as daemons, it allows the application to exit even if some threads still alive. The necessary modules on this applications are only default modules that comes with Python 2.7, it is not necessary to install any extra modules. I decided to create a class called WebSiteMonitor because it helps to get reports to each monitored website. I used a list of thread to each website because as every 5 second a new request has to be made and even though the last request made cannot be a fast response anymore, once it has passed 5 seconds, it can be a successful response still. So, I create a new thread to the new request and keep the old one in the list. Not to keep finished threads in the list, I remove threads that are not alive anymore. # IMPROVEMENTS AND ISSUES The first improvement on this application was to create a better user interface, although it does what it was asked for, this application is not user-friendly. A GUI to better user interaction and visualization can be done. Another alternative would be use this script as content provider to a web application with a better user interface. Another improvement would be finding a better way to calculate the request response time. Doing some fast research I found some modules that return the exactly response time to a request, I did not use this because I did not have enough time and I wanted to keep this script simple. During tests I found out that the some DNS servers can cause a 'Name or service not known' error when monitoring more than 15-20 websites. Some forums said that this is error can be caused be the DNS server. I did not have time to better investigate this error and find solutions, so I used a try catch as a workaround. # CREDITS This script was developed by <NAME> (<EMAIL>) <file_sep>#Author: <NAME> #Date: 07/20/2017 #Local: Juazeiro-BA, Brazil import sys import threading import time import re import math from websitemonitor import WebSiteMonitor sites = [] begin_time = None begin_time_show = None #Verify if Exist any thread alive def has_alive_thread(threads): for thread in threads: if thread.is_alive(): return True return False #Validate inputs with regular expressions def validate_input(input): match = re.search(r'^\d{1,2}(\.\d+){0,1}$',input[1].replace(',','.')) if not match or not (float(input[1].replace(',','.')) >= 0 and float(input[1].replace(',','.')) <= 100 ): return False match = re.search(r'^\d{1,2}(\.\d+){0,1}$', input[2].replace(',','.')) if not match or not (float(input[2].replace(',','.')) >= 0 and float(input[2].replace(',','.')) <= 100 ): return False match = re.search(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', input[0]) if not match: return False return True #Read input file with URL's and SLO's def read_file(file): sites=[] try: with open(file,'r') as file: for line in file: info = line.split(';') if len(info) < 3: print('\nError on line - {}.\n' 'Correct format is: <url>;<successful response SLO>;<fast response SLO>'.format(line.strip())) else: if not validate_input(info): print('\nError with url format or double values on line - {}.\n' 'Correct format is: <url>;<double>;<double>'.format(line.strip())) continue url = info[0].strip() if url[-1] == '/': url = url[:-1] site = WebSiteMonitor(url,float(info[1]),float(info[2]), float(info[3])) sites.append(site) except IOError: print('Could not open file {}.'.format(file)) exit() return sites #Thread responsable for making requests every 5 seconds def make_requests_thread(): count = 0 while True: for site in sites: site.make_request() time.sleep(5) count += 1 if count == 12: for site in sites: site.calc_percentil() count = 0 #Mount string with websites status info def get_status_info(): info = 'SHOW WEBSITE STATUS\n' info += 'BEGIN TIME {}\n'.format(time.strftime('%d/%m/%Y -- %H:%M:%S', begin_time_show)) info += 'NOW {}\n'.format(time.strftime('%d/%m/%Y -- %H:%M:%S')) info += '{0:40s}\t{1:40s}\t{2:30s}\t{3:30s}\n'.format('', 'SUCCESSFUL RESPONSE', 'FAST RESPONSE', 'PERCENTIL') info += '{0:40s}\t{1:10s}\t{2:10s}\t{3:10s}\t{4:10s}\t{5:10s}\t{6:10s}\t{7:10s}\t{8:10s} {9}\n' \ .format('URL', 'SLI', 'SLO', 'STATUS', 'SLI', 'SLO', 'STATUS', 'SLI', 'SLO', 'STATUS','OBS') for site in sites: if site.req_n == 0: info += '{0:30s}\t{1}\n'.format(site.url, 'NO REQUESTS') continue sli_succ_resp = float(site.succ_res_n / float(site.req_n)) * 100 sli_fast_resp = float(site.fast_res_n / float(site.req_n)) * 100 if sli_fast_resp < site.fast_res_slo: fast_sli_status = 'BAD' else: fast_sli_status = 'GOOD' if sli_succ_resp < site.succ_res_slo: succ_sli_status = 'BAD' else: succ_sli_status = 'GOOD' if has_alive_thread(site.threads): alive_threads = '*{}'.format(len(site.threads)) else: alive_threads = '' if site.dns_error: dns_error = '+' else: dns_error = '' time_now = time.time() min_passed = (time_now - begin_time)/60.0 min_passed = math.floor(min_passed) if min_passed!= 0: perc_sli = (site.perc_ok_n/min_passed)*100 else: perc_sli = 0.0 if perc_sli < site.perc_slo: perc_status = 'BAD' else: perc_status = 'GOOD' info += '{0:40s}\t{1:10.2f}%\t{2:10.2f}%\t{3:10s}\t{4:10.2f}%\t{5:10.2f}%\t{6:10s} \t{7:10.2f}%\t{8:10.2f}%\t{9:10s} {10}{11}\n'.format( site.url[:35], sli_succ_resp, site.succ_res_slo, succ_sli_status, sli_fast_resp, site.fast_res_slo, fast_sli_status, perc_sli, site.perc_slo, perc_status, alive_threads, dns_error) info += 'Legend:\n* - Waiting for succesful responses\n+ - DNS Error' return info #Save report with websites' status def save_report(): print('Save status to report.txt') try: with open('report.txt','w') as file: file.write(get_status_info()) except IOError: print('Could not save file report.txt!') #Display website's status on terminal def show_status(): print(get_status_info()) #Main if __name__ == "__main__": if len(sys.argv) < 2: print('usage: python website_monitoring_tool.py <file_with_sites_urls_and_slos>') else: print('Web Site SLO Monitor') print('\nReading file with URL\'s and SLO\'s') sites = read_file(sys.argv[1]) thread = threading.Thread(target=make_requests_thread) thread.daemon = True thread.start() begin_time = time.time() begin_time_show = time.localtime() print('\nMonitoring has started!') while True: print('\nMonitoring...') print('Menu:\ns - Show Status\nr - Save Report\nq - Exit') input = raw_input('Choice:') if input == 'q': exit(0) elif input == 's': show_status() elif input == 'r': save_report() <file_sep>#Author: <NAME> #Date: 07/20/2017 #Local: Juazeiro-BA, Brazil import httplib import threading import time import numpy as np class WebSiteMonitor: #Class constructor. def __init__(self, url, succ_res_slo, fast_res_slo, perc_slo): self.url = url self.succ_res_slo = succ_res_slo self.fast_res_slo = fast_res_slo self.perc_slo = perc_slo self.req_n = 0 self.succ_res_n = 0 self.fast_res_n = 0 self.dns_error = False self.threads = [] self.req_time = [] self.perc_ok_n = 0 #Thread responsable for making requests def __make_request_thread(self, show=False): try: self.req_n += 1 req_nn = self.req_n conn = httplib.HTTPConnection(host=self.url.replace('http://',''), timeout=30) begin_time = time.time() conn.request("GET", "/") end_time = time.time() req_time_value = end_time - begin_time self.req_time.append(req_time_value) resp = conn.getresponse() if resp.status in range(200, 500): self.succ_res_n += 1 if (end_time - begin_time) <= 0.1: self.fast_res_n += 1 #For Debugging if show: print('\nWeb Site: {}'.format(self.url)) print('Request - {}/{}'.format(req_nn,self.req_n)) print('Time: {}s'.format((end_time-begin_time))) print('Status: {}'.format(resp.status)) except Exception as e: if 'Name or service not known' in e: self.dns_error = True print('\nError: Name or service not known({}). Verify your DNS Server!'.format(self.url)) print('\nMonitoring...') print('Menu:\nr - Report\ns - Show status\nq - Exit') print('Choice:') def calc_percentil(self): percentil = np.percentile(self.req_time, 90) if percentil <= 1: self.perc_ok_n += 1 del self.req_time[:] def make_request(self): thread = threading.Thread(name=self.url+'-'+str(len(self.threads)), target=self.__make_request_thread) thread.daemon = True thread.start() #Insert thread in threads list self.threads.append(thread) #Remove threads that are not alive for thread in self.threads: if not thread.is_alive(): self.threads.remove(thread)
b1f07314051ee5ce2c5331aefb2ad7e63e0b2214
[ "Markdown", "Python" ]
3
Markdown
jardel-lima/WebSiteMonitoringTool
c04bc4a95542bc5f65f7ec1510e1c7e5549289d9
dbf6dc7d6e6b34d98ebd3c66231ea2e89c5b8f2b
refs/heads/master
<file_sep>// The purpose of this application is to create a shuffled deck of cards // The shuffle function was already provided by the tutor function shuffle(arr) { var j, x, i; for (i = arr.length - 1; i > 0; i--) { j = Math.floor(Math.random() * (i + 1)); x = arr[i]; arr[i] = arr[j]; arr[j] = x; } return arr; } function createDeck() { var suites = ['♠︎','♣︎','♥︎','♦︎']; var ranks = ['Ace','King','Queen','Jack','10','9','8','7','6','5','4', '3','2']; var deck = []; // First objective is to create the 2D array for ( let i=0;i<suites.length;i++){ for (let j=0;j<ranks.length;j++){ let card = deck.push(ranks[j]+" "+suites[i]); } } // We need to then shuffle the top level array and return it to the script return shuffle(deck); } // We call the function and assign the returned array to a variable "myDeck" var myDeck = createDeck(); // Show the shuffled deck of cards by looping through the array for ( let i=0;i<myDeck.length;i++){ console.log(myDeck[i]); }
8d6bb7feefb1db52a283c28d4dd4d36a55d82f1a
[ "JavaScript" ]
1
JavaScript
Sliminconcoova/deckOfCards
cf740b3da445e8bb78dd3569a9e894b5e347224e
91c6770d662273bcb44a778be91665f7e642a9da
refs/heads/main
<file_sep># Python Repositório de estudos Python
9d47e04cbdff80c6c995d538fae2b5559359c31a
[ "Markdown" ]
1
Markdown
Matheus-HX-Alves/Python
c96f71bdcc92d8704f701d7cdd0da4aa1a781a03
cbf1d890e749db2b370c78283b1c4a3778c9cb43
refs/heads/master
<file_sep>#include<iostream> #include "LinkList.h" #include <cmath> using namespace std; /*=========================================================== //===================== Notes =============================// - Create a Template LinkList Class! ===========================================================*/ //===========================================================// // Copy Constructor: // Copies and allocates spaces for a new list //===========================================================// LinkList::LinkList(LinkList &list) { LNode *head = list.retHead(); LNode *node = NULL; int index = 0; while (head) { node = list.indexNodePtr(index); index++; pushEnd(node->data_); head = head->next_; } } //===========================================================// // Destructor: // Deletes nodes an frees up allocated memory //===========================================================// LinkList::~LinkList() { int index = 0; int counter = 0; int size = size_; while (counter < size) { //removing the front index //until the list empty deleteIndex(index); counter++; } } //===========================================================// // listSize: Returns the number of nodes in the list // Receives: Nothing // Returns: _size = Number of nodes //===========================================================// int LinkList::listSize() { return size_; } //===========================================================// // displayList: Displays the entire list of nodes // Receives: Nothing // Returns: Nothing //===========================================================// void LinkList::displayList() { LNode *head = headPtr_; if (head == NULL || size_ == 0) { //cout << "List is currently Empty! " << endl; throw LLExceptions(EMPTY_LIST); } int count = 0; cout << "===== List Display =====" << endl; while (head) { cout << "[" << count << "]: " << head->data_ << endl; count++; head = head->next_; } } //===========================================================// // pushFront: Adds a node to the front of ther list // Receives: value = the data to insert into the list // Returns: True if successful insertion, else false //===========================================================// void LinkList::pushFront(int value) { //Create LNode LNode *newItem; newItem = new LNode; if (newItem == NULL) { throw LLExceptions(UNKOWN_ERROR); } //If headPtr is NULL the start of the list if (headPtr_ == NULL) { newItem->data_ = value; newItem->next_ = NULL; size_++; headPtr_ = newItem; } //else more one or more in the list. else { newItem->data_ = value; newItem->next_ = headPtr_; headPtr_ = newItem; size_++; } } //===========================================================// // removeFront: Removes the node at the front of the list // Receives: Nothing // Returns: True if successful deletion, else false //===========================================================// void LinkList::removeFront() { LNode *oldHead = headPtr_; //If the LinkList is empty return error message if (headPtr_ == NULL) { //cout << "The list is empty!" << endl; throw LLExceptions(EMPTY_LIST); } //Else one or more Node is in the LinkList //Advance the current headPtr headPtr_ = headPtr_->next_; delete oldHead; size_--; } //===========================================================// // pushEnd: Adds a value to the end of the list // Receives: value = the data to insert into the list // Returns: True if successful insertion, else false //===========================================================// void LinkList::pushEnd(int value) { LNode* head = headPtr_; //Create and Initialize a new node LNode *newItem = new LNode(); newItem->next_ = NULL; newItem->data_ = value; if (newItem == NULL) { throw LLExceptions(UNKOWN_ERROR); //return false; } if (head == NULL) { return pushFront(value); } while (head->next_ != NULL) { head = head->next_; } //head is now the end on the list because it is pointing to null head->next_ = newItem; size_++; //return true; } //===========================================================// // removeEnd: Removes the node at the end of the list // Receives: Nothing // Returns: True if successful deletion, else false //===========================================================// void LinkList::removeEnd() { int count = 0; LNode* head = headPtr_; LNode* tailPtr = NULL; //If the LinkList is empty return error message if (size_ == 0 && headPtr_ == NULL) { //cout << "The list is empty!" << endl; //return false; throw LLExceptions(EMPTY_LIST); } //If there is only one item in the LinkList //Remove the front! if (size_ == 1) { removeFront(); return; } while (head) { //save the second to last node address if (count == ((size_ - 1) - 1)) { tailPtr = head; } count++; head = head->next_; } //Removing the last item in the list & releasing //heap memory tailPtr->next_ = NULL; delete head; size_--; //return true; } //===========================================================// // InsertIndex: Allows the user to input a value in any index // in the current list, including adding one to the end! // Receives: // value = the data to insert into the list // index = the index where the new value will be inputed // Returns: True if successful insertion, else false //===========================================================// void LinkList::InsertIndex(int index, int value) { int counter = 0; LNode *tailPtr = NULL; LNode* head = headPtr_; //Create and initialize a new LNode LNode *newItem = new LNode(); newItem->next_ = NULL; newItem->data_ = value; //Test if heap allocation was successful if (newItem == NULL) { //return false; throw LLExceptions(UNKOWN_ERROR); } //Testing if user index is out of bounds if (index > size_ || index < 0) { //cout << "Invalid Index! " << endl; //return false; throw LLExceptions(INVALID_INDEX); } //Front insertion if (index == 0) { pushFront(value); return; } //Insertion from index ([1] - [N-1]) if (index < size_) { while (counter != index) { //Saves a pointer the [index -1] if (counter == index - 1) { tailPtr = head; } head = head->next_; counter++; } //inserts new item between [N-1] & [N] tailPtr->next_ = newItem; newItem->next_ = head; size_++; return; } //End insertion if (index == size_) { pushEnd(value); return; } //Returns False if no insertion occurs throw LLExceptions(UNKOWN_ERROR); } //===========================================================// // deleteIndex: Allows the user to delete a value in any index // in the current list // Receives: index = the index where the value will be deleted // Returns: True if successful deletion, else false //===========================================================// void LinkList::deleteIndex(int index) { LNode *tailPtr = NULL; LNode *head = headPtr_; int count = 0; //If invalid index return false if (index < 0 || index >= size_) { //cout << "Invalid index!!" << endl; //return false; throw LLExceptions(INVALID_INDEX); } //Front removal if (index == 0) { removeFront(); return; } //End removal if (index == size_-1) { removeEnd(); return; } //Stores the address before (index-1) //and after (index+1) the index while (count < index) { if (count == index-1 ) { tailPtr = head; } count++; head = head->next_; } //Freeing heap memory and adjusting LinkList tailPtr->next_ = head->next_; delete head; size_--; return; } //==== This function can be used to overload the [] operator ====// //===========================================================// // indexNodePtr: Returns the address of the node at // the given index // Receives: index = the "index" the node is located // Returns: a pointer the node at the "index" //===========================================================// LNode* LinkList::indexNodePtr(int index) { LNode *returnNode = headPtr_; //Testing for empty list if (returnNode == NULL && size_ == 0) { cout << "The list is empty!" << endl; return returnNode; } //Testing index out of bounds if (index < 0 || index >= size_) { cout << "Invalid Index!" << endl; return NULL; } //At least one item in the list //Returns the first node at index [0] if (index == 0 || size_ == 1) { return returnNode; } for (int count = 0; count < index; count++) { returnNode = returnNode->next_; } return returnNode; } //===========================================================// // nodePtrIndex: Returns the index of the node // Receives: node = pointer to a node whos index will be // returned // Returns: index of the node, else -1 if index does not exist //===========================================================// int LinkList::nodePtrIndex(LNode * node) { LNode *head = headPtr_; //Testing for empty list if (head == NULL && size_ == 0) { cout << "The list is empty!" << endl; return -1; } if (head == node) { return 0; } for (int count = 0; count < size_; count++) { if (head == node) { return count; } head = head->next_; } return -1; } //===========================================================// // swapIndex: Switches the values of two indexies // Receives: index1 = the "index" of the node to swap data // index2 = the "index" of the second node to swap // RReturns: True if successful swap, else false //===========================================================// void LinkList::swapIndex(int index1, int index2) { LNode *nodePtr1; LNode *nodePtr2; int temp; //Testing for empty list if (headPtr_ == NULL && size_ == 0) { //cout << "Empty List!" << endl; throw LLExceptions(EMPTY_LIST); } if (size_ == 1) { //cout << "Error their is only one item in the list" << endl; throw LLExceptions(ONE_ITEM); } if (index1 < 0 || index1 >= size_) { //cout << "Error the first index is invalid!" << endl; throw LLExceptions(INVALID_FIRST); } if (index2 < 0 || index2 >= size_) { //cout << "Error the second index is invalid!" << endl; throw LLExceptions(INVALID_SECOND); } //Switching the values of each node at the given idexies nodePtr1 = indexNodePtr(index1); nodePtr2 = indexNodePtr(index2); temp = nodePtr1->data_; nodePtr1->data_ = nodePtr2->data_; nodePtr2->data_ = temp; } //===========================================================// // copyOverIndex: Copies a value at the given "index" // Receives: index = the "index" of the node // value = the data to copy over // Returns: True if successful swap, else false //===========================================================// void LinkList::copyOverIndex(int index, int value) { LNode *head = headPtr_; head = indexNodePtr(index); if (head == NULL && size_ == 0) { throw LLExceptions(EMPTY_LIST); } head->data_ = value; } //===========================================================// // remCase: This function removes value off the list depending // on what function is passed to it // Receives: func = A function that takes in a value and // returns a boolean depending on the case. // Returns: Nothing //===========================================================// void LinkList::remCase(bool(*func) (int)) { LNode *head = headPtr_; int currIndex = 0; //Testing for an empty list if (head == NULL && size_ == 0) { //cout << "List is currently Empty! " << endl; throw LLExceptions(EMPTY_LIST); } cout << "===== Removing Numbers =====" << endl; //Displays the data being deleted // at the current "index" while (currIndex != size_-1) { //Deletes Node at current index if ((*func) (head->data_)) //<=== function goes here! { cout << (head)->data_ << " Deleted! " << endl; deleteIndex(currIndex); currIndex--; } currIndex++; head = indexNodePtr(currIndex); } } //===========================================================// // isEven: Dtermines wether a value is even or not // Receives: value = the value to test // Returns: True if even, else false //===========================================================// bool isEven(int value) { if ((value) % 2 == 0) { return true; } return false; } //===========================================================// // isOdd: Dtermines wether a value is odd // Receives: value = the value to test // Returns: True if odd, else false //===========================================================// bool isOdd(int value) { return !isEven(value); } //===========================================================// // isPrime: Dtermines wether a value is Prime // Receives: value = the value to test // Returns: True if Prime, else false //===========================================================// bool isPrime(int value) { bool bVal = true; for (int i = 2; i <= value / 2; i++) { if (value % i == 0) { bVal = false; break; } } return bVal; } // A number is a fibonacci # if either (5*n^2+4) or (5*n^2-4) // are perfect squares or both //===========================================================// // isFibonacci: Deyytermines wether a value is a fibbonacci # // Receives: value = the value to test // Returns: True if in fibonacci sequence, else false //===========================================================// bool isFibonacci(int value) { int S1 = 5 * (pow(value, 2)) + 4; int S2 = 5 * (pow(value, 2)) - 4; int s1 = sqrt(S1); int s2 = sqrt(S2); if (value < 0) { return false; } if ((s1*s1 == S1) || (s2*s2 == S2)) { return true; } return false; } // -Find the fastest algorith that will work for a link list! // -Figure out how to //===========================================================// // sort: Sorts the link list depending on the user choice // Receives: headPtr = Pointer to the head of the list // func = a function determining the direction of // the sorting algorithm. // Returns: Nothing //===========================================================// void LinkList::sort(LNode * headPtr, bool(*func)(int, int)) { LNode *tempNode = headPtr; //base case returns when its at the end of the list if (headPtr->next_ == NULL) { return; } else { tempNode = headPtr->next_; sort(tempNode, func); } //compares head node value with each node value //swaps every time condition matches after each swap //check entire list again to make sure it is in order //if it isnt continue swaps if ((func)((tempNode->data_), (headPtr->data_))) { swapIndex(nodePtrIndex(tempNode), nodePtrIndex(headPtr)); sort(headPtr, func); return; } return; } LNode* LinkList::retHead() { return headPtr_; } bool Up(int val1, int val2) { if (val1 < val2) { return true; } return false; } bool Down(int val1, int val2) { if (val1 > val2) { return true; } return false; } //===========================================================// // Overloaded operator [] // Receives: index = the "index" of the node // Returns: A Refrence to a LNode //===========================================================// LNode& LinkList::operator[](int index) { LNode* returnNode = indexNodePtr(index); if (returnNode) { return *returnNode; } else { cout << "Error index invalid!" << endl; return *returnNode; } } //===========================================================// // reverseList: Reverses the order of the entire linkList // Receives: Nothing // Returns: true if successful reversal of list, else false //===========================================================// void LinkList::reverseList() { int currIndex = size_ - 1; LNode * node = NULL; //the last memeber of the linklist will be the new head! LNode *newHead = indexNodePtr(currIndex); for (int x = 0; x < size_ ; x++) { //When iteration with full list is done set //the new last node's next(NULL) //and set the new head pinter! if (x == size_ - 1) { //set new end of list node = indexNodePtr(currIndex); node->next_ = NULL; //set new head pointer headPtr_ = newHead; return; } node = indexNodePtr(currIndex); //if the current node is not null set its next //next pointer to its previous in the list if (node) { node->next_ = indexNodePtr(currIndex - 1); } currIndex--; } //if loop exits error has occured //cout << "Error could not reverse list!" << endl; throw LLExceptions(UNKOWN_ERROR); } //===========================================================// // Overloaded operator << // Receives: os = putstream // node = node data you want to display // Returns: A Refrence to a LNode //===========================================================// ostream& operator<<(ostream& os, const LNode& node) { os << node.data_; return os; } //===========================================================// // Overloaded operator = // Receives: value = the desired value to assigned the member // Returns: Nothing //===========================================================// void LNode::operator=(int value) { if (this != NULL) { data_ = value; } } //===========================================================// // LLQuery: Handles exceptions when thrown // Receives: error_message - an exception error // Returns: Nothing //===========================================================// void LLQuery(LLExceptions & error_message) { switch (error_message.GetExVal()) { case INVALID_INDEX: cout << "INVALID_INDEX has been thrown" << endl << endl; break; case EMPTY_LIST: cout << "EMPTY_LIST has been thrown" << endl << endl; break; case INVALID_FIRST: cout << "INVALID_FIRST has been thrown" << endl << endl; break; case INVALID_SECOND: cout << "INVALID_SECOND has been thrown" << endl << endl; break; case ONE_ITEM: cout << "ONE_ITEM error has been thrown" << endl << endl; break; case UNKOWN_ERROR: cout << "UNKOWN_ERROR has been thrown" << endl << endl; break; } } //===========================================================// // Menu: Disdplays a Menu for every function available in // LinkList class // Receives: A refereance to a list // Returns: None //===========================================================// void Menu(LinkList* List) { int size = 0; bool menuActive = true; bool caseBool = true; bool(*func)(int, int) = NULL; bool(*remFunc)(int) = NULL; int userChoice = -1; int index1 = 0; int index2 = 0; int value = 0; while (menuActive) { cout << "1: pushFront " << endl << "2: pushEnd " << endl << "3: removeFront " << endl << "4: removeEnd " << endl << "5: InsertIndex " << endl << "6: copyOverIndex " << endl << "7: displayList " << endl << "8: listSize " << endl << "9: deleteIndex " << endl << "10: reverseList " << endl << "11: sort" << endl << "12 Remove Case" << endl << "-1: EXIT! " << endl << endl << endl << "Choice: "; cin >> userChoice; while (cin.fail()) { cout << "Error please enter a valid integer! " << endl << endl; cin.clear(); cin.ignore(256, '\n'); cout << "Choice: "; cin >> userChoice; } cout << endl; switch (userChoice) { case -1: menuActive = false; break; case 1: try { cout << "Please enter a value to be pushed in the front of the LinkList! " << endl; cin >> value; List->pushFront(value); cout << endl << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 2: try { cout << "Please enter a value to be pushed in the end of the LinkList! " << endl; cin >> value; List->pushEnd(value); cout << endl << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 3: try { List->removeFront(); cout << "The first node in the link list has been removed!" << endl << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 4: try { List->removeEnd(); cout << "The last node in the link list has been removed!" << endl << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 5: try { cout << "Please enter an value and an index to place it into the list!" << endl; cout << "Value: "; cin >> value; cout << endl; cout << "index: "; cin >> index1; cout << endl << endl; List->InsertIndex(index1, value); } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 6: try { cout << "Please enter an value and an index to replace in the list!" << endl; cout << "Value: "; cin >> value; cout << endl; cout << "index: "; cin >> index1; cout << endl << endl; List->copyOverIndex(index1, value); } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 7: try { List->displayList(); cout << endl << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 8: try { size = List->listSize(); cout << "The LinkList size is " << size << endl << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 9: try { cout << "Please enter index to delete its value from the list!" << endl; cout << "index: "; cin >> index1; cout << endl << endl; List->deleteIndex(index1); } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 10: try { List->reverseList(); cout << "The LinkList order has been reversed!" << endl << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 11: try { while (caseBool) { cout << "Choose (0) for upwards and (1) for downwards! " << endl; cout << "Choice: "; cin >> value; while (cin.fail()) { cout << "Error please enter a valid integer! " << endl << endl; cin.clear(); cin.ignore(256, '\n'); cout << "Choice: "; cin >> value; } if (value == 0) { func = Up; caseBool = false; } else if (value == 1) { func = Down; caseBool = false; } else { cout << "Error please enter a valid integer! " << endl << endl; } } caseBool = true; List->sort(List->retHead(), func); } catch (LLExceptions & error_message) { LLQuery(error_message); } break; case 12: try { while (caseBool) { cout << "Choose what values you would like to remove " << endl << " (0) Even (1) Odd (2) More Options" << endl; cout << "Choice: "; cin >> value; while (cin.fail()) { cout << "Error please enter a valid integer! " << endl << endl; cin.clear(); cin.ignore(256, '\n'); cout << "Choice: "; cin >> value; } if (value == 0) { remFunc = isEven; caseBool = false; } else if (value == 1) { remFunc = isOdd; caseBool = false; } else if (value == 2) { cout << "(0) Prime (1) Fibbanacci " << endl; cout << "Choice: "; cin >> value; while (cin.fail()) { cout << "Error please enter a valid integer! " << endl << endl; cin.clear(); cin.ignore(256, '\n'); cout << "Choice: "; cin >> value; } if (value == 0) { remFunc = isPrime; caseBool = false; } else if (value == 1) { remFunc = isFibonacci; caseBool = false; } } else { cout << "Error please enter a valid integer! " << endl << endl; } } caseBool = true; List->remCase(remFunc); cout << endl; } catch (LLExceptions & error_message) { LLQuery(error_message); } break; default: cout << "Error please enter a valid integer! " << endl; break; } } } <file_sep># LinkListProject > A linklist project I created to understand the inner workings of the datastructure # What I Learned > Correclty implamenting a working link list w/ useful functions > Advantages/Disadvantages of linklists > Time Complexities of each function > Debugging! It was a mess but now I learned the hard way. # Future Ideas > Instead of traversing through link list to find its "index"; create a unordered map > and pair the nodes memory address with the correct "index". > Diffucult to implament because any modification to the link list would require updating > all "indexies". > Optimizing sorting algorithm used, slow. > Add template functionality > Fixing code (removing unecessary code, fixing hacky code, removing redundent code, space/time complexity optimization) <file_sep>#include "LinkList.h" #include <iostream> using namespace std; void Menu(LinkList* List); int main() { int size = 0; LinkList List; LinkList *listPtr = &List; //===========================================================// /*--------------------Debugging Tests!!----------------------*/ //===========================================================// //List.displayList(); List[0] = 55; // List is empty so invalid index List.pushFront(5); List[0] = 55; List.pushFront(4); List.pushFront(3); List.pushFront(2); List.pushFront(1); List.displayList(); cout << List[2] << endl; List.displayList(); List.deleteIndex(1); List.displayList(); List.copyOverIndex(1, 100); List.displayList(); size = List.listSize(); cout << "List size is "<< size << endl; List.displayList(); List.swapIndex(1,2); List.displayList(); List.pushFront(2); List.pushEnd(65); List.pushEnd(23); List.pushEnd(9); List.pushEnd(13); List.pushEnd(45689); List.pushEnd(3214); List.displayList(); List.remCase(isFibonacci); List.displayList(); //first arguement head pointer, second arguement sort up or down List.sort(List.retHead(), Up); List.displayList(); List.sort(List.retHead(), Down); List.displayList(); List.reverseList(); List.displayList(); //Create a looping menu, allow them to choose what function to use on the link list //display proper output! Menu(listPtr); return 0; } <file_sep>#pragma once #include <iostream> using namespace std; enum LLError { INVALID_INDEX, EMPTY_LIST, UNKOWN_ERROR, INVALID_FIRST, INVALID_SECOND, ONE_ITEM }; class LLExceptions { public: LLExceptions(LLError exVal) :m_exVal(exVal){} LLError GetExVal()const{ return m_exVal; } private: LLError m_exVal; }; struct LNode { int data_; LNode *next_; void operator=(int value); }; class LinkList { public: //ctor LinkList():headPtr_(NULL),size_(0){} LinkList(LinkList &list); ~LinkList(); //Functions int listSize(); // void displayList();// void pushFront(int value);// void pushEnd(int value);// void InsertIndex(int index, int value);// void removeFront();// void removeEnd();// void deleteIndex(int index);// void copyOverIndex(int index, int value);// void swapIndex(int index1, int index2); void remCase(bool(*func) (int)); void reverseList(); LNode& operator[] (int value); void sort(LNode *headPtr, bool(*func) (int, int)); LNode* retHead(); private: LNode* indexNodePtr(int index); int nodePtrIndex(LNode * node); LNode *headPtr_; int size_; }; //Overloading the << operator ostream& operator<< (ostream& os, const LNode& node); //remCase passing functions bool isEven(int value); bool isOdd(int value); bool isPrime(int value); bool isFibonacci(int value); //sort passing functions bool Up(int val1, int val2); bool Down(int val1, int val2); void LLQuery(LLExceptions &error_message);
25a12f2965db37724486f56bf6482b0c0f47cf72
[ "Markdown", "C++" ]
4
C++
EstebanMontelongo/LinkListProject
a86d45292d17386522e06a0a2ca8b9bc71befc15
e712dd61ede448563a391d981ad3926eecfb36d9
refs/heads/master
<file_sep>import yargs from "yargs"; import {connectEBB, startServer} from "./server"; export function cli(argv: string[]): void { const args = yargs.strict() .option("port", { alias: "p", default: Number(process.env.PORT || 9080), describe: "TCP port on which to listen", type: "number" }) .option("device", { alias: "d", describe: "device to connect to", type: "string" }) .option("enable-cors", { describe: "enable cross-origin resource sharing (CORS)", type: "boolean" }) .option("max-payload-size", { describe: "maximum payload size to accept", default: "200 mb", type: "string" }) .option("firmware-version", { describe: "print the device's firmware version and exit", type: "boolean" }) .parse(argv); if (args["firmware-version"]) { connectEBB(args.device).then(async (ebb) => { if (!ebb) { console.error(`No EBB connected`); return process.exit(1); } const fwv = await ebb.firmwareVersion(); console.log(fwv); await ebb.close(); }); } else { startServer(args.port, args.device, args["enable-cors"], args["max-payload-size"]); } } <file_sep>import {EBB} from "../ebb"; import SerialPort from "serialport"; import MockBinding from "@serialport/binding-mock"; (() => { let oldBinding: any; beforeAll(() => { oldBinding = SerialPort.Binding; SerialPort.Binding = MockBinding; }); afterAll(() => { SerialPort.Binding = oldBinding; MockBinding.reset(); }); })(); describe("EBB.list", () => { afterEach(() => { MockBinding.reset(); }) it("is empty when no serial ports are available", async () => { expect(await EBB.list()).toEqual([]) }) it("doesn't return a port that doesn't look like an EBB", async () => { MockBinding.createPort('/dev/nonebb'); expect(await EBB.list()).toEqual([]) }) it("returns a port that does look like an EBB", async () => { MockBinding.createPort('/dev/ebb', { manufacturer: "SchmalzHaus" }); expect(await EBB.list()).toEqual(["/dev/ebb"]) }) it("handles 'SchmalzHaus LLC'", async () => { MockBinding.createPort('/dev/ebb', { manufacturer: "SchmalzHaus LLC" }); expect(await EBB.list()).toEqual(["/dev/ebb"]) }) it("handles no manufacturer but vendor id / product id", async () => { MockBinding.createPort('/dev/ebb', { vendorId: "04D8", productId: "FD92" }); expect(await EBB.list()).toEqual(["/dev/ebb"]) }) }) describe("EBB", () => { afterEach(() => { MockBinding.reset(); }) type TestPort = SerialPort & { binding: SerialPort.BaseBinding & { recording: Buffer; emitData: (data: Buffer) => void; }; }; async function openTestPort(path = '/dev/ebb'): Promise<TestPort> { MockBinding.createPort(path, {record: true}); const port = new SerialPort(path); await new Promise(resolve => port.on('open', resolve)); return port as any; } it("firmware version", async () => { const port = await openTestPort(); const ebb = new EBB(port); port.binding.emitData(Buffer.from('aoeu\r\n')); expect(await ebb.firmwareVersion()).toEqual('aoeu'); expect(port.binding.recording).toEqual(Buffer.from("V\r")); }) it("enable motors", async () => { const port = await openTestPort(); const ebb = new EBB(port); port.binding.emitData(Buffer.from('OK\r\n')); await ebb.enableMotors(2); expect(port.binding.recording).toEqual(Buffer.from("EM,2,2\r")); }) }) <file_sep>declare module '*.svg'; declare module 'wake-lock'; declare module '@serialport/binding-mock';
d808f9c47ad02dd0628c348e64717d55464d4474
[ "TypeScript" ]
3
TypeScript
Deimos1966/saxi
b6cc3ff2e18ae4581ad6f8402f26384302e8a666
8047c714d631d93e4e7828ed65de3cfde0068240
refs/heads/master
<repo_name>prithviraju1369/logger<file_sep>/app.js // app.js var express = require('express'); var app = express(); var server = require('http').createServer(app); var io = require('socket.io')(server); app.use(express.json()); app.use(express.static(__dirname + '/node_modules')); app.get('/', function(req, res,next) { res.sendFile(__dirname + '/index.html'); }); app.post('/logger', function(req, res,next) { console.log(req.body); // client.emit('message', req.body); io.emit('message', JSON.stringify(req.body)); res.send({}) }); server.listen(process.env.PORT || 3000);
b9626e1537021e8aa82161835847c7cc23aad236
[ "JavaScript" ]
1
JavaScript
prithviraju1369/logger
41cb9bef46c3afc8f269808c9c704658da61cf31
f2eaa3d4aa5b83a911d5aba4cce093bc56de9e56
refs/heads/master
<file_sep>enyo.depends( "HashView.js", "HashPanels.js", "Link.js", "Link.css" ); <file_sep>/** Contains a polyfill for certain version of IE and WindowsPhone, which sets the value of window.devicePixelRatio. Due to the nature of changing zoom level and screen orientation, so long as the viewport is set to device-width, the devicePixelRatio can be calculated at a given time. In addition, an `onpixelratiochange` signal will be sent whenever the device pixel ratio is updated, which you can listen for like: {kind: "enyo.Signals", onpixelratiochange: "handlePixelRatioChange"} `enyo.dom.calcPixelRatio()` when invoked, will update window.devicePixelRatio manually if needed. This is automatically done when the device orientation changes as well as whenever the window is resized (to check for browser zoom level changes). */ enyo.dom.calcPixelRatio = function() { var ratio = window.devicePixelRatio; if(enyo.platform.ie) { window.devicePixelRatio = window.devicePixelRatio = window.screen.deviceXDPI / window.screen.logicalXDPI; } else if(enyo.platform.windowsPhone) { window.devicePixelRatio = ((window.matchMedia("(orientation: portrait)").matches ? screen.width : screen.height)/document.documentElement.clientWidth); } if(window.devicePixelRatio != ratio) { enyo.Signals.send("onpixelratiochange"); } }; //* @protected enyo.dispatcher.listen(document, "orientationchange", enyo.dom.calcPixelRatio); enyo.dispatcher.listen(document, "MSOrientationChange", enyo.dom.calcPixelRatio); enyo.dispatcher.listen(window, "resize", enyo.dom.calcPixelRatio); enyo.dom.calcPixelRatio(); <file_sep>/** Variation of <a href="#enyo.Panels">enyo.Panels</a> with built-in support for the Web History API. Each panel within acts as a separate navigation entry, allowing for back/forward nativeley without changing the current html page nor hash. */ enyo.kind({ name:"enyo.WebHistoryPanels", kind:"Panels", //* @protected draggable:false, create: function() { this.inherited(arguments); this.stateSignal = this.createComponent({kind:"Signals", onpopstate:"historyPopState"}); window.history.pushState({index:this.index}, ""); }, historyPopState: function(inSender, inEvent) { if(inEvent && inEvent.state && inEvent.state.index!==undefined) { this.setIndex(inEvent.state.index, true); } }, //* @public /** Sets the index to a new value, with an optional `skipHistoryState` parameter which, when true, will skip adding the panel to the web history. */ setIndex: function(newIndex, skipHistoryState) { if(!skipHistoryState) { if(this.index!=newIndex) { window.history.pushState({index:newIndex}, ""); } } this.inherited(arguments); }, //* Moves back in web history states previous: function() { window.history.back(); }, //* Moves forward in web history states next: function() { window.history.forward(); } }); <file_sep>/** A wrapper component that provides animated fading functionality. Works on all browsers that Enyo2 supports and includes a static function, `enyo.Fader.attachTo()` that attaches a fader functionality to a control itself. */ enyo.kind({ name: "enyo.Fader", events: { /** Event triggered after a fade effect finishes Event data returned includes _"opacity"_ (number 0-1), _"fadedIn"_ a boolean of whether the effect faded in completely, and _"fadedOut"_ a boolean of whether the effect faded out completely. */ onFaded:"" }, published: { //* Current opacity value opacity:1 }, //* Minimum opacity level the Fader can fade to. minOpacity: 0, //* Maximum opacity level the Fader can fade to. maxOpacity: 1, //* Default time of a fade (in milliseconds). defaultFadeLength: 500, //* @protected handlers: { ontransitionend: "transitionComplete", onwebkitTransitionEnd: "transitionComplete" }, create: function() { this.inherited(arguments); this.useFallback = ((enyo.platform.ie && enyo.platform.ie<10) || window.opera); this.opacityChanged(); }, opacityChanged: function() { this.opacity = Math.max(Math.min(this.opacity, this.maxOpacity), this.minOpacity); this.applyStyle("opacity", this.opacity); this.applyStyle("filter", "progid:DXImageTransform.Microsoft.Alpha(Opacity=" + (this.opacity*100) + ")"); this.applyStyle("filter", "alpha(opacity=" + (this.opacity*100) + ")"); }, //* @public //* Fades in to the maximum opacity in a given length of time (defaults to `defaultFadeLength`). fadeIn: function(length) { this.fadeTo(this.maxOpacity, length); }, //* Fades out to the minimum opacity in a given length of time (defaults to `defaultFadeLength`). fadeOut: function(length) { this.fadeTo(this.minOpacity, length); }, /** Toggles fading in or out depending if opacity is closer to the minimum or maximum values, going to the opposite, in a given length of time (defaults to `defaultFadeLength`). */ fadeToggle: function(length) { if(this.opacity >= (this.maxOpacity/2)) { this.fadeOut(length); } else { this.fadeIn(length); } }, //* Fades to a specified opacity value, in a given length of time (defaults to `defaultFadeLength`). fadeTo: function(opacity, length) { opacity = Math.max(Math.min(opacity, this.maxOpacity), this.minOpacity); if(opacity == this.opacity) { return; } length = length || this.defaultFadeLength; if(this.useFallback) { var stepLength = 20; //modify this to tune fade smoothing on IE8/IE9/Opera var numSteps = length/stepLength; var step = (opacity - this.opacity) / numSteps; var decreasing = (step < 0) var self = this; if(this.fadeJob) { clearInterval(this.fadeJob); } this.fadeJob = setInterval(function() { if((decreasing && self.opacity > opacity) || (!decreasing && self.opacity < opacity)) { self.setOpacity(self.opacity + step); } else { clearInterval(self.fadeJob); self.fadeJob = undefined; self.setOpacity(opacity); self.doFaded({ opacity: self.opacity, fadedIn: (self.opacity==self.maxOpacity), fadedOut: (self.opacity==self.minOpacity) }); } }, stepLength); } else { this.applyStyle(enyo.dom.transition, "opacity " + (length/1000) + "s ease-in-out"); //re-apply current opacity so the transition will apply to changes from this state this.setOpacity(this.opacity); this.setOpacity(opacity); } }, //* @protected transitionComplete: function(inSender, inEvent) { this.applyStyle(enyo.dom.transition, null); this.doFaded({ opacity: this.opacity, fadedIn: (this.opacity==this.maxOpacity), fadedOut: (this.opacity==this.minOpacity) }); return true; }, //* @public statics: { /** Attaches a fader to any existing _contol_. _Opacity_ value is an initial opacity for the control (defaults to _1_) _onFaded_ is an optional function to be executed when a fade event finishes, forwarding the event data as the parameter to the function. */ attachTo: function(control, opacity, onFaded) { opacity = (opacity==undefined) ? 1 : opacity; control.fader = new enyo.Fader(); control.fader.applyStyle = enyo.bind(control, control.applyStyle); var renderedFunction = enyo.bind(control, control.rendered); control.rendered = function() { var node = control.hasNode() if(node) { enyo.dispatcher.listen(node, "transitionend", enyo.bind(control.fader, control.fader.transitionComplete)); enyo.dispatcher.listen(node, "webkitTransitionEnd", enyo.bind(control.fader, control.fader.transitionComplete)); } renderedFunction(); } control.fader.doFaded = function(data) { if(control.fader.onFaded) { control.fader.onFaded(data); } } if(onFaded) { control.fader.onFaded = onFaded; } control.fader.setOpacity(opacity); } } }); <file_sep>/** A simple HTML5 audio wrapper with event bubbling, streamlined ogg/wav/mp3 source setting, relayed javascript play/pause/stop API, and fade-in and fade-out functions. */ enyo.kind({ name: "enyo.Audio", tag: "audio", published: { //* URL for an mp3 audio source mp3:"", //* URL for an ogg audio source ogg:"", //* URL for a wav audio source wav:"" }, /** A number of events are here commented out as there's a _lot_ of HTML5 audio events. Uncomment any ones you want to use. */ attributes: { //onabort: enyo.bubbler, //oncanplay: enyo.bubbler, //oncanplaythrough: enyo.bubbler, //ondurationchange: enyo.bubbler, //onemptied: enyo.bubbler, //onended: enyo.bubbler, //onerror: enyo.bubbler, //onloadeddata: enyo.bubbler, //onloadedmetadata: enyo.bubbler, //onloadstart: enyo.bubbler, //onpause: enyo.bubbler, //onplay: enyo.bubbler, //onplaying: enyo.bubbler, //onprogress: enyo.bubbler, //onratechange: enyo.bubbler, //onseeked: enyo.bubbler, //onseeking: enyo.bubbler, //onstalled: enyo.bubbler, //onsuspend: enyo.bubbler, //ontimeupdate: enyo.bubbler, //onvolumechange: enyo.bubbler, //onwaiting: enyo.bubbler }, //* Default audio fade time (in milliseconds) for the fadeIn/fadeOut functions defaultFadeTime:200, //* @protected mimes: { mp3:"audio/mpeg", ogg:"audio/ogg", wav:"audio/wav" }, create: function() { this.inherited(arguments); this.mp3Changed(); this.oggChanged(); this.wavChanged(); }, mp3Changed: function() { this.updateSource("mp3"); }, oggChanged: function() { this.updateSource("ogg"); }, wavChanged: function() { this.updateSource("wav"); }, updateSource: function(ext) { if(this[ext] && this[ext]!="") { this.setSource(ext, this[ext]); } else { this.removeSource(ext); } var node = this.hasNode(); if(node) { node.load(); } }, setSource: function(ext, url) { if(this.$[ext]) { if(this.$[ext].src != url) { this.$[ext].setSrc(url); } } else { this.createComponent({name:ext, tag:"source", src:url, attributes:{type:this.mimes[ext]}}); } }, removeSource: function(ext) { if(this.$[ext]) { this.$[ext].destroy(); } }, //* @public //* Plays the audio (so long as a source audio is specified that works on the given browser) play: function() { var node = this.hasNode(); if(node) { if (!node.paused) { // we want restart the audio file to the beginning but 0 doesn't work on // iOS so workarund by seting it to close to 0 node.currentTime = 0.01; } node.play(); } }, //* Pauses the audio pause: function() { var node = this.hasNode(); if(node) { node.pause(); } }, //* Stops the audio stop: function() { var node = this.hasNode(); if(node) { node.stop(); } }, /** Fades the audio in, for a given length of time (in milliseconds). If no time is specified, `defaultFadeTime` is used. */ fadeIn: function(length) { length = length || this.defaultFadeTime || 200; var node = this.hasNode(); var volume = 0; if(node) { node.volume = volume; node.play(); var fadeInJob = this.fadeInJob = setInterval(function() { if(volume < 1) { volume += 0.05; node.volume = volume.toFixed(2); } else { clearInterval(fadeInJob); } }, (length/20)); } }, //* Cancels any in-progress `fadeIn()` effects, resetting the volume to 100% cancelFadeIn: function() { clearInterval(this.fadeInJob); node.volume = 1; }, /** Fades the audio out, for a given length of time (in milliseconds). Can specify the `fadeOut()` effect mode to fade out to a `stop()` with _"stop"_ or to fade out to a `pause()` with _"pause"_; If no time is specified, `defaultFadeTime` is used. If no mode is specified, _"stop"_ is used. */ fadeOut: function(length, mode) { length = length || 200; mode = mode || "stop"; var node = this.hasNode(); var volume = 1; if(node) { node.volume = volume; var fadeOutJob = this.fadeOutJob = setInterval(function() { if(volume > 0) { volume -= 0.05; node.volume = volume.toFixed(2); } else { clearInterval(fadeOutJob); node[mode](); node.volume = 1; } }, (length/20)); } }, //* Cancels any in-progress `fadeOut()` effects, resetting the volume to 100% cancelFadeOut: function() { clearInterval(this.fadeOutJob); node.volume = 1; } }); <file_sep>enyo.depends( "VerticalSlider.js", "VerticalSlider.css" ); <file_sep>/** The default panel kind for <a href="#enyo.HashPanels">enyo.HashPanels</a>. Each HashView corresponds to a website URL hash, to give each one a hard URL for the panel contents. It also allows for a custom page title as well as lazy loading of content, so the content gets loaded when the user navigates to the page, rather than all pages loading at once. */ enyo.kind({ name: "enyo.HashView", //* Page name. Will end up as the hash of the URL (without the "#") page: undefined, //* Page title that gets set to `document.title` when the page is navigated to title: undefined, //* Whether or not to lazy load the child components of the HashPage lazy: false, events: { /** Fired after the child components have been created and rendered lazily via the `load()` or `asyncLoad()` functions. */ onLazyLoad: "" }, //* A flag variable that will turn to true while a lazy load is in-progress loadInProgress: false, /** A flag variable that will turn to true once lazy loading is completed (set to _true_ by default if _"lazy"_ is set to _false_) */ loaded: false, //* @protected style: "width:100%; height:100%;", create: function() { this.loaded = !this.lazy; if(this.lazy) { this.lazyComponents = this.components; this.components = []; } this.inherited(arguments); if(!this.page || this.page.length==0) { this.page = this.id; } }, //* @public //* Creates and renders the lazy children components. Will re-render if already loaded. load: function() { this.loadInProgress = true; if(this.lazyComponents) { this.components = this.lazyComponents; this.lazyComponents = undefined; this.createClientComponents(this.components); } this.render(); this.loadInProgress = false; this.loaded = true; this.doLazyLoad(); }, //* Calls the `load()` function asynchronously. asyncLoad: function() { this.loadInProgress = true; enyo.asyncMethod(this, this.load); } }); <file_sep>enyo.depends( "Fader.js" ); <file_sep>enyo.depends( "View.js", "ViewStack.js", "AppStack.js" ); <file_sep>enyo.depends( "WebHistoryPanels.js" ); <file_sep>enyo.depends( "Socket.js" ); <file_sep>enyo.depends( "Color.js" );<file_sep>/** Simple lightweight wrapper to lazy-load contained components, synchonously or asynchronously. */ enyo.kind({ name:"enyo.Lazy", events: { /** Fired after the child components have been created and rendered lazily via the `load()` or `asyncLoad()` functions. */ onLazyLoad: "" }, //* A flag variable that will turn to true while a lazy load is in-progress loadInProgress: false, //* A flag variable that will turn to true once loading is completed loaded: false, //* @protected create: function() { this.lazy = this.components; this.components = []; this.inherited(arguments); }, //* @public //* Creates and renders the lazy children components. Will re-render if already loaded. load: function() { this.loadInProgress = true; if(this.lazy) { this.components = this.lazy; this.lazy = undefined; this.createClientComponents(this.components); } this.render(); this.loadInProgress = false; this.loaded = true; this.doLazyLoad(); }, //* Calls the `load()` function asynchronously. asyncLoad: function() { this.loadInProgress = true; enyo.asyncMethod(this, this.load); } });<file_sep>/** A special kind of <a href="#enyo.ViewStack">enyo.ViewStack</a> designed to only be used once per application. Access to this object instance will bound to enyo.stack for global manipulation of the stack. A handy idea is to have your root application kind be a subkind of enyo.AppStack. */ enyo.kind({ name:"enyo.AppStack", kind:"enyo.ViewStack", //* @protected create: function() { enyo.stack = this; this.inherited(arguments); } }); <file_sep>enyo.depends( "Lightbox.js", "Lightbox.css", "ImageLightbox.js" ); <file_sep>enyo.depends( "Lazy.js" );
8bd3ca8a9f2f481a9515a5138e259084209a9df2
[ "JavaScript" ]
16
JavaScript
kshraddha1290/enyo-2-components
25a249b54e3d391e42941878e2f1ad53cd62d474
117281b6963121ec2b54b5711c355173e30fed39
refs/heads/main
<file_sep>var money=0 var income=1 function startmining() { money=money+income document.getElementById("moneyequal").innerHTML = "Money You Have "+money }
e928bf99a88b6dc54d5489166c29c281cfd6eba4
[ "JavaScript" ]
1
JavaScript
TemiCodes/OreToMoney
90db666bbf0ccb8cbb4b5d9da9e54608cfe70fc3
94163bd4b3e75af9526e2bd6c920853e6725349f
refs/heads/master
<file_sep>Mobile app made with Ionic2. Like Airbnb but for food... 1. Install the the latest beta version of the Ionic CLI: ``` npm install -g ionic@beta ``` 2. Install the dependencies ``` npm install ``` 3. Start the server ``` node server ``` 4. Open another command prompt and type the following command to build the app and start it in the browser: ``` ionic serve ``` <file_sep>import {OnInit} from 'angular2/core'; import {Page, NavController, NavParams} from 'ionic-framework/ionic'; import {MealDetailsPage} from '../meal-details/meal-details'; import {MealService} from '../../services/meal-service'; @Page({ templateUrl: 'build/pages/meal-list/meal-list.html' }) export class MealListPage { static get parameters() { return [[NavController], [NavParams], [MealService]]; } constructor(nav, navParams, mealService) { this.nav = nav; this.mealService = mealService; this.selectedItem = navParams.get('item'); } ngOnInit() { this.mealService.findAll().subscribe( data => this.meals = data ); } itemTapped(event, meal) { this.nav.push(MealDetailsPage, { meal: meal }); } doRefresh(refresher) { this.mealService.findAll().subscribe((data) => { this.meals = data; refresher.complete(); }); } }<file_sep>import {App, IonicApp, Platform} from 'ionic-framework/ionic'; //import {Storage, LocalStorage} from 'ionic-framework'; import {WelcomePage} from './pages/welcome/welcome'; import {MealMapPage} from './pages/meal-map/meal-map'; import {MealListPage} from './pages/meal-list/meal-list'; import {CookListPage} from './pages/cook-list/cook-list'; import {SubmitPage} from './pages/submit/submit'; import {FavoriteListPage} from './pages/favorite-list/favorite-list'; import {MealService} from './services/meal-service'; import {CookService} from './services/cook-service'; import {GooglebooksService} from './services/googlebooks-service'; @App({ templateUrl: 'build/app.html', config: {}, providers: [MealService, CookService, GooglebooksService] }) class MyApp { static get parameters() { return [[IonicApp], [Platform]]; } constructor(app, platform) { // set up our app this.app = app; this.platform = platform; this.initializeApp(); // set our app's pages this.pages = [ {title: 'Welcome', component: WelcomePage, icon: "bookmark"}, {title: 'Map', component: MealMapPage, icon: "pin"}, {title: 'Books', component: MealListPage, icon: "book"}, {title: 'Favorites', component: FavoriteListPage, icon: "star"}, {title: 'Submit a book', component: SubmitPage, icon: "arrow-dropup-circle"} ]; //TODO /* this.local = new Storage(LocalStorage); if (!this.local.get('firstLaunch')) { this.rootPage = WelcomePage; } else { this.local.set('firstLaunch', false); this.rootPage = MealListPage; } */ this.rootPage = WelcomePage; } initializeApp() { this.platform.ready().then(() => { if (window.StatusBar) { window.StatusBar.styleDefault(); } }); } openPage(page) { // navigate to the new page if it is not the current page let nav = this.app.getComponent('nav'); nav.setRoot(page.component); } } <file_sep>var express = require('express'), bodyParser = require('body-parser'), compression = require('compression'), cors = require('cors'), meals = require('./server/meal-service'), cooks = require('./server/cook-service'), app = express(); app.set('port', process.env.PORT || 5000); app.use(cors()); app.use(bodyParser.json()); app.use(compression()); app.use('/', express.static(__dirname + '/www')); app.get('/meals', meals.findAll); app.get('/meals/favorites', meals.getFavorites); app.get('/meals/:id', meals.findById); app.post('/meals/likes', meals.like); app.post('/meals/favorites', meals.favorite); app.delete('/meals/favorites/:id', meals.unfavorite); app.get('/cooks', cooks.findAll); app.get('/cooks/:id', cooks.findById); app.listen(app.get('port'), function () { console.log('Feedme server listening on port ' + app.get('port')); });<file_sep>import {OnInit} from 'angular2/core'; import {Page, NavController, NavParams} from 'ionic-framework/ionic'; import {MealDetailsPage} from '../meal-details/meal-details'; import {MealService} from '../../services/meal-service'; @Page({ templateUrl: 'build/pages/favorite-list/favorite-list.html' }) export class FavoriteListPage { static get parameters() { return [[NavController], [NavParams], [MealService]]; } constructor(nav, navParams, mealService) { this.nav = nav; this.mealService = mealService; this.selectedItem = navParams.get('item'); } ngOnInit() { this.mealService.getFavorites().subscribe( data => this.meals = data ); } itemTapped(event, meal) { this.nav.push(MealDetailsPage, { meal: meal }); } deleteItem(event, meal) { this.mealService.unfavorite(meal).subscribe(); } }<file_sep>import {Injectable} from 'angular2/core'; import {Http} from 'angular2/http'; import {SERVER_URL} from './config'; import {Observable} from 'rxjs/Observable'; import 'rxjs/Rx'; let cooksURL = SERVER_URL + 'cooks/'; @Injectable() export class CookService { static get parameters() { return [[Http]]; } constructor (http) { this.http = http; } findAll() { return this.http.get(cooksURL) .map(res => res.json()) .catch(this.handleError); } findById(id) { return this.http.get(cooksURL + id) .map(res => res.json()) .catch(this.handleError); } handleError(error) { return Observable.throw(error.json().error || 'Server error'); } }<file_sep>import {OnInit} from 'angular2/core'; import {Page, NavController, NavParams} from 'ionic-framework/ionic'; import {CookDetailsPage} from '../cook-details/cook-details'; import {CookService} from '../../services/cook-service'; @Page({ templateUrl: 'build/pages/cook-list/cook-list.html' }) export class CookListPage { static get parameters() { return [[NavController], [NavParams], [CookService]]; } constructor(nav, navParams, cookService) { this.nav = nav; this.cookService = cookService; // If we navigated to this page, we will have an item available as a nav param this.selectedItem = navParams.get('item'); } ngOnInit() { this.cookService.findAll().subscribe( data => this.cooks = data ); } itemTapped(event, cook) { this.nav.push(CookDetailsPage, { cook: cook }); } }<file_sep>import {OnInit} from 'angular2/core'; import {Page, NavController, NavParams} from 'ionic-framework/ionic'; import {CookService} from '../../services/cook-service'; @Page({ templateUrl: 'build/pages/cook-details/cook-details.html' }) export class CookDetailsPage { static get parameters() { return [[NavController], [NavParams], [CookService]]; } constructor(nav, navParams, cookService) { this.cookService = cookService; this.cook = navParams.get('cook'); } ngOnInit() { this.cookService.findById(this.cook.id).subscribe( cook => this.cook = cook ); } } <file_sep>import {Page, NavController, NavParams, Alert, ActionSheet} from 'ionic-framework/ionic'; import {CookDetailsPage} from '../cook-details/cook-details'; import {MealMapPage} from '../meal-map/meal-map'; import {MealService} from '../../services/meal-service'; @Page({ templateUrl: 'build/pages/meal-details/meal-details.html' }) export class MealDetailsPage { static get parameters() { return [[NavController], [NavParams], [MealService]]; } constructor(nav, navParams, mealService) { this.nav = nav; this.mealService = mealService; this.meal = navParams.get('meal'); } favorite(event, meal) { this.mealService.favorite(meal).subscribe( meal => { let alert = Alert.create({ title: 'Favorites', subTitle: 'Meal added to your favorites', buttons: ['OK'] }); this.nav.present(alert); } ); } like(event, meal) { this.mealService.like(meal).subscribe( likes => { meal.likes = likes; } ); } share(event, meal) { let actionSheet = ActionSheet.create({ buttons: [ { text: 'Text', handler: () => { console.log('Text clicked'); } }, { text: 'Email', handler: () => { console.log('Email clicked'); } }, { text: 'Facebook', handler: () => { console.log('Facebook clicked'); } }, { text: 'Twitter', handler: () => { console.log('Twitter clicked'); } }, { text: 'Cancel', style: 'cancel', handler: () => { console.log('Cancel clicked'); } } ] }); this.nav.present(actionSheet); } showCook(event, cook) { this.nav.push(CookDetailsPage, { cook: cook }); } showIngredients(event) { } showMap(event) { this.nav.push(MealMapPage, { meal: this.meal }); } }<file_sep>import {OnInit} from 'angular2/core'; import {Page, NavController, NavParams} from 'ionic-framework/ionic'; import {MealDetailsPage} from '../meal-details/meal-details'; import {MealService} from '../../services/meal-service'; import mapStyle from './map-style'; @Page({ templateUrl: 'build/pages/meal-map/meal-map.html', }) export class MealMapPage { static get parameters() { return [[NavController], [NavParams], [MealService]]; } constructor(nav, navParams, mealService) { this.nav = nav; this.mealService = mealService; this.selectedMeal = navParams.get('meal'); if (this.selectedMeal) {this.direction = true;} this.map = null; this.searchQuery = ''; } ngOnInit() { this.loadMap().then(() => { if (this.selectedMeal) { //Find the meal (in this case, it is already complete) this.setDirection(this.selectedMeal); } else { this.mealService.findAll().subscribe((data) => { this.meals = data; this.setMarkers(); }); } }); } loadMap(){ return new Promise( (resolve, reject) => { let options = {timeout: 10000, enableHighAccuracy: true}; navigator.geolocation.getCurrentPosition( (position) => { this.currentPosition = position; let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); let mapOptions = { center: latLng, zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP, disableDefaultUI: true } this.map = new google.maps.Map(document.getElementById("map"), mapOptions); this.map.set('styles', mapStyle); return resolve(); }, (error) => { console.log(error); return reject(); }, options ); }); } setMarkers() { if (this.selectedMeal) { this.addMarker(selectedMeal); } this.meals.forEach((meal) => { this.addMarker(meal); }); } addMarker(meal){ if (!meal.coords) { return; } let latLng = new google.maps.LatLng(meal.coords.lat, meal.coords.long); let marker = new google.maps.Marker({ map: this.map, animation: google.maps.Animation.DROP, position: latLng, icon: 'images/book-icon-map.png' }); let content = `<p (click)="showMealDetails()">${meal.title}</p><img src="${meal.thumbnail}" height="64" width="64">`; this.addInfoWindow(marker, content, meal); } addInfoWindow(marker, content, meal){ let infoWindow = new google.maps.InfoWindow({ content: content }); google.maps.event.addListener(marker, 'click', function(){ infoWindow.open(this.map, marker); this.tappedMeal = meal; }); } setDirection(meal) { if (!meal.coords) { return; } let directionsDisplay = new google.maps.DirectionsRenderer({ map: this.map }); let origin = new google.maps.LatLng(this.currentPosition.coords.latitude, this.currentPosition.coords.longitude); let destination = new google.maps.LatLng(meal.coords.lat, meal.coords.long); // Set destination, origin and travel mode. let request = { destination: destination, origin: origin, travelMode: google.maps.TravelMode.WALKING }; // Pass the directions request to the directions service. let directionsService = new google.maps.DirectionsService(); directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { // Display the route on the map. directionsDisplay.setDirections(response); } }); } itemTapped(event, meal) { this.nav.push(MealDetailsPage, { meal: meal || this.tappedMeal }); } getItems(searchBar) { } doRefresh(refresher) { this.mealService.findAll().subscribe((data) => { this.meals = data; refresher.complete(); }); } }<file_sep>import {Page, NavController} from 'ionic-framework/ionic'; import {MealService} from '../../services/meal-service'; import {GooglebooksService} from '../../services/googlebooks-service'; import {BarcodeScanner} from 'ionic-native'; @Page({ templateUrl: 'build/pages/submit/submit.html' }) export class SubmitPage { static get parameters() { return [[NavController], [MealService], [GooglebooksService]]; } constructor(nav, mealService, googlebooksService) { this.nav = nav; this.mealService = mealService; this.googlebooksService = googlebooksService; this.book = {}; } scanBarcode() { BarcodeScanner.scan().then((barcodeData) => { console.log("We got a barcode\n" + "Result: " + result.text + "\n" + "Format: " + result.format + "\n" + "Cancelled: " + result.cancelled); }, (err) => { console.log('ERROR WHEN SCANING BARCODE', err); }); } getBookInfo() { //TODO Activate loading animation this.googlebooksService.getBookInfoFromISBN(this.book.isbn).subscribe( data => { if (data) { this.book = { isbn: this.book.isbn, title: data.volumeInfo.title, authors: data.volumeInfo.authors, publisher: data.volumeInfo.publisher, publishedDate: data.volumeInfo.publishedDate, description: data.volumeInfo.description, categories: data.volumeInfo.categories, pageCount: data.volumeInfo.pageCount, smallDescription: data.searchInfo.textSnippet, averageRating: data.volumeInfo.averageRating, language: data.volumeInfo.language, thumbnail: data.volumeInfo.imageLinks.thumbnail, country: data.saleInfo.country } } else { this.error = 'Book not found'; console.log('BOOK NOT FOUND'); setTimeout(() => {this.error = null}, 3000); } //TODO Remove loading animation } ); } autoSetBookCoords() { navigator.geolocation.getCurrentPosition( (position) => { this.book.coords = [position.coords.latitude, position.coords.longitude]; } ); } setBookCoords() { } submit() { mealService.submitBook(this.book).subscribe( data => this.nav.pop() ).catch( err => console.log('ERROR WHEN SUBMITING ITEM', err)//TODO handle error creation ); } }<file_sep>exports.data = [ { title: "Caillou promène son chien", smallDescription: "La grand-mère de Caillou l'invite à promener le chien Alfred. Celui-ci, laisse en mains, est tout heureux. Il passe un excellent moment avec son aïeule et Alfred, bien entendu", pageCount : 10, thumbnail : "http://www.images-chapitre.com/ima3/original/865/1559865_3395684.jpg", coords: { lat: 45.498862, long: -73.623144 }, price: '$5.99', }, { title: "<NAME> et la chambre des secrets", smallDescription: "<NAME> passe l'été chez <NAME> et reçoit la visite de Dobby, un elfe de maison. Celui-ci vient l'avertir que des évènements étranges vont bientôt se produire à Poudlard et lui conseille donc vivement de ne pas y retourner", pageCount : 753, price: '$5.99', coords: { lat: 45.50489, long: -73.6244 }, thumbnail : "http://www.encyclopedie-hp.org/images/covers/couverture_cs.jpg" }, { title: "Le Seigneur des anneaux : La Communauté de l'anneau", smallDescription: "Sur la Terre du Milieu, dans la paisible Comté, vit le Hobbit <NAME>. Comme tous les Hobbits, Frodon est un bon vivant, amoureux de la terre bien cultivée et de la bonne chère. Orphelin alors qu'il n'était qu'un enfant, il s'est installé à Cul-de-Sac chez son oncle Bilbon, connu de toute la Comté pour les aventures extraordinaires qu'il a vécues étant jeune et les trésors qu'il en a tirés", pageCount : 650, coords: { lat: 45.498387, long: -73.619450 }, thumbnail : "http://idata.over-blog.com/5/96/77/93/Article-Emy/SdA-Tome1.jpg" }, { title: "Le Petit Chaperon Rouge", smallDescription: "Il était une fois une petite fille de village, la plus jolie qu'on eût su voir ; sa mère en était folle, et sa mère-grand plus folle encore. Cette bonne femme lui fit faire un petit chaperon rouge, qui lui seyait si bien que partout on l'appelait le petit Chaperon rouge", pageCount : 85, price: '$5.99', coords: { lat: 45.497966, long: -73.622432 }, thumbnail : "http://images.oxybul.com/Photo/IMG_FICHE_PRODUIT/Image/500x500/1/129245.jpg" }, ];
e577f42df9aaf3ee9cc9be7b44713b9aceb22aeb
[ "Markdown", "JavaScript" ]
12
Markdown
NazoSnare/Feedme
650a62ceae4afa5b7c054c87d9f9440023a7120e
dbf05d4ce5fe5c9202d04f8b6b52cabf2fcf18e6
refs/heads/master
<file_sep>from pyrtcdcpp import RTCConf, PeerConnection, \ processWait, init_cb_event_loop, DataChannel from pprint import pprint from threading import Thread from time import sleep, time import json import sys import argparse import numpy as np import matplotlib.pyplot as plt dc_stress_flag = False parser = argparse.ArgumentParser() parser.add_argument("--size", help="Size in kilobytes of each payload. \ Default is 32 kB.", default=32, type=int) parser.add_argument("--count", help="Number of times each payload gets sent. \ Default is 2000.", default=100, type=int) parser.add_argument("--p2p-pairs", help="Number of p2p connections to make. \ Default is 2 (4 peers).", default=2, type=int) args = parser.parse_args() def autolabel(rects, ax): """ Attach a text label above each bar displaying its height """ for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.01 * height, '%d' % int(height), ha='center', va='bottom') class graph(): speed_for_packet = [] # List of (packet size, value) speed_for_packet_concurrent = {} # Same, but under concurrent load def __init__(self): pass def add_speed(self, packet_size, speed): speed = round(speed, 2) print("Adding speed: ", speed) self.speed_for_packet.insert(0, (packet_size, speed)) print(self.speed_for_packet) def add_concurrent_speed(self, packet_size, speed): print("Adding {} and speed {}".format(packet_size, speed)) speed = round(speed, 2) try: old_speed = self.speed_for_packet_concurrent[packet_size] self.speed_for_packet_concurrent[packet_size] \ = (old_speed + speed) / 2 except KeyError: self.speed_for_packet_concurrent[packet_size] = speed def plot(self): N = len(self.speed_for_packet) fig, ax = plt.subplots() width = 0.15 ind = np.arange(N) height_1 = [speed[1] for speed in self.speed_for_packet] height_2 = [speed for speed in self.speed_for_packet_concurrent.values()] bottom_1 = [speed[0] for speed in self.speed_for_packet] rect1 = ax.bar(ind, height_1, width=width, color='y', label='Sequential test') if len(height_2) > 0: N = len(self.speed_for_packet_concurrent) ind = np.arange(N) rect2 = ax.bar(ind + width, height_2, width=width, color='r', label='Concurrent test') autolabel(rect2, ax) autolabel(rect1, ax) ax.set_ylabel('MB/s') ax.set_xlabel('Individual packet size (in KBs)') ax.set_xticks(ind) ax.set_xticklabels([speed[0] for speed in self.speed_for_packet]) ax.legend() fig.tight_layout() plt.savefig('graph.png') print("Tests done! Graph is saved to graph.png") print("Plotting graph...") plt.show() def handshake_peers(evt_loop, pkt_size, graph_obj, concurrent=False): pc1 = Peer1(evt_loop) pc2 = Peer2(evt_loop) pc1.concurrent = concurrent pc2.pkt_size = pkt_size pc1.CreateDataChannel("test", evt_loop, None, DataChannel.DATA_CHANNEL_RELIABLE, 3000000) pc2.graph_obj = graph_obj pc1.graph_obj = graph_obj pc1.ParseOffer('') # To make offer have ice candidates pc2.ParseOffer('') offer = pc1.GenerateOffer() if offer is not None: pc2.ParseOffer(offer) else: return answer = pc2.GenerateAnswer() if answer is not None: pc1.ParseOffer(answer) global pkt_size pkt_size = None def stress(dc, pc_obj): i = 1 count = 0 global running max_count = args.count byte_count = 0 if pc_obj.pkt_size is None: j = args.size # kB else: j = pc_obj.pkt_size i = j * 1024 print("===Testing fixed payloads of", j, "kB", max_count, "times===") time_start = time() while (count < max_count): count += 1 dc.SendString('A' * i) time_end = time() total_data = (count * j) / 1024 # in MB total_time = time_end - time_start last_payload = {'t': total_time, 'd': total_data, 'jj': j} dc.SendString('EOL' + json.dumps(last_payload)) class Peer1(PeerConnection): def onCandidate(self, ice): # print("Python peer1 got candidates: ", ice['candidate']) pass # We don't want trickle ICE now def onMessage(self, msg): # print("\n[PC1]MESSAGE: " + msg + "\n") if (msg[:3] == 'EOL'): payload = json.loads(msg[3:]) total_time = payload['t'] total_data = payload['d'] j = payload['jj'] print("Total data sent:", total_data, "MB") print("Time taken in seconds:", total_time) print("Data rate:", total_data / total_time, "MB/s") if self.concurrent: self.graph_obj.add_concurrent_speed(j, total_data / total_time) else: self.graph_obj.add_speed(j, total_data / total_time) self.Close() # dc Close def onChannel(self, dc): print("\n=======PC1 Got DC=======\n") def onClose(self): print("DC1 Closed") class Peer2(PeerConnection): def onCandidate(self, ice): # print("Python peer2 got candidates: ", ice['candidate']) pass # We don't want trickle ICE now def onMessage(self, msg): # print("\n[PC2]MESSAGE: " + msg + "\n") pass def onChannel(self, dc): print("\n=======PC2 Got DC=======") Thread(None, stress, "Stress_test_t", (dc, self)).start() def onClose(self): print("DC2 Closed") stress_graph = graph() evt_loop = init_cb_event_loop() # 1 loop may not be so performant if (len(sys.argv) > 1): for i in range(0, args.p2p_pairs): handshake_peers(evt_loop, args.size, stress_graph) processWait() else: # Run a series of tests and plot em after test finishes print("##### Stress testing localhost IPC (single pair) ####") for i in range(1, 7): pkt_size = 2 ** i handshake_peers(evt_loop, pkt_size, stress_graph) processWait() concurrent_count = 2 print("Stress testing localhost IPC in concurrent pairs \ ({} at a time with same packet sizes)".format(concurrent_count)) for packet_size in range(1, 7): for con_cnt in range(0, concurrent_count): pkt_size = 2 ** packet_size handshake_peers(evt_loop, pkt_size, stress_graph, True) processWait() stress_graph.plot() <file_sep>#include <vector> #include <map> #include <unordered_map> typedef void (*open_cb)(void); typedef void (*on_string_msg)(int pid, const char* message); typedef void (*on_binary_msg)(void* message); typedef void (*on_close)(int pid); typedef void (*on_error)(const char* description); typedef struct IceCandidate_C IceCandidate_C; typedef void (*on_ice_cb)(IceCandidate_C ice_c); class cb_event_loop { typedef void (*dc_fn_ptr_pid)(int, void*, cb_event_loop*); public: cb_event_loop(); void add_pull_socket(int pid, void *socket); void add_on_candidate(int pid, on_ice_cb fn_ptr); void add_on_datachannel(int pid, dc_fn_ptr_pid fn_ptr); void add_on_open(int pid, open_cb fn_ptr); void add_on_string(int pid, on_string_msg fn_ptr); void add_on_binary(int pid, on_binary_msg fn_ptr); void add_on_close(int pid, on_close fn_ptr); void add_on_error(int pid, on_error fn_ptr); void* getSocket(int pid); void addSocket(int pid, void* socket); private: std::unordered_map<int, void*> pids_vs_sockets; std::map<int, void*> pull_sockets; static void parent_cb_loop(cb_event_loop* cb_evt_loop); std::unordered_map<int, on_ice_cb> on_candidate_cb; std::unordered_map<int, dc_fn_ptr_pid> on_datachannel_cb; std::unordered_map<int, open_cb> on_open_cb; std::unordered_map<int, on_string_msg> on_stringmsg_cb; std::unordered_map<int, on_binary_msg> on_binarymsg_cb; std::unordered_map<int, on_close> on_close_cb; std::unordered_map<int, on_error> on_error_cb; }; <file_sep>/** * C Wrapper around the C++ Classes. */ #pragma once #ifdef __cplusplus #include <rtcdcpp/cb_event_loop.hpp> extern "C" { typedef struct rtcdcpp::PeerConnection PeerConnection; typedef struct rtcdcpp::DataChannel DataChannel; #else typedef struct PeerConnection PeerConnection; typedef struct DataChannel DataChannel; typedef struct cb_event_loop cb_event_loop; #endif #include <stdint.h> #include <stdbool.h> #include <glib.h> #include <sys/types.h> cb_event_loop* init_cb_event_loop(void); struct RTCIceServer_C { const char* hostname; int port; }; struct RTCConfiguration_C { const GArray* ice_servers; // RTCIceServer_C unsigned int ice_port_range1; unsigned int ice_port_range2; const char* ice_ufrag; const char* ice_pwd; const GArray* certificates; // RTCCertificate }; struct IceCandidate_C { int pid; const char* candidate; const char* sdpMid; int sdpMLineIndex; }; typedef struct IceCandidate_C IceCandidate_C; IceCandidate_C* newIceCandidate(const char* candidate, const char* sdpMid, int sdpMLineIndex); typedef void (*on_ice_cb)(IceCandidate_C ice_c); typedef void (*on_dc_cb)(DataChannel *dc, void* socket); typedef void (*dc_fn_ptr_pid)(int, void*, cb_event_loop*); struct pc_info { int pid; void* socket; }; typedef struct pc_info pc_info; pc_info newPeerConnection(struct RTCConfiguration_C config, on_ice_cb ice_cb, dc_fn_ptr_pid dc_cb, cb_event_loop* cb_loop); void sendSignal(void* zmqsock); void signalSink(void* zmqsock); void destroyPeerConnection(void* socket); void ParseOffer(void* socket, const char* sdp); char* GenerateOffer(void* socket); char* GenerateAnswer(void* socket); bool SetRemoteIceCandidate(void* socket, const char* candidate_sdp); bool SetRemoteIceCandidates(void* socket, const GArray* candidate_sdps); int CreateDataChannel(void* socket, const char* label, const char* protocol, u_int8_t chan_type, u_int32_t reliability); // DataChannel member functions // TODO u_int16_t getDataChannelStreamID(void* socket, DataChannel *dc); u_int8_t getDataChannelType(void* socket, DataChannel *dc); const char* getDataChannelLabel(void* socket, DataChannel *dc); const char* getDataChannelProtocol(void* socket, DataChannel *dc); bool SendString(void* socket, const char* msg); bool SendBinary(void* socket, DataChannel *dc, const u_int8_t *msg, int len); void closeDataChannel(void* socket); void _destroyPeerConnection(PeerConnection* pc); void _ParseOffer(PeerConnection* pc, const char* sdp); char* _GenerateOffer(PeerConnection* pc); char* _GenerateAnswer(PeerConnection* pc); bool _SetRemoteIceCandidate(PeerConnection* pc, const char* candidate_sdp); bool _SetRemoteIceCandidates(PeerConnection* pc, const GArray* candidate_sdps); DataChannel *_CreateDataChannel(PeerConnection* pc, char* label, char* protocol, u_int8_t chan_type, u_int32_t reliability); // DataChannel member functions u_int16_t _getDataChannelStreamID(DataChannel *dc); u_int8_t _getDataChannelType(DataChannel *dc); const char* _getDataChannelLabel(DataChannel *dc); const char* _getDataChannelProtocol(DataChannel *dc); bool _SendString(DataChannel *dc, const char* msg); bool _SendBinary(DataChannel *dc, u_int8_t *msg, int len); void _closeDataChannel(DataChannel *dc); //DataChannel Callback related methods typedef void (*open_cb)(void); typedef void (*on_string_msg)(int pid, const char* message); typedef void (*on_binary_msg)(void* message); typedef void (*on_close)(int pid); typedef void (*on_error)(const char* description); void SetOnOpen(int pid, cb_event_loop* cb_event_loop, open_cb on_open_cb); void SetOnStringMsgCallback(int pid, cb_event_loop* cb_event_loop, on_string_msg recv_str_cb); void SetOnBinaryMsgCallback(void *socket, on_binary_msg msg_binary_cb); void SetOnClosedCallback(int pid, cb_event_loop* cb_event_loop, on_close close_cb); void SetOnErrorCallback(void *socket, DataChannel *dc, on_error error_cb); //void _SetOnOpen(DataChannel *dc, open_cb on_open_cb); //void _SetOnStringMsgCallback(DataChannel *dc, on_string_msg recv_str_cb); //void _SetOnBinaryMsgCallback(DataChannel *dc, on_binary_msg msg_binary_cb); //void _SetOnClosedCallback(DataChannel *dc, on_close close_cb); //void _SetOnErrorCallback(DataChannel *dc, on_error error_cb); void processWait(void); #ifdef __cplusplus } #endif <file_sep>#include <rtcdcpp/cb_event_loop.hpp> #include <thread> #include <zmq.h> #include <callbacks.pb.h> #include <unistd.h> #include <iostream> #include <errno.h> struct IceCandidate_C { int pid; const char* candidate; const char* sdpMid; int sdpMLineIndex; }; cb_event_loop::cb_event_loop() { std::thread cb_event_loop(cb_event_loop::parent_cb_loop, this); cb_event_loop.detach(); } void* cb_event_loop::getSocket(int pid) { return this->pids_vs_sockets[pid]; } void cb_event_loop::addSocket(int pid, void* socket) { if (!this->pids_vs_sockets.emplace(pid, socket).second) { this->pids_vs_sockets.erase(pid); this->pids_vs_sockets.emplace(pid, socket); } } void cb_event_loop::add_pull_socket(int pid, void *socket) { this->pull_sockets.insert_or_assign(pid, socket); } void cb_event_loop::add_on_candidate(int pid, on_ice_cb fn_ptr) { if (!this->on_candidate_cb.emplace(pid, fn_ptr).second) { this->on_candidate_cb.erase(pid); this->on_candidate_cb.emplace(pid, fn_ptr); } } void cb_event_loop::add_on_datachannel(int pid, dc_fn_ptr_pid fn_ptr) { if (!this->on_datachannel_cb.emplace(pid, fn_ptr).second) { this->on_datachannel_cb.erase(pid); this->on_datachannel_cb.emplace(pid, fn_ptr); } } void cb_event_loop::add_on_open(int pid, open_cb fn_ptr) { if (!this->on_open_cb.emplace(pid, fn_ptr).second) { this->on_open_cb.erase(pid); this->on_open_cb.emplace(pid, fn_ptr); } } void cb_event_loop::add_on_string(int pid, on_string_msg fn_ptr) { if (!this->on_stringmsg_cb.emplace(pid, fn_ptr).second) { this->on_stringmsg_cb.erase(pid); this->on_stringmsg_cb.emplace(pid, fn_ptr); } } void cb_event_loop::add_on_binary(int pid, on_binary_msg fn_ptr) { if (!this->on_binarymsg_cb.emplace(pid, fn_ptr).second) { this->on_binarymsg_cb.erase(pid); this->on_binarymsg_cb.emplace(pid, fn_ptr); } } void cb_event_loop::add_on_close(int pid, on_close fn_ptr) { if (!this->on_close_cb.emplace(pid, fn_ptr).second) { this->on_close_cb.erase(pid); this->on_close_cb.emplace(pid, fn_ptr); } } void cb_event_loop::add_on_error(int pid, on_error fn_ptr) { if (!this->on_error_cb.emplace(pid, fn_ptr).second) { this->on_error_cb.erase(pid); this->on_error_cb.emplace(pid, fn_ptr); } } void cb_event_loop::parent_cb_loop(cb_event_loop* cb_evt_loop) { bool alive = true; while(alive) { zmq_msg_t cb_msg; int cb_msg_init = zmq_msg_init (&cb_msg); assert (cb_msg_init == 0); int cb_zmq_recv; for (auto const &pull_socket : cb_evt_loop->pull_sockets) { int pid = pull_socket.first; // auto pid? cb_zmq_recv = zmq_recvmsg (pull_socket.second, &cb_msg, ZMQ_DONTWAIT); if (cb_zmq_recv == -1) { if (errno == 11) { // EAGAIN; which means it was in non blocking mode and no messages were found // printf("\nNo message found\n"); // std::this_thread::sleep_for(std::chrono::milliseconds(50)); continue; } } std::string recv_string((const char *) zmq_msg_data(&cb_msg)); librtcdcpp::Callback cb_obj; // printf("\nRecv string size: %zu\n", recv_string.size()); if (cb_obj.ParseFromString(recv_string) == false) { // printf("\nParseFromString returned false\n"); // not sure what that bool actually means. Wasn't able to find proper doc // std::this_thread::sleep_for(std::chrono::milliseconds(100)); // continue; } if (cb_obj.has_on_cand()) { const librtcdcpp::Callback::onCandidate& parsed_candidate = cb_obj.on_cand(); // cb_obj auto callback_fn = cb_evt_loop->on_candidate_cb[pid]; IceCandidate_C cand_arg; cand_arg.pid = pid; cand_arg.candidate = parsed_candidate.candidate().c_str(); cand_arg.sdpMid = parsed_candidate.sdpmid().c_str(); cand_arg.sdpMLineIndex = parsed_candidate.sdpmlineindex(); //printf("\n[C] candidate for pid %d is %s\n", pid, cand_arg.candidate); callback_fn(cand_arg); } else { if (cb_obj.has_on_msg()) { const librtcdcpp::Callback::onMessage& parsed_message = cb_obj.on_msg(); auto callback_fn = cb_evt_loop->on_stringmsg_cb[pid]; if (callback_fn != NULL) { callback_fn(pid, parsed_message.message().c_str()); } } else { if (cb_obj.cbwo_args() == librtcdcpp::Callback::ON_CHANNEL) { auto callback_fn = cb_evt_loop->on_datachannel_cb[pid]; callback_fn(pid, cb_evt_loop->getSocket(pid), cb_evt_loop); } else if (cb_obj.cbwo_args() == librtcdcpp::Callback::ON_CLOSE) { auto callback_fn = cb_evt_loop->on_close_cb[pid]; callback_fn(pid); //signal the command loop on its child to exit out of it zmq_send(cb_evt_loop->getSocket(pid), "a", sizeof(char), 0); if (zmq_close(cb_evt_loop->pull_sockets[pid]) != 0) { perror("Close pull_socket error:"); } cb_evt_loop->pull_sockets.erase(pid); break; } //TODO: onError } } } } } <file_sep>#include <rtcdcpp/librtcdcpp.h> #include <glib.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* Custom multiline stdin scanning function */ gchar* getlines() { size_t len = 0, linesize, inc_size; gchar *line, *lines=NULL; inc_size = 0; linesize = 2; while (linesize > 1) { linesize = getline(&line, &len, stdin); size_t strlength = strlen(line); size_t old_size = inc_size; inc_size += (sizeof(char) * strlength); lines = realloc(lines, inc_size); for (int i = 0; i < strlength; i++) { lines[old_size + i] = line[i]; } } lines = realloc(lines, inc_size + 1); lines[inc_size + 1] = '\0'; return lines; } /* end of custom multiline stdin scanning function */ int main() { struct RTCIceServer_C rtc_ice; rtc_ice.hostname = "stun3.l.google.com"; rtc_ice.port = 19302; struct RTCConfiguration_C rtc_conf; GArray* ice_servers; ice_servers = g_array_new(false, false, sizeof(rtc_ice)); g_array_append_val(ice_servers, rtc_ice); rtc_conf.ice_ufrag = NULL; rtc_conf.ice_pwd = NULL; rtc_conf.ice_servers = ice_servers; cb_event_loop* cb_loop; cb_loop = init_cb_event_loop(); void onIceCallback(struct IceCandidate_C ice_cand) {} struct DataChannel* dc; void onDCCallback(struct DataChannel* dc) { printf("\n========Got datachannel!=========\n"); } pc_info pc_info_ret1; pc_info_ret1 = newPeerConnection(rtc_conf, onIceCallback, onDCCallback, cb_loop); void* sock1 = pc_info_ret1.socket; ParseOffer(sock1, ""); // Leads to ICE candidates being saved in next Generate SDP call char* answer = GenerateAnswer(sock1); gchar* answer_e = g_base64_encode(answer, strlen(answer)); printf("\nAnswer:\n%s\n", answer_e); printf("\n\nEnter offer SDP:\n"); gchar *received_sdp = getlines(); gsize decoded_sdp_len; received_sdp = g_base64_decode(received_sdp, &decoded_sdp_len); ParseOffer(sock1, received_sdp); free(answer); while(1) { usleep(1); } return 0; } <file_sep>#add_executable(testclient #cpslib/pslib.h #json/json.h #json/json-forwards.h #easywsclient.cpp #easywsclient.hpp #jsoncpp.cpp #testclient.cpp #WebSocketWrapper.cpp #WebSocketWrapper.hpp) #set(CMAKE_PREFIX_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cpslib/") #find_library(CPS_LIB NAMES pslib) #target_link_libraries(testclient pslib "${CPS_LIB}" rtcdcpp) add_executable(c_offer c_offer.c "${CMAKE_CURRENT_SOURCE_DIR}/../../include/rtcdcpp/librtcdcpp.h" ) target_link_libraries(c_offer rtcdcpp) set_target_properties(c_offer PROPERTIES LINKER_LANGUAGE C ) add_executable(2in1 2in1.c "${CMAKE_CURRENT_SOURCE_DIR}/../../include/rtcdcpp/librtcdcpp.h" ) target_link_libraries(2in1 rtcdcpp) set_target_properties(2in1 PROPERTIES LINKER_LANGUAGE C ) add_executable(c_answer c_answer.c "${CMAKE_CURRENT_SOURCE_DIR}/../../include/rtcdcpp/librtcdcpp.h" ) target_link_libraries(c_answer rtcdcpp) set_target_properties(c_answer PROPERTIES LINKER_LANGUAGE C ) #add_executable(testclientoffer #json/json.h #json/json-forwards.h #easywsclient.cpp #easywsclient.hpp #jsoncpp.cpp #testclient_offer.cpp #WebSocketWrapper.cpp #WebSocketWrapper.hpp) #target_link_libraries(testclientoffer rtcdcpp) #add_executable(testclientanswer #json/json.h #json/json-forwards.h #easywsclient.cpp #easywsclient.hpp #jsoncpp.cpp #testclient_answer.cpp #WebSocketWrapper.cpp #WebSocketWrapper.hpp) #target_link_libraries(testclientanswer rtcdcpp) <file_sep>/** * Simple WebRTC test client. */ #include "WebSocketWrapper.hpp" #include "json/json.h" #include <rtcdcpp/PeerConnection.hpp> #include <rtcdcpp/Logging.hpp> #include <ios> #include <iomanip> #include <iostream> #include <fstream> #include <unistd.h> #define SCTP_DEBUG #define SCTP_MBUF_LOGGING #include<thread> #include<chrono> #include<ctime> extern "C" { #include "cpslib/pslib.h" } bool running = true; using namespace rtcdcpp; #include<usrsctp.h> void send_loop(std::shared_ptr<DataChannel> dc) { std::ifstream bunnyFile; bunnyFile.open("frag_bunny.mp4", std::ios_base::in | std::ios_base::binary); char buf[100 * 1024]; while (bunnyFile.good()) { bunnyFile.read(buf, 100 * 1024); int nRead = bunnyFile.gcount(); if (nRead > 0) { dc->SendBinary((const uint8_t *)buf, nRead); std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "Sent message of size " << std::to_string(nRead) << std::endl; } } std::chrono::time_point<std::chrono::system_clock> start, end; ChunkQueue messages; void onDCMessage(std::string message) { std::cout << message << "\n"; }; void onDCClose() { std::cout << "DC Close!" << "\n"; running = false; messages.Stop(); }; int gdbbreak = 0; void stress1(std::shared_ptr<DataChannel> dc) { int i = 1; int count = 0; int max_count = 2000; int bytecount1 = 0, bytecount2 = 0; int j; j = 32; // size in kilobytes i = j * 1024; std::vector<CpuTimes> cpuvec; auto cpuvec_val = cpu_times(false); cpuvec.push_back(*cpuvec_val); std::cout << "===Testing fixed payloads of " << j << " kB " << max_count << " times===\n"; start = std::chrono::system_clock::now(); while (running && count < max_count) { count += 1; std::string test_str((size_t) i, 'A'); try { dc->SendString(test_str); } catch(std::runtime_error& e) { std::cout << "BROKE at count: " << count << "\n"; count--; break; } bytecount1 += i; } cpuvec_val = cpu_times(true); cpuvec.push_back(*cpuvec_val); end = std::chrono::system_clock::now(); std::chrono::duration<double> elapsed_seconds = end-start; CpuTimes ct1 = cpuvec.front(); double *cpures = cpu_util_percent(false, &ct1); std::cout << "CPU util: " << std::fixed << std::setprecision(1) << *cpures << "%\n"; //std::cout << bytecount1 << " bytes sent.\n"; int inc_stop; inc_stop = count; i = 1; count = 0; int wait_1, close_wait; wait_1 = 4; //std::cout << "\nWaiting " << wait_1 << " seconds.\n"; // usleep(wait_1 * 1000000); std::cout << "===Testing throughput using single char spam===\n"; while (running && count < 419) { count += 1; std::string test_str((size_t) i, 'A'); try { //usleep(300000); if (count == 419) { gdbbreak = 1; } dc->SendString(test_str); } catch(std::runtime_error& e) { std::cout << "BROKE at count: " << count << "\n"; count--; break; } } std::cout << count << " bytes sent.\n\n"; std::cout << "Incremental throughput stops at: " << inc_stop << "\n"; std::cout << "Single char spam stops at count: " << count << "\n"; std::cout << "TOTAL successful send_string calls: " << inc_stop + count << "\n"; std::cout << "TOTAL data sent: " << bytecount1 / (1024 * 1024) << " MB\n"; std::cout << "TOTAL time taken: " << elapsed_seconds.count() << " seconds\n"; std::cout << "Data rate: " << ((bytecount1) / elapsed_seconds.count()) / (1024 * 1024) << " MB/s\n"; close_wait = 3; std::cout << "\nWaiting " << close_wait << " seconds before closing DC.\n"; usleep(close_wait * 1000000); //5s dc->Close(); } int main(void) { #ifndef SPDLOG_DISABLED auto console_sink = spdlog::sinks::stdout_sink_mt::instance(); spdlog::create("rtcdcpp.PeerConnection", console_sink); spdlog::create("rtcdcpp.SCTP", console_sink); spdlog::create("rtcdcpp.Nice", console_sink); spdlog::create("rtcdcpp.DTLS", console_sink); spdlog::set_level(spdlog::level::debug); #endif WebSocketWrapper ws("ws://localhost:5000/channel/test"); std::shared_ptr<PeerConnection> pc; std::shared_ptr<DataChannel> dc; if (!ws.Initialize()) { std::cout << "WebSocket connection failed\n"; return 0; } RTCConfiguration config; config.ice_servers.emplace_back(RTCIceServer{"stun3.l.google.com", 19302}); // bool run std::function<void(std::string)> onMessage = [](std::string msg) { messages.push(std::shared_ptr<Chunk>(new Chunk((const void *)msg.c_str(), msg.length()))); }; std::function<void(PeerConnection::IceCandidate)> onLocalIceCandidate = [&ws](PeerConnection::IceCandidate candidate) { Json::Value jsonCandidate; jsonCandidate["type"] = "candidate"; jsonCandidate["msg"]["candidate"] = candidate.candidate; jsonCandidate["msg"]["sdpMid"] = candidate.sdpMid; jsonCandidate["msg"]["sdpMLineIndex"] = candidate.sdpMLineIndex; Json::StreamWriterBuilder wBuilder; ws.Send(Json::writeString(wBuilder, jsonCandidate)); }; std::thread stress_thread; std::function<void(std::shared_ptr<DataChannel> channel)> onDataChannel = [&dc, &stress_thread](std::shared_ptr<DataChannel> channel) { std::cout << "Hey cool, got a data channel\n"; dc = channel; std::thread send_thread = std::thread(send_loop, channel); send_thread.detach(); }; ws.SetOnMessage(onMessage); ws.Start(); ws.Send("{\"type\": \"client_connected\", \"msg\": {}}"); Json::Reader reader; Json::StreamWriterBuilder msgBuilder; while (running) { ChunkPtr cur_msg = messages.wait_and_pop(); if (!running) { std::cout << "Breaking\n"; break; } std::string msg((const char *)cur_msg->Data(), cur_msg->Length()); std::cout << msg << "\n"; Json::Value root; if (reader.parse(msg, root)) { //std::cout << "Got msg of type: " << root["type"] << "\n"; if (root["type"] == "offer") { //std::cout << "Time to get the rtc party started\n"; pc = std::make_shared<PeerConnection>(config, onLocalIceCandidate, onDataChannel); pc->ParseOffer(root["msg"]["sdp"].asString()); Json::Value answer; answer["type"] = "answer"; answer["msg"]["sdp"] = pc->GenerateAnswer(); answer["msg"]["type"] = "answer"; //std::cout << "Sending Answer: " << answer << "\n"; ws.Send(Json::writeString(msgBuilder, answer)); } else if (root["type"] == "candidate") { pc->SetRemoteIceCandidate("a=" + root["msg"]["candidate"].asString()); } } else { std::cout << "Json parse failed" << "\n"; } } pc.reset(); //lose pc. ws.Close(); return 0; } <file_sep>from pyrtcdcpp import RTCConf, PeerConnection from pprint import pprint from time import sleep from base64 import b64encode, b64decode got_dc = False ### CALLBACKS ### class Peer(PeerConnection): def onCandidate(self, ice): pass # We don't want trickle ICE now def onMessage(self, msg): #print("\nMESSAGE: " + msg + "\n") pass def onChannel(self, dc): global dataChan global got_dc dataChan = dc got_dc = True print("\n=======Got DC=======\n") def onClose(self): print("DC Closed") pc1 = Peer() pc1.ParseOffer('') # This is to trigger the collection of candidates in sdp (non trickle way to connect) # Handshake part. Give our answer, take the offer answer = pc1.GenerateAnswer() answer = bytes(answer, 'utf-8') print("Answer: ", b64encode(answer).decode('utf-8')) offer = b64decode(input("Offer:")) pc1.ParseOffer(offer.decode('utf-8')) while True: if got_dc: #msg = input("Enter msg: ") #dataChan.SendString(msg) pass sleep(1) <file_sep>from cffi import FFI import os ffibuilder = FFI() ffibuilder.set_source("libpyrtcdcpp", """ typedef struct PeerConnection PeerConnection; typedef struct DataChannel DataChannel; #include <stdbool.h> #include <glib.h> #include <sys/types.h> #include "rtcdcpp/librtcdcpp.h" """, include_dirs=["../src/", "../include", "/usr/include/glib-2.0", "/usr/lib64/glib-2.0/include", "/usr/lib/glib-2.0/include", "/usr/lib/arm-linux-gnueabihf/glib-2.0/include"], libraries=["rtcdcpp"], library_dirs=["../"]) lines = open(os.path.abspath("../include/rtcdcpp") + "/librtcdcpp.h") altered_lines = ['' if line.startswith('#include ') or line.startswith('#pragma') or line.startswith('extern') or line.startswith('typedef struct rtcdcpp::') or line.startswith('#if') or line.startswith('#e') else line for line in lines] cdef_string = ''' typedef char... gchar; typedef unsigned int guint; struct GArray { gchar *data; guint len; }; typedef struct GArray GArray; typedef uint16_t u_int16_t; typedef uint32_t u_int32_t; typedef uint8_t u_int8_t; typedef bool gboolean; typedef const void *gconstpointer; typedef unsigned int pid_t; GArray * g_array_new (gboolean zero_terminated, gboolean clear_, guint element_size); GArray * g_array_append_vals(GArray* a, gconstpointer v, guint len); ''' + ''.join(altered_lines) cdef_string = cdef_string[:-2] # Remove the trailing } cdef_string += ''' extern "Python" void onDCCallback(int pid, void* socket, cb_event_loop* cb_loop); extern "Python" void onIceCallback(IceCandidate_C ice); extern "Python" void onOpened(void); extern "Python" void onClosed(int pid); extern "Python" void onStringMsg(int pid, const char* message); extern "Python" void onBinaryMsg(void* message); extern "Python" void onError(const char* description); ''' ffibuilder.cdef(cdef_string) if __name__ == "__main__": ffibuilder.compile(verbose=True) <file_sep>from cent import Client, generate_token # Cent.Client for publishing. import signal # Websocket centrifugo client (centrifuge.Client) for subscribing from centrifuge import Client as clientpy from centrifuge import Credentials import sys from uuid import uuid4 import json import time from time import sleep from pyrtcdcpp import RTCConf, PeerConnection, \ processWait, exitter, init_cb_event_loop, DataChannel import asyncio import os signalling_server = os.getenv('CENTRIFUGO_SERVER', "localhost:8000") secret_key = "secret" # or use --insecure_api ? class InvalidUUID(Exception): pass global state # Denotes "DC connected" state. 0 being disconnected and 1 being connected state = 0 global dc dc = None class Peer(PeerConnection): def onCandidate(self, ice): pass # We don't want trickle ICE now def onMessage(self, msg): print("\nReceived message: " + msg) print("Send msg:-") def onChannel(self, dcn): global dc global state state = 1 dc = dcn print("\n=======Got DC=======\n") print("\nPress enter to get the prompt.") def onClose(self): print("DC Closed") os._exit(0) url = "http://" + signalling_server global cent_client cent_client = Client(url, secret_key, timeout=1) # Cent async def run(evt_loop, user): global peer global dc dc = None peer = None timestamp = str(int(time.time())) info = json.dumps({"client_version": "0.1"}) token = generate_token(secret_key, user, timestamp, info=info) async def input_validation(uinput): uinput = uinput[:-1] # Remove '\n' global state global peer if state == 1: return if uinput not in cent_client.channels() or uinput == user: raise InvalidUUID else: peer = Peer(evt_loop) peer.ParseOffer('') # gather candidates peer.CreateDataChannel("test", evt_loop, None, DataChannel.DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED, 2000) offer_sdp = peer.GenerateOffer() payload = { "sdp_cand": offer_sdp, "sdp_type": "offer", "from": user } if cent_client.publish(uinput, payload) is None: pass return peer async def uuid_input_loop(peer): global state while True: if state == 0: prompt_user(user) else: break user_input = await q.get() try: peer = await input_validation(user_input) except InvalidUUID: print("\nInvalid UUID!") credentials = Credentials(user, timestamp, info, token) address = "ws://" + signalling_server + "/connection/websocket" async def message_handler(**kwargs): rsc = kwargs['data'] global peer try: sdp = rsc['sdp_cand'] sdp_type = rsc['sdp_type'] from_client = rsc['from'] except KeyError: print("key error") return if sdp_type == "offer": print("Got offer") peer = Peer(evt_loop) peer.ParseOffer('') # cand peer.ParseOffer(sdp) answer = peer.GenerateAnswer() payload = { "sdp_cand": answer, "sdp_type": "answer", "from": None # No need for them to contact us anymore } cent_client.publish(from_client, payload) elif sdp_type == "answer": peer.ParseOffer(sdp) print("SDP answer has been parsed, trying to establish a connection...") async def join_handler(**kwargs): print("Join:", kwargs) async def leave_handler(**kwargs): print("Leave:", kwargs) async def error_handler(**kwargs): print("Sub error:", kwargs) async def dc_input_loop(): # TODO: Clear queue? global dc while state == 1: print("Send msg:-") user_input = await q.get() dc.SendString(user_input) pass async def connection_handler(**kwargs): os.system('clear') print("Connected", kwargs) sub = await clientpy1.subscribe( user, # The channel is our UUID on_message=message_handler, on_join=join_handler, on_leave=leave_handler, on_error=error_handler ) await uuid_input_loop(peer) await dc_input_loop() async def disconnected_handler(**kwargs): print("Disconnected:", kwargs) if dc is None: os._exit(0) else: dc.Close() async def connect_error_handler(**kwargs): print("Error:", kwargs) clientpy1 = clientpy( address, credentials, on_connect=connection_handler, on_disconnect=disconnected_handler, on_error=connect_error_handler ) print("Connecting to centrifugo signalling server...") await clientpy1.connect() def prompt_user(user): print("My ID: ", user) print("Enter the ID to call:-") def uuid_input_cb(q): asyncio.async(q.put(sys.stdin.readline())) if __name__ == '__main__': def signal_handler(signal, frame): if dc is not None: dc.Close() cent_client.disconnect(user) signal.signal(signal.SIGINT, signal_handler) evt_loop = init_cb_event_loop() user = "psl-" + uuid4().hex[:3] q = asyncio.Queue() loop = asyncio.get_event_loop() loop.add_reader(sys.stdin, uuid_input_cb, q) asyncio.ensure_future(run(evt_loop, user)) try: loop.run_forever() except KeyboardInterrupt: print("interrupted") finally: loop.close() <file_sep>#include <rtcdcpp/librtcdcpp.h> #include <glib.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> extern bool running; #include <fcntl.h> //#include "/usr/include/linux/fcntl.h" // Set callbacks insie onChannel and use the underscore prefix APIs // TODO: Remove the _ from prefix APIs and deprecate the other ones gchar* getlines() { size_t len = 0, linesize, inc_size; gchar *line, *lines=NULL; inc_size = 0; linesize = 2; while (linesize > 1) { linesize = getline(&line, &len, stdin); size_t strlength = strlen(line); size_t old_size = inc_size; inc_size += (sizeof(char) * strlength); lines = realloc(lines, inc_size); for (int i = 0; i < strlength; i++) { lines[old_size + i] = line[i]; } } lines = realloc(lines, inc_size + 1); lines[inc_size + 1] = '\0'; return lines; } void stress1(void *socket) { int i = 1; int count = 0; int max_count = 2000; int bytecount1 = 0, bytecount2 = 0; int j; j = 16; // size in kilobytes i = j * 1024; //std::vector<CpuTimes> cpuvec; //auto cpuvec_val = cpu_times(false); //cpuvec.push_back(*cpuvec_val); printf("\n===Testing fixed payloads of %d kB %d times===\n", j, max_count); time_t start; time(&start); char test_str[i]; for (int str_p = 0; str_p < i; str_p++) { test_str[str_p] = 'A'; } test_str[i] = '\0'; while (count < max_count) { count += 1; if (SendString(socket, test_str) == 0) { printf("\n BROKE at count: %d\n", count); count--; break; } bytecount1 += i; } //cpuvec_val = cpu_times(true); //cpuvec.push_back(*cpuvec_val); time_t end; time(&end); int elapsed_seconds; elapsed_seconds = end - start; //elapsed_seconds = difftime(end, start); //CpuTimes ct1 = cpuvec.front(); //double *cpures = cpu_util_percent(false, &ct1); //std::cout << "CPU util: " << std::fixed << std::setprecision(1) << *cpures << "%\n"; //std::cout << bytecount1 << " bytes sent.\n"; int inc_stop; inc_stop = count; i = 1; count = 0; int wait_1, close_wait; wait_1 = 4; printf("Incremental throughput stops at: %d\n", inc_stop); printf("Single char spam stops at count: %d\n", count); printf("TOTAL successful send_string calls: %d\n", inc_stop + count); printf("TOTAL data sent: %d MB\n", bytecount1 / (1024 * 1024)); printf("TOTAL time taken: %d seconds\n", elapsed_seconds); printf("Data rate: %d MB/s\n", (bytecount1 / elapsed_seconds) / (1024 * 1024)); close_wait = 1; printf("\nWaiting %d seconds before closing DC.\n", close_wait); usleep(close_wait * 1000000); //5s closeDataChannel(socket); } void run_stress_test(void *socket) { printf("\nRunning stress tests\n"); pthread_t t1; pthread_create(&t1, NULL, (void *)&stress1, socket); pthread_detach(t1); } int main() { bool running = false; struct RTCIceServer_C rtc_ice; rtc_ice.hostname = "stun3.l.google.com"; rtc_ice.port = 19302; struct RTCConfiguration_C rtc_conf; GArray* ice_servers; ice_servers = g_array_new(false, false, sizeof(rtc_ice)); g_array_append_val(ice_servers, rtc_ice); rtc_conf.ice_ufrag = NULL; rtc_conf.ice_pwd = <PASSWORD>; rtc_conf.ice_servers = ice_servers; rtc_conf.ice_port_range1 = rtc_conf.ice_port_range2 = 0; struct RTCIceServer_C rtc_ice1; rtc_ice1.hostname = "stun3.l.google.com"; rtc_ice1.port = 19302; struct RTCConfiguration_C rtc_conf1; GArray* ice_servers1; ice_servers1 = g_array_new(false, false, sizeof(rtc_ice1)); g_array_append_val(ice_servers1, rtc_ice1); rtc_conf1.ice_ufrag = NULL; rtc_conf1.ice_pwd = <PASSWORD>; rtc_conf1.ice_servers = ice_servers1; rtc_conf1.ice_port_range1 = rtc_conf1.ice_port_range2 = 0; void onIceCallback(struct IceCandidate_C ice_cand) { } struct DataChannel* dc; cb_event_loop* cb_loop; cb_loop = init_cb_event_loop(); void custom_close1(int pid) { printf("\nCLOSE1 at %d of %d\n", getpid(), pid); //exitter(0); } void onStringMsg1(int pid, const char* message) { /*printf("\nMSG1: %s\n", message);*/ } void onDCCallback(int pid, void *socket, cb_event_loop* cb_loop) { printf("\n=sock1===Got datachannel!=======%d\n", getpid()); //printf("\nCB loop process: %p\n", cb_loop); SetOnClosedCallback(pid, cb_loop, custom_close1); SetOnStringMsgCallback(pid, cb_loop, onStringMsg1); } void custom_close2(int pid) { printf("\nCLOSE2 at %d of %d\n", getpid(), pid); //exitter(0); //No need to call it here now. child will die after it transmits callback to parent } void onStringMsg2(int pid, const char* message) { /*printf("\nMSG2: %s\n", message);*/ } void onDCCallback1(int pid, void* socket, cb_event_loop* cb_loop) { printf("\n=sock2===Got datachannel!=======%d\n", getpid()); //printf("\nCB loop process: %p\n", cb_loop); SetOnClosedCallback(pid, cb_loop, custom_close2); SetOnStringMsgCallback(pid, cb_loop, onStringMsg2); closeDataChannel(socket); //run_stress_test(socket); // spawns a thread as nothing should block in callbacks } void* sock1; void* sock2; pc_info pc_info_ret1; pc_info pc_info_ret2; pc_info_ret1.pid = pc_info_ret2.pid = 0; pc_info_ret1.socket = pc_info_ret2.socket = NULL; pc_info_ret1 = newPeerConnection(rtc_conf, onIceCallback, onDCCallback1, cb_loop); pc_info_ret2 = newPeerConnection(rtc_conf1, onIceCallback, onDCCallback, cb_loop); sock1 = pc_info_ret1.socket; sock2 = pc_info_ret2.socket; ParseOffer(sock1, ""); //trigger ICE ParseOffer(sock2, ""); // "" CreateDataChannel(sock1, "testchannel", "", 0x00, 0); printf("\n====================++++%d++\n", getpid()); char* offer = GenerateOffer(sock1); ParseOffer(sock2, offer); free(offer); char* answer = GenerateAnswer(sock2); ParseOffer(sock1, answer); free(answer); processWait(); return 0; } <file_sep>cd .. && \ sh build.sh && \ cd python && \ python3 pyrtcdcpp_build.py <file_sep>cd ./usrsctp/usrsctplib/ && make && \ cd ../../ && \ cd examples/websocket_client/cpslib/ && \ make && \ cd ../../../ && \ cmake -DUSRSCTP_LIBRARY=./usrsctp/usrsctplib/.libs/libusrsctp.so.1 -DUSRSCTP_INCLUDE_DIR=./usrsctp/usrsctplib -DSPDLOG_INCLUDE_DIR="./spdlog/include/" -DDISABLE_SPDLOG=on -DCMAKE_BUILD_TYPE=Debug && \ make <file_sep>from pyrtcdcpp import RTCConf, PeerConnection from pprint import pprint from time import sleep from base64 import b64encode, b64decode import time got_dc = False ### CALLBACKS ### class Peer(PeerConnection): def onCandidate(self, ice): pass # We don't want trickle ICE now def onMessage(self, msg): print("\nMESSAGE: " + msg + "\n") def onChannel(self, dc): global got_dc got_dc = True print("\n=======Got DC=======\n") def onClose(self): print("DC Closed") def stress(dc): i = 1 count = 0 global running max_count = 2000 byte_count = 0 j = 32 # kB i = j * 1024 print("===Testing fixed payloads of", j, "kB", max_count, "times==="); time_start = time.time() while (running == True) and (count < max_count): count += 1 try: dc.SendString('A' * i) except: print("ERR") break running = False time_end = time.time() total_data = (count * j) / 1024 # in MB total_time = time_end - time_start print("Total data sent:", total_data, "MB") print("Time taken in seconds:", total_time) print("Data rate:", total_data / total_time, "MB/s") pc1 = Peer() pc1.ParseOffer('') # This is to trigger the collection of candidates in sdp (we want a non trickle way to connect) # pc1 generates the offer, so we create the datachannel object dataChan = pc1.CreateDataChannel("test") # Handshake part. Give our offer, take the answer offer = pc1.GenerateOffer() offer = bytes(offer, 'utf-8') print("Offer: ", b64encode(offer).decode('utf-8')) answer = b64decode(input("Answer:")) pc1.ParseOffer(answer.decode('utf-8')) running = True while running == True: if got_dc: #msg = input("Enter msg: ") #dataChan.SendString(msg) stress(dataChan) sleep(1) <file_sep>from setuptools import setup, find_packages setup(name = "pyrtcdcpp", version = "0.1", packages = find_packages(), setup_requires=["cffi>=1.10.0"], cffi_modules=["pyrtcdcpp_build.py:ffibuilder"], install_requires = ["cffi>=1.10.0"], description = "Python bindings for the librtcdcpp library", url = "http://github.com/hamon-in/librtcdcpp", ) <file_sep># Introduction This is a fork of the librtcdcpp project which was written in C++. Changes include a C wrapper which is used by the python wrapper (implemented using CFFI) and the ability to run multiple peer connections within the same process. A stress test script and a CLI python client is bundled. ## Quick start After a clone, do: * `git submodule init && git submodule update` * `docker build -f Dockerfile-debian.armv7 -t librtcdcpp .` for ARMv7 > :warning: It may take several couple of hours to build the ARMv7 container, especially if it has matplotlib, numpy and its dependencies. Comment out [those lines](https://github.com/hamon-in/librtcdcpp/blob/8b8f373c828078c985824b45876b40c5b6648fcc/Dockerfile-debian.armv7#L22-#L24) to build a more lightweight container. The resulting container may not be able to run `stress_test.py`, but should be able to run the signalling client `peer.py`. * `docker run -it librtcdcpp:latest` > :warning: Make sure that the containers that hold the client *and* centrifugo server are configured for proper [networking](https://docs.docker.com/engine/userguide/networking/). You can set `--network=host` to let the containers use the host network's stack for easier networking. Otherwise it'll use the default docker bridge network. ### Stress test Running the stress test script without arguments will run a series of tests, first of which is a sequential test for each packet sizes of 2, 4, 8 ... 64 KBs. Secondly, it will do a concurrent test (2 peers at a time) for each of those packet sizes. At the end of this, it will plot :bar_chart: using matplotlib. * Inside the container, `cd python/` and `./build.sh` * `export LD_LIBRARY_PATH=../` (Since our built .so file will be in project root) * Run the stress test script. See help: `python3 stress-test.py --help` > :recycle: Note: Each time the library is made to create new 'peers', an IPC socket file will be created which has the path "/tmp/librtcdcpp{pid}". If not closed properly, these files will be left back. Do check for `/tmp/librtcdcpp*` files and `rm /tmp/librtcdcpp*` to make sure the inodes don't get full. Stress test [results](https://github.com/hamon-in/librtcdcpp/wiki/Performance-evaluation-(AMD-A8-7410-CPU)#python-concurrent-test-protobuf--zmq) on AMD A8 7410 with the ZMQ/protocol buffers fixes-: ![](http://image.ibb.co/m3j2qm/AMD_librtcdcpp.png) _\*concurrent test was done with 2 peers at a time with the same packet size for each packet size._ ### Signalling server From project root, on the host machine or a different machine on the network (x86/amd64 only), set up the signalling server: * Run the centrifugo real-time messaging server container: `docker run --ulimit nofile=65536:65536 -v $(pwd):/centrifugo -p 8000:8000 centrifugo/centrifugo centrifugo -c cent_config.json` ### Signalling client Go inside the debian container created from the quick start step above and do the following: * Set env var `CENTRIFUGO_SERVER` to hostname:ip of the server started from above. (else it will use the default "localhost:8000") * Do `export LD_LIBRARY_PATH=./` to let the client be aware of the `librtcdcpp.so` shared object that will be made in the project root. Modify as necessary depending on where you are, and relative to the where you have the .so file. * Run `python3 python/peer.py` on the nodes (Python 3.5+ needed). Peer.py assigns a random UUID and you can 'call' any other peer just by typing in their UUID <file_sep>from libpyrtcdcpp import ffi, lib from typing import List, Callable class DataChannel(): DATA_CHANNEL_RELIABLE = 0x00 DATA_CHANNEL_RELIABLE_UNORDERED = 0x80 DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT = 0x01 DATA_CHANNEL_PARTIAL_RELIABLE_REXMIT_UNORDERED = 0x81 DATA_CHANNEL_PARTIAL_RELIABLE_TIMED = 0x02 DATA_CHANNEL_PARTIAL_RELIABLE_TIMED_UNORDERED = 0x82 def __init__(self, dc, pc, cb_loop): self.dc = dc # This is pid now self.pc = pc self.cb_loop = cb_loop def SendString(self, msg: str): if len(msg) > 0: msg = ffi.new("char[]", bytes(msg, 'utf-8')) lib.SendString(self.pc, msg) def SendBinary(self, msg: bytes): msg = ffi.new("u_int_8_t", msg) lib.SendBinary(self.pc, msg, len(msg)) def SetOnOpen(self, on_open): lib.SetOnOpen(self.dc, self.cb_loop, lib.onOpened) def SetOnStringMsgCallback(self, on_string): lib.SetOnStringMsgCallback(self.dc, self.cb_loop, lib.onStringMsg) def SetOnBinaryMsgCallback(self, on_binary): @ffi.def_extern() def onBinaryMsg(msg): if on_binary is not None: on_binary(msg) lib.SetOnBinaryMsgCallback(self.pc, lib.onBinaryMsg) def SetOnClosedCallback(self, on_closed): lib.SetOnClosedCallback(self.dc, self.cb_loop, lib.onClosed) def SetOnErrorCallback(self, on_error): @ffi.def_extern() def onError(description): if on_error is not None: on_error(ffi.string(description).decode('utf-8')) lib.SetOnErrorCallback(self.pc, lib.onError) def Close(self): lib.closeDataChannel(self.pc) def getStreamID(self) -> int: return lib.getDataChannelStreamID(self.pc) # u_int8_t getDataChannelType(DataChannel *dc); # TODO def getLabel(self) -> str: return ffi.string(lib.getDataChannelLabel(self.pc)).decode('utf-8') def getProtocol(self) -> str: return ffi.string(lib.getDataChannelProtocol(self.pc)).decode('utf-8') # This can be a dict instead of a class class RTCConf(): def __init__(self, ice_servers: List[tuple], ice_ufrag: str = None, ice_pwd: str = None, ice_port_range: tuple = (0, 0)): self._ice_servers = ice_servers self._ice_ufrag = ice_ufrag self._ice_pwd = ice_pwd self._ice_port_range1 = ice_port_range[0] self._ice_port_range2 = ice_port_range[1] class PeerConnection(): # Methods that could be overridden. def onMessage(self, message): ''' When a message is received on the data channel ''' pass def onClose(self): ''' When the data channel closes ''' pass def onChannel(self, channel): ''' When data channel is obtained ''' pass def onCandidate(self, candidate): ''' When the peer connection gets a new local ICE candidate ''' pass # Private methods def _onChannel(self, channel, pc): # Set our private onMessage and onClose callbacks channel.SetOnClosedCallback(self.onClose) channel.SetOnStringMsgCallback(self.onMessage) # TODO: Implement OnBinary # channel.SetOnBinaryMsgCallback(self.onMessage) self.onChannel(channel) def __init__(self, cb_evt_loop, rtc_conf: RTCConf = None, onIceCallback_p=None, onDCCallback_p=None): if rtc_conf is None: # Hardcoded default config/setting for STUN server rtc_conf = RTCConf([("stun3.l.google.com", 19302)]) if onIceCallback_p is None: onIceCallback_p = self.onCandidate if onDCCallback_p is None: onDCCallback_p = self._onChannel # Note: These two below aren't 'redefinied'. Take it like one global # callback function that then calls the correct callback. @ffi.def_extern() def onStringMsg(pid: int, msg): callback_fn = cb_evt_loop.get_py_strmsg_cb(pid) callback_fn(ffi.string(msg).decode('utf-8')) # Same issue with this @ffi.def_extern() def onClosed(pid: int): callback_fn = cb_evt_loop.get_py_close_cb(pid) callback_fn() garray = ffi.new("GArray* ice_servers") ice_struct = ffi.new("struct RTCIceServer_C *") garray = lib.g_array_new(False, False, ffi.sizeof(ice_struct[0])) for ice_server in rtc_conf._ice_servers: hostname = ffi.new("char[]", bytes(ice_server[0], 'utf-8')) ice_struct.hostname = hostname ice_struct.port = ice_server[1] lib.g_array_append_vals(garray, ice_struct, 1) rtc_conf_s = ffi.new("struct RTCConfiguration_C *") rtc_conf_s.ice_ufrag = ffi.NULL if rtc_conf._ice_ufrag is None \ else rtc_conf._ice_ufrag rtc_conf_s.ice_pwd = ffi.NULL if rtc_conf._ice_pwd is None \ else rtc_conf._ice_pwd rtc_conf_s.ice_servers = garray rtc_conf_s.ice_port_range1 = rtc_conf._ice_port_range1 rtc_conf_s.ice_port_range2 = rtc_conf._ice_port_range2 # Note: Both onDCCallback and onIceCallback aren't redefined. @ffi.def_extern() def onDCCallback(pid: int, pc, cb_loop): argument = DataChannel(pid, pc, cb_loop) callback_fn = cb_evt_loop.get_py_dc_cb(pid) callback_fn(argument, pc) @ffi.def_extern() def onIceCallback(ice): arguments = {} pid: int = ice.pid callback_fn = cb_evt_loop.get_py_ice_cb(pid) arguments["candidate"] = ffi.string(ice.candidate).decode('utf-8') arguments["sdpMid"] = ffi.string(ice.sdpMid).decode('utf-8') arguments["sdpMLineIndex"] = ice.sdpMLineIndex callback_fn(arguments) ret_val = lib.newPeerConnection(rtc_conf_s[0], lib.onIceCallback, lib.onDCCallback, cb_evt_loop.get_event_loop()) cb_evt_loop.add_py_dc_cb(ret_val.pid, onDCCallback_p) cb_evt_loop.add_py_ice_cb(ret_val.pid, onIceCallback_p) cb_evt_loop.add_py_close_cb(ret_val.pid, self.onClose) cb_evt_loop.add_py_strmsg_cb(ret_val.pid, self.onMessage) self.pc = ret_val.socket def GenerateOffer(self) -> str: retvl = lib.GenerateOffer(self.pc) if retvl != ffi.NULL: return ffi.string(retvl).decode() else: return None def GenerateAnswer(self) -> str: retvl = lib.GenerateAnswer(self.pc) if retvl != ffi.NULL: return ffi.string(retvl).decode() else: return None def ParseOffer(self, offer: str) -> bool: sdp = ffi.new("char[]", bytes(offer, 'utf-8')) if str(self.pc)[16:-1] == '0x1': # print('PC object is null') return return lib.ParseOffer(self.pc, sdp) def CreateDataChannel(self, label: str, cb_loop, protocol: str = None, chan_type=DataChannel.DATA_CHANNEL_RELIABLE, reliability=None): if str(self.pc)[16:-1] == '0x1': # print('PC object is null') return protocol = ffi.new("char[]", bytes('', 'utf-8')) if protocol is None \ else ffi.new("char[]", bytes(label, 'utf-8')) label = ffi.new("char[]", bytes(label, 'utf-8')) if reliability is None: reliability = 0 pid = lib.CreateDataChannel(self.pc, label, protocol, chan_type, reliability) dc = DataChannel(pid, self.pc, cb_loop) return dc def SetRemoteIceCandidate(self, candidate: str) -> bool: candidate = ffi.new("char[]", bytes(candidate, 'utf-8')) return lib.SetRemoteIceCandidate(self.pc, candidate) def SetRemoteIceCandidates(self, candidate_sdps: List[str]) -> bool: garray = ffi.new("GArray* candidate_sdps") for sdp in candidate_sdps: candidate = ffi.new("char[]", bytes(sdp[0], 'utf-8')) lib.g_array_append_vals(garray, candidate, 1) return lib.SetRemoteIceCandidates(self.pc, garray) def Close(self): lib.closeDataChannel(self.pc) class init_cb_event_loop(): def __init__(self): self.dc_callbacks = {} self.ice_callbacks = {} self.close_callbacks = {} self.strmsg_callbacks = {} self.cb_event_loop = None def get_event_loop(self): if self.cb_event_loop is None: self.cb_event_loop = lib.init_cb_event_loop() return self.cb_event_loop def add_py_dc_cb(self, pid: int, callback): self.dc_callbacks[pid] = callback def add_py_ice_cb(self, pid: int, callback): self.ice_callbacks[pid] = callback def add_py_close_cb(self, pid: int, callback): self.close_callbacks[pid] = callback def get_py_close_cb(self, pid: int): return self.close_callbacks[pid] def add_py_strmsg_cb(self, pid: int, callback): self.strmsg_callbacks[pid] = callback def get_py_strmsg_cb(self, pid: int): return self.strmsg_callbacks[pid] def get_py_dc_cb(self, pid: int): return self.dc_callbacks[pid] def get_py_ice_cb(self, pid: int): return self.ice_callbacks[pid] def processWait(): lib.processWait() <file_sep>/** * C Wrapper around the C++ classes. */ #include <unistd.h> #include <strings.h> #include <stdio.h> #include <rtcdcpp/PeerConnection.hpp> #include <callbacks.pb.h> #include <rtcdcpp/librtcdcpp.h> #include <rtcdcpp/DataChannel.hpp> #include <glib.h> #include <stdbool.h> #include <memory> #include <functional> #include <iostream> #include <sys/types.h> #include <signal.h> #include <sys/wait.h> #include <list> #include <unordered_map> #include <zmq.h> #include <thread> #include <errno.h> #define DESTROY_PC 0 #define PARSE_SDP 1 #define GENERATE_OFFER 2 #define GENERATE_ANSWER 3 #define SET_REMOTE_ICE_CAND 4 #define SET_REMOTE_ICE_CANDS 5 #define CREATE_DC 6 #define GET_DC_SID 7 #define GET_DC_TYPE 8 #define GET_DC_LABEL 9 #define GET_DC_PROTO 10 #define SEND_STRING 11 #define SEND_BINARY 12 #define CLOSE_DC 13 extern "C" { IceCandidate_C* newIceCandidate(const char* candidate, const char* sdpMid, int sdpMLineIndex) { //IceCandidate_C ice_cand; IceCandidate_C* ice_cand = (IceCandidate_C *) malloc(sizeof(IceCandidate_C)); ice_cand->candidate = candidate; //& ice_cand->sdpMid = sdpMid; ice_cand->sdpMLineIndex = sdpMLineIndex; return ice_cand; } void sendSignal(void* zmqsock) { zmq_send (zmqsock, "", 0, 0); } void signalSink(void *zmqsock) { void* nothing; zmq_recv (zmqsock, nothing, 0, 0); } std::list<int> process_status; void fillInCandidate(librtcdcpp::Callback* callback, std::string candidate, std::string sdpMid, int sdpMLineIndex) { librtcdcpp::Callback::onCandidate* on_candidate = new librtcdcpp::Callback::onCandidate; on_candidate->set_candidate(candidate.c_str()); on_candidate->set_sdpmid(sdpMid.c_str()); on_candidate->set_sdpmlineindex(sdpMLineIndex); callback->set_allocated_on_cand(on_candidate); } void fillInStringMessage(librtcdcpp::Callback* callback, std::string message) { librtcdcpp::Callback::onMessage* on_message = new librtcdcpp::Callback::onMessage; on_message->set_message(message); callback->set_allocated_on_msg(on_message); } void SetCallbackTypeOnChannel(librtcdcpp::Callback* callback) { callback->set_cbwo_args(librtcdcpp::Callback::ON_CHANNEL); } void SetCallbackTypeOnClose(librtcdcpp::Callback* callback) { callback->set_cbwo_args(librtcdcpp::Callback::ON_CLOSE); } cb_event_loop* init_cb_event_loop() { cb_event_loop* cb_loop = new cb_event_loop(); return cb_loop; } pc_info newPeerConnection(RTCConfiguration_C config_c, on_ice_cb ice_cb, dc_fn_ptr_pid dc_cb, cb_event_loop* parent_event_loop) { //spdlog::set_level(spdlog::level::info); //spdlog::set_pattern("*** [%H:%M:%S] %P %v ***"); // Local callback that is registered to 'route' the callback to the event loop socket std::function<void(rtcdcpp::PeerConnection::IceCandidate)> onLocalIceCandidate = [ice_cb](rtcdcpp::PeerConnection::IceCandidate candidate) { IceCandidate_C ice_cand_c; ice_cand_c.candidate = candidate.candidate.c_str(); // ice_cand_c.sdpMid = candidate.sdpMid.c_str(); ice_cand_c.sdpMLineIndex = candidate.sdpMLineIndex; librtcdcpp::Callback* callback = new librtcdcpp::Callback; fillInCandidate(callback, ice_cand_c.candidate, ice_cand_c.sdpMid, ice_cand_c.sdpMLineIndex); std::string serialized_cb; callback->SerializeToString(&serialized_cb); void *child_to_parent_context = zmq_ctx_new (); void *pusher = zmq_socket (child_to_parent_context, ZMQ_PUSH); char cb_connect_path[33]; snprintf(cb_connect_path, sizeof(cb_connect_path), "ipc:///tmp/librtcdcpp%d-cb", getpid()); int cb_rc = zmq_connect (pusher, cb_connect_path); zmq_send (pusher, (const void *) serialized_cb.c_str(), serialized_cb.size(), 0); zmq_close (pusher); }; rtcdcpp::RTCConfiguration config; for(int i = 0; i < config_c.ice_servers->len; i++) { config.ice_servers.emplace_back(rtcdcpp::RTCIceServer{"stun3.l.google.com", 19302}); } std::pair<unsigned, unsigned> port_range = std::make_pair(config_c.ice_port_range1, config_c.ice_port_range2); config.ice_port_range = port_range; if (config_c.ice_ufrag) { std::string ice_ufrag_string (config_c.ice_ufrag); config.ice_ufrag = ice_ufrag_string; } if (config_c.ice_pwd) { std::string ice_pwd_string (config_c.ice_pwd); config.ice_pwd = ice_pwd_string; } //TODO: Check this later. Doesn't seem to break any use-cases I'm aware of. /* rtcdcpp::RTCCertificate *rtc_cert; rtc_cert = (rtcdcpp::RTCCertificate*) malloc(sizeof(rtcdcpp::RTCCertificate)); for(int i = 0; i <= config_c.certificates->len; i++) { rtc_cert = &g_array_index(config_c.certificates, rtcdcpp::RTCCertificate, i); config.certificates.emplace_back(&rtc_cert); } */ pid_t cpid = fork(); //TODO: Try using some options from SETSOCKOPT void *context = zmq_ctx_new (); void *requester = zmq_socket (context, ZMQ_REQ); void *cb_context = zmq_ctx_new (); void *cb_pull_socket = zmq_socket (cb_context, ZMQ_PULL); pc_info pc_info_ret; int process_status_var; process_status.push_front(process_status_var); if (cpid == 0) { bool relayedOnClose = false; bool alive = true; //child void *child_context = zmq_ctx_new (); DataChannel* child_dc; std::function<void(std::shared_ptr<DataChannel> channel)> onDataChannel = [dc_cb, &child_dc, &relayedOnClose, &alive](std::shared_ptr<DataChannel> channel) { void *child_to_parent_context = zmq_ctx_new (); // TODO: onBinary and onError callbacks (later) std::function<void(std::string string1)> onStringMsg = [child_to_parent_context](std::string string1) { librtcdcpp::Callback* callback = new librtcdcpp::Callback; fillInStringMessage(callback, string1); std::string serialized_cb; callback->SerializeToString(&serialized_cb); void *pusher = zmq_socket (child_to_parent_context, ZMQ_PUSH); char cb_connect_path[33]; snprintf(cb_connect_path, sizeof(cb_connect_path), "ipc:///tmp/librtcdcpp%d-cb", getpid()); int cb_rc = zmq_connect (pusher, cb_connect_path); zmq_send (pusher, (const void *) serialized_cb.c_str(), serialized_cb.size(), 0); zmq_close (pusher); }; std::function<void()> onClosed = [child_to_parent_context, &relayedOnClose, &alive]() { librtcdcpp::Callback* callback = new librtcdcpp::Callback; SetCallbackTypeOnClose(callback); std::string serialized_cb; callback->SerializeToString(&serialized_cb); void *pusher = zmq_socket (child_to_parent_context, ZMQ_PUSH); char cb_connect_path[33]; snprintf(cb_connect_path, sizeof(cb_connect_path), "ipc:///tmp/librtcdcpp%d-cb", getpid()); int cb_rc = zmq_connect (pusher, cb_connect_path); zmq_send (pusher, (const void *) serialized_cb.c_str(), serialized_cb.size(), 0); //zmq_setsockopt(pusher, //no linger? if (zmq_close (pusher) != 0) { printf("\nZMQ close error: %s\n", strerror(errno)); } if (zmq_ctx_term(child_to_parent_context) != 0) { printf("\nZMQ term error: %s\n", strerror(errno)); } relayedOnClose = true; alive = false; }; child_dc = (DataChannel *) channel.get(); child_dc->SetOnClosedCallback(onClosed); child_dc->SetOnStringMsgCallback(onStringMsg); librtcdcpp::Callback* callback = new librtcdcpp::Callback; SetCallbackTypeOnChannel(callback); std::string serialized_cb; if (callback->SerializeToString(&serialized_cb) == false) { printf("\nDC cb serialize error!\n"); // return? } void *pusher = zmq_socket (child_to_parent_context, ZMQ_PUSH); char cb_connect_path[33]; snprintf(cb_connect_path, sizeof(cb_connect_path), "ipc:///tmp/librtcdcpp%d-cb", getpid()); int cb_rc = zmq_connect (pusher, cb_connect_path); zmq_send (pusher, (const void *) serialized_cb.c_str(), serialized_cb.size(), 0); zmq_close (pusher); }; PeerConnection* child_pc; child_pc = new rtcdcpp::PeerConnection(config, onLocalIceCandidate, onDataChannel); void *responder = zmq_socket (child_context, ZMQ_REP); char bind_path[30]; snprintf(bind_path, sizeof(bind_path), "ipc:///tmp/librtcdcpp%d", getpid()); int rc1 = zmq_bind (responder, bind_path); //printf("\nCreated file %s\n", bind_path); assert (rc1 == 0); int command; while(alive) { zmq_recv (responder, &command, sizeof(command), 0); //printf("\nReceived command %d in process %d\n", command, getpid()); switch(command) { case DESTROY_PC: sendSignal(responder); // Respond. _destroyPeerConnection(child_pc); break; case PARSE_SDP: { // send dummy response on command socket. This means it can start sending arguments sendSignal(responder); // Wait for arg. (which is length) size_t length; zmq_recv (responder, &length, sizeof(length), 0); // Wait for response // Ask for actual content in our response using dummy signal sendSignal(responder); char* parse_sdp_arg = (char *) calloc(sizeof(char), length + 1); zmq_recv (responder, parse_sdp_arg, length, 0); parse_sdp_arg[length] = '\0'; _ParseOffer(child_pc, parse_sdp_arg); free(parse_sdp_arg); sendSignal(responder); } break; case GENERATE_OFFER: { char* offer; offer = _GenerateOffer(child_pc); size_t length = strlen(offer); zmq_send (responder, &length, sizeof(length), 0); // Respond with length of generate offer signalSink(responder); // Wait for next dummy REQ to send the content zmq_send (responder, offer, length, 0); // Respond with content } break; case GENERATE_ANSWER: { char* answer; answer = _GenerateAnswer(child_pc); size_t length = strlen(answer); zmq_send (responder, &length, sizeof(length), 0); signalSink(responder); zmq_send (responder, answer, length, 0); } break; case SET_REMOTE_ICE_CAND: { bool ret_bool; sendSignal(responder); // Respond with dummy signal to get length size_t length; zmq_recv (responder, &length, sizeof(length), 0); sendSignal(responder); // Respond with dummy signal to get content char* candidate_sdp_arg = (char *) calloc(sizeof(char), length + 1); zmq_recv (responder, candidate_sdp_arg, length, 0); candidate_sdp_arg[length] = '\0'; ret_bool = _SetRemoteIceCandidate(child_pc, candidate_sdp_arg); free(candidate_sdp_arg); zmq_send (responder, &ret_bool, sizeof(ret_bool), 0); // Respond with return value } break; case SET_REMOTE_ICE_CANDS: { GArray *args_garray; //GArray // ! // Send signal to send GArray sendSignal(responder); GArray *candidate_sdps_arg; candidate_sdps_arg = (GArray *) malloc(sizeof(GArray)); zmq_recv (responder, candidate_sdps_arg, sizeof(candidate_sdps_arg), 0); bool ret_bool = _SetRemoteIceCandidates(child_pc, candidate_sdps_arg); signalSink(responder); zmq_send (responder, &ret_bool, sizeof(ret_bool), 0); } break; case CREATE_DC: { sendSignal(responder); // Get label length size_t label_arg_length; size_t proto_arg_length; zmq_recv(responder, &label_arg_length, sizeof(label_arg_length), 0); sendSignal(responder); // req proto length zmq_recv(responder, &proto_arg_length, sizeof(proto_arg_length), 0); sendSignal(responder); // req label char* label_arg = (char*) malloc(label_arg_length + 1); char* proto_arg = (char*) malloc(proto_arg_length + 1); zmq_recv(responder, label_arg, label_arg_length, 0); (label_arg)[label_arg_length] = '\0'; sendSignal(responder); // req proto zmq_recv(responder, proto_arg, proto_arg_length, 0); (proto_arg)[proto_arg_length] = '\0'; sendSignal(responder); u_int8_t chan_type; zmq_recv(responder, &chan_type, sizeof(chan_type), 0); sendSignal(responder); u_int32_t reliability; zmq_recv(responder, &reliability, sizeof(reliability), 0); child_dc = (DataChannel *) malloc(sizeof(DataChannel *)); child_dc = _CreateDataChannel(child_pc, label_arg, proto_arg, chan_type, reliability); int pid = getpid(); zmq_send(responder, &pid, sizeof(pid), 0); } break; case CLOSE_DC: _closeDataChannel(child_dc); sendSignal(responder); alive = false; //! break; case GET_DC_SID: u_int16_t sid; sid = _getDataChannelStreamID(child_dc); zmq_send(responder, &sid, sizeof(sid), 0); break; case GET_DC_TYPE: u_int8_t dc_type; dc_type = _getDataChannelType(child_dc); zmq_send(responder, &dc_type, sizeof(dc_type), 0); break; case GET_DC_LABEL: { const char* chan_label; chan_label = _getDataChannelLabel(child_dc); size_t label_len = strlen(chan_label); zmq_send (responder, &label_len, sizeof(label_len), 0); signalSink(responder); zmq_send (responder, chan_label, label_len, 0); } break; case GET_DC_PROTO: { const char* chan_proto; chan_proto = _getDataChannelProtocol(child_dc); size_t proto_len = strlen(chan_proto); zmq_send (responder, &proto_len, sizeof(proto_len), 0); signalSink(responder); zmq_send (responder, chan_proto, proto_len, 0); } break; case SEND_STRING: { sendSignal(responder); size_t send_len; zmq_recv (responder, &send_len, sizeof(send_len), 0); char send_str[send_len]; send_str[send_len] = '\0'; sendSignal(responder); zmq_recv (responder, send_str, send_len, 0); bool ret_bool = _SendString(child_dc, send_str); zmq_send (responder, &ret_bool, sizeof(bool), 0); } break; case SEND_BINARY: // ! { u_int8_t len; sendSignal(responder); //req length zmq_recv (responder, &len, sizeof(len), 0); u_int8_t send_stuff[len]; sendSignal(responder); zmq_recv (responder, send_stuff, len, 0); bool ret_bool = _SendBinary(child_dc, send_stuff, len); zmq_send (responder, &ret_bool, sizeof(bool), 0); } break; default: alive = false; break; } } while(!relayedOnClose) { sleep(0.3); // Keep child process alive to handle DC close (till onClosed is called) } zmq_close(responder); zmq_ctx_term(child_context); exit(0); } else { // Parent char cb_bind_path[33]; snprintf(cb_bind_path, sizeof(cb_bind_path), "ipc:///tmp/librtcdcpp%d-cb", cpid); zmq_connect (cb_pull_socket, cb_bind_path); zmq_bind (cb_pull_socket, cb_bind_path); //printf("\nCreated file %s\n", cb_bind_path); parent_event_loop->addSocket(cpid, requester); parent_event_loop->add_pull_socket(cpid, cb_pull_socket); parent_event_loop->add_on_candidate(cpid, ice_cb); parent_event_loop->add_on_datachannel(cpid, dc_cb); char connect_path[30]; snprintf(connect_path, sizeof(connect_path), "ipc:///tmp/librtcdcpp%d", cpid); int rc2 = zmq_connect(requester, connect_path); assert (rc2 == 0); pc_info_ret.socket = requester; pc_info_ret.pid = cpid; return pc_info_ret; } } void _waitCallable(int i) { pid_t process_id; process_id = wait(&i); if (process_id == -1) { //printf("\nWait err: %s\n", strerror(errno)); return; } //printf("\nProcess %d has terminated with status code %d\n", process_id, i); if (WIFEXITED(i)) { //printf("\nIt exited normally with status code %d\n", WEXITSTATUS(i)); } if (WIFSIGNALED(i)) { //printf("\nProcess %d exited by signal with sig no %d\n", process_id, WTERMSIG(i)); if (WCOREDUMP(i)) { printf("\nProcess %d exited with a coredump!!\n", process_id); } } if (WIFSTOPPED(i)) { //printf("\nProcess stopped by a trace signal %d\n", WSTOPSIG(i)); } if (WIFCONTINUED(i)) { //printf("\nProcess resumed by SIGCONT signal\n"); } } void processWait() { for (int i : process_status) { _waitCallable(std::ref(i)); //! } } void _destroyPeerConnection(PeerConnection *pc) { delete pc; } void _ParseOffer(PeerConnection* pc, const char* sdp) { std::string sdp_string (sdp); pc->ParseOffer(sdp_string); } void destroyPeerConnection(void *socket) { int command = DESTROY_PC; zmq_send (socket, &command, sizeof(command), 0); signalSink(socket); } void ParseOffer(void *socket, const char *sdp) { int child_command = PARSE_SDP; zmq_send (socket, &child_command, sizeof(child_command), 0); // Send command size_t sdp_length = strlen(sdp); signalSink(socket); zmq_send (socket, &sdp_length, sizeof(sdp_length), 0); signalSink(socket); zmq_send (socket, sdp, sdp_length, 0); signalSink(socket); } char* GenerateOffer(void* socket) { int child_command = GENERATE_OFFER; zmq_send (socket, &child_command, sizeof(child_command), 0); // Send command request // Response will contain length of generated offer size_t* length = (size_t *) malloc(sizeof(size_t)); if (zmq_recv (socket, length, sizeof(length), 0) == -1) { //printf("\nGenerate offer length receive error: %d\n", errno); return NULL; } sendSignal(socket); // dummy request for content char* recv_offer = (char*) malloc(*length + 1); recv_offer[*length] = '\0'; zmq_recv (socket, recv_offer, *length, 0); free(length); return recv_offer; } char* GenerateAnswer(void *socket) { int command = GENERATE_ANSWER; zmq_send (socket, &command, sizeof(command), 0); size_t length; if (zmq_recv (socket, &length, sizeof(length), 0) == -1) { //printf("\nGenerate answer length receive error: %d\n", errno); return NULL; } sendSignal(socket); char *answer = (char *) malloc(length + 1); zmq_recv (socket, answer, length, 0); answer[length] = '\0'; return answer; } bool SetRemoteIceCandidate(void *socket, const char* candidate_sdp) { int command = SET_REMOTE_ICE_CAND; zmq_send (socket, &command, sizeof(command), 0); signalSink(socket); size_t candidate_sdp_len = strlen(candidate_sdp); zmq_send (socket, &candidate_sdp_len, sizeof(candidate_sdp_len), 0); signalSink(socket); // send content zmq_send (socket, candidate_sdp, candidate_sdp_len, 0); // Get response that contains return boolean bool ret_val; zmq_recv (socket, &ret_val, sizeof(ret_val), 0); return ret_val; } bool SetRemoteIceCandidates(void *socket, const GArray* candidate_sdps) { //return false; // WIP int command = SET_REMOTE_ICE_CANDS; zmq_send (socket, &command, sizeof(command), 0); // Send command request signalSink(socket); zmq_send (socket, candidate_sdps, sizeof(candidate_sdps), 0); bool ret_val; zmq_recv (socket, &ret_val, sizeof(ret_val), 0); return ret_val; } int CreateDataChannel(void* socket, const char* label, const char* protocol, u_int8_t chan_type, u_int32_t reliability) { int command = CREATE_DC; zmq_send (socket, &command, sizeof(command), 0); signalSink(socket); // send lengths size_t label_length = strlen(label); size_t protocol_length = strlen(protocol); zmq_send (socket, &label_length, sizeof(label_length), 0); signalSink(socket); zmq_send (socket, &protocol_length, sizeof(protocol_length), 0); signalSink(socket); zmq_send (socket, label, label_length, 0); signalSink(socket); zmq_send (socket, protocol, protocol_length, 0); signalSink(socket); zmq_send (socket, &chan_type, sizeof(chan_type), 0); signalSink(socket); zmq_send (socket, &reliability, sizeof(reliability), 0); int pid; zmq_recv (socket, &pid, sizeof(pid), 0); return pid; }; void closeDataChannel(void* socket) { printf("\nSent close\n"); int command = CLOSE_DC; zmq_send (socket, &command, sizeof(command), 0); signalSink(socket); } u_int16_t getDataChannelStreamID(void* socket, DataChannel* dc) { int command = GET_DC_SID; u_int16_t sid; zmq_send (socket, &command, sizeof(command), 0); zmq_recv (socket, &sid, sizeof(sid), 0); return sid; } u_int8_t getDataChannelType(void* socket, DataChannel *dc) { u_int8_t dc_type; int command = GET_DC_TYPE; zmq_send (socket, &command, sizeof(command), 0); zmq_recv (socket, &dc_type, sizeof(dc_type), 0); return dc_type; } const char* getDataChannelLabel(void* socket, DataChannel *dc) { int command = GET_DC_LABEL; zmq_send (socket, &command, sizeof(command), 0); size_t label_len; zmq_recv (socket, &label_len, sizeof(label_len), 0); sendSignal(socket); char label[label_len]; zmq_recv (socket, label, label_len, 0); char* label_ptr = label; return label_ptr; } const char* getDataChannelProtocol(void *socket, DataChannel *dc) { int command = GET_DC_PROTO; zmq_send (socket, &command, sizeof(command), 0); size_t proto_len; zmq_recv (socket, &proto_len, sizeof(proto_len), 0); sendSignal(socket); char proto[proto_len]; zmq_recv (socket, proto, proto_len, 0); char* proto_ptr = proto; return proto_ptr; } bool SendString(void* socket, const char* msg) { int command = SEND_STRING; zmq_send (socket, &command, sizeof(command), 0); signalSink(socket); size_t send_len = strlen(msg); // Send length of our msg zmq_send (socket, &send_len, sizeof(send_len), 0); signalSink(socket); zmq_send (socket, msg, send_len, 0); bool ret_val; zmq_recv (socket, &ret_val, sizeof(ret_val), 0); return ret_val; } bool SendBinary(void* socket, DataChannel *dc, const u_int8_t *msg, int len) { int command = SEND_BINARY; zmq_send (socket, &command, sizeof(command), 0); signalSink(socket); // Send length of our msg zmq_send (socket, &len, sizeof(len), 0); signalSink(socket); zmq_send (socket, msg, len, 0); bool ret_val; zmq_recv (socket, &ret_val, sizeof(ret_val), 0); return ret_val; } void SetOnOpen(int pid, cb_event_loop* cb_event_loop, open_cb on_open_cb) { cb_event_loop->add_on_open(pid, on_open_cb); } void SetOnStringMsgCallback(int pid, cb_event_loop* cb_event_loop, on_string_msg recv_str_cb) { cb_event_loop->add_on_string(pid, recv_str_cb); } void SetOnBinaryMsgCallback(void *socket, on_binary_msg msg_binary_cb) { //TODO: SetOnBinaryMsgCallback } void SetOnErrorCallback(void *socket, DataChannel *dc, on_error error_cb) { //TODO: SetOnErrorCallback } void SetOnClosedCallback(int pid, cb_event_loop* cb_event_loop, on_close close_cb) { cb_event_loop->add_on_close(pid, close_cb); } char* _GenerateOffer(PeerConnection *pc) { std::string ret_val; ret_val = pc->GenerateOffer(); char* ret_val1 = (char*) malloc(ret_val.size()); snprintf(ret_val1, ret_val.size(), ret_val.c_str()); return ret_val1; } char* _GenerateAnswer(PeerConnection *pc) { std::string ret_val; ret_val = pc->GenerateAnswer(); char* ret_val1 = (char*) malloc(ret_val.size()); snprintf(ret_val1, ret_val.size(), ret_val.c_str()); return ret_val1; } bool _SetRemoteIceCandidate(PeerConnection *pc, const char* candidate_sdp) { std::string candidate_sdp_string (candidate_sdp); return pc->SetRemoteIceCandidate(candidate_sdp_string); } bool _SetRemoteIceCandidates(PeerConnection *pc, const GArray* candidate_sdps) { std::vector<std::string> candidate_sdps_vec; for(int i = 0; i <= candidate_sdps->len; i++) { std::string candidate_sdp_string (&g_array_index(candidate_sdps, char, i)); candidate_sdps_vec.emplace_back(candidate_sdp_string); } return pc->SetRemoteIceCandidates(candidate_sdps_vec); } DataChannel* _CreateDataChannel(PeerConnection *pc, char* label, char* protocol, u_int8_t chan_type, u_int32_t reliability) { std::string label_string (label); std::string protocol_string (protocol); free(label); free(protocol); if (protocol_string.size() > 0) { return pc->CreateDataChannel(label_string, protocol_string, chan_type, reliability).get(); } else { return pc->CreateDataChannel(label_string, protocol_string = "", chan_type, reliability).get(); } } u_int16_t _getDataChannelStreamID(DataChannel *dc) { return dc->GetStreamID(); } u_int8_t _getDataChannelType(DataChannel *dc) { return dc->GetChannelType(); } const char* _getDataChannelLabel(DataChannel *dc) { std::string dc_label_string; dc_label_string = dc->GetLabel(); return dc_label_string.c_str(); } const char* _getDataChannelProtocol(DataChannel *dc) { std::string dc_proto_string; dc_proto_string = dc->GetProtocol(); return dc_proto_string.c_str(); } bool _SendString(DataChannel *dc, const char* msg) { std::string message (msg); return dc->SendString(message); } bool _SendBinary(DataChannel *dc, u_int8_t *msg, int len) { return dc->SendBinary(msg, len); } void _closeDataChannel(DataChannel *dc) { dc->Close(); } }
2280902d4dcddf1b15f358f61443d340b7a49508
[ "CMake", "Markdown", "Python", "C", "C++", "Shell" ]
18
Python
zsmweb/librtcdcpp
79934214aba4d163cfe09dd5842409a68b356234
0aac382ff29519e3a69b91d6f6c92c6b4ece0342
refs/heads/master
<file_sep>echo "Enter the number" read n s=0 r=0 while [ $n -ne 0 ] do r=$(($n % 10)) n=$(($n / 10)) s=$(($s + $r)) done echo "The sum of digit of a number is" $s
ba939ef680575cf3a64cfcd3f7b8765aa0aeb624
[ "Shell" ]
1
Shell
athirarejimca/Exam
e6629c4bfad3803a73f8fa948a356cffe1ab5512
ddd3b27f81da7d3979ae871e305529af15f809bb
refs/heads/master
<repo_name>Cethy/gatsby-starter-portfolio-emilia<file_sep>/src/components/ProjectPagination.js import React from 'react'; import styled from 'styled-components'; import Link from 'gatsby-link'; import * as palette from '../../config/Style'; import arrowLeft from './left-chevron.svg'; import arrowRight from './right-chevron.svg'; const Wrapper = styled.div` display: flex; max-width: ${palette.MAX_WIDTH}px; margin: 6rem auto; a { color: ${palette.COLOR}; display: flex; align-items: center; font-size: 1.25rem; } justify-items: center; `; const Prev = styled.div` img { width: 25px; height: 25px; margin: 0 1rem 0 0; } `; const Next = styled.div` img { width: 25px; height: 25px; margin: 0 0 0 1rem; } margin-left: auto; `; const ProjectPagination = ({ next, prev }) => ( <Wrapper> {prev && ( <Prev> <Link to={prev.fields.slug}> <img src={arrowLeft} alt="Arrow Left" /> {prev.frontmatter.title} </Link> </Prev> )} {next && ( <Next> <Link to={next.fields.slug}> {next.frontmatter.title} <img src={arrowRight} alt="Arrow Right" /> </Link> </Next> )} </Wrapper> ); export default ProjectPagination; <file_sep>/content/projects/2017-12-03/index.md --- cover: "./roman-kraft.jpg" date: "2017-12-03" title: "Roman Kraft" areas: - Still --- <file_sep>/src/templates/project.js /* eslint react/no-danger: off */ import React from 'react'; import Helmet from 'react-helmet'; import format from 'date-fns/format'; import Img from 'gatsby-image'; import Overdrive from 'react-overdrive'; import SEO from '../components/SEO'; import ProjectHeader from '../components/ProjectHeader'; import ProjectPagination from '../components/ProjectPagination'; import config from '../../config/SiteConfig'; import * as palette from '../../config/Style'; const Project = props => { const { slug, next, prev } = props.pathContext; const postNode = props.data.project; const images = props.data.images.edges; const project = postNode.frontmatter; const date = format(project.date, config.dateFormat); return ( <div> <Helmet title={`${project.title} | ${config.siteTitle}`} /> <SEO postPath={slug} postNode={postNode} postSEO /> <ProjectHeader avatar={config.avatar} name={config.name} date={date} title={project.title} areas={project.areas} /> <div style={{ padding: `0 ${palette.CONTENT_PADDING}`, margin: '-6rem auto 6rem auto', }} > <div style={{ position: 'relative', maxWidth: palette.MAX_WIDTH_PROJECT_DETAIL, margin: '0 auto', }} > <Overdrive id={`${slug}-cover`}> <Img sizes={project.cover.childImageSharp.sizes} /> </Overdrive> </div> <div dangerouslySetInnerHTML={{ __html: postNode.html }} /> <div style={{ position: 'relative', maxWidth: palette.MAX_WIDTH_PROJECT_DETAIL, margin: '2.75rem auto', }} > {images.map(image => ( <Img sizes={image.node.childImageSharp.sizes} style={{ marginBottom: '2.75rem', }} /> ))} </div> <ProjectPagination next={next} prev={prev} /> </div> </div> ); }; export default Project; /* eslint no-undef: off */ export const pageQuery = graphql` query ProjectPostBySlug($slug: String!, $absolutePathRegex: String!, $absolutePathCover: String!) { images: allFile( filter: { absolutePath: { ne: $absolutePathCover, regex: $absolutePathRegex }, extension: { eq: "jpg" } } ) { edges { node { childImageSharp { sizes(maxWidth: 1600, quality: 90, traceSVG: { color: "#328bff" }) { ...GatsbyImageSharpSizes_withWebp_tracedSVG } resize(width: 800) { src } } } } } project: markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { cover { childImageSharp { sizes(maxWidth: 1600, quality: 90, traceSVG: { color: "#328bff" }) { ...GatsbyImageSharpSizes_withWebp_tracedSVG } resize(width: 800) { src } } } date title areas } } } `; <file_sep>/content/projects/2017-12-05/index.md --- cover: "./marion-michele.jpg" date: "2017-12-05" title: "<NAME>" areas: - Photography - Art --- <file_sep>/content/projects/2017-12-01/index.md --- cover: "./amy-luo.jpg" date: "2017-12-01" title: "<NAME>" areas: - Photography - Art --- <file_sep>/src/layouts/index.js import React from 'react'; import Helmet from 'react-helmet'; import { injectGlobal } from 'styled-components'; import SEO from '../components/SEO'; import Footer from '../components/Footer'; import favicon from './favicon.ico'; import config from '../../config/SiteConfig'; import * as palette from '../../config/Style'; /* eslint no-unused-expressions: off */ injectGlobal` body { background: #16191f; color: ${palette.COLOR}; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } a { color: ${palette.LINK_COLOR}; transition: color .5s; text-decoration: none; } a:hover { text-decoration: none; color: ${palette.LINK_HOVER_COLOR}; } .gatsby-resp-image-wrapper { margin: 2.75rem 0; } `; const TemplateWrapper = props => { const { children } = props; return ( <div> <Helmet title={config.siteTitleAlt} meta={[ { name: 'description', content: 'Gatsby Starter Portfolio - Emilia' }, { name: 'keywords', content: 'gatsby, starter, portfolio, lekoarts' }, ]} > <link rel="shortcut icon" href={favicon} /> </Helmet> <SEO /> {children()} <Footer /> </div> ); }; export default TemplateWrapper; <file_sep>/src/pages/index.js import React from 'react'; import styled from 'styled-components'; import Card from '../components/Card'; import Header from '../components/Header'; import config from '../../config/SiteConfig'; import * as palette from '../../config/Style'; const Grid = styled.div` display: grid; grid-template-columns: repeat(${palette.GRID_COLUMNS}, 1fr); grid-gap: 50px; @media (max-width: 768px) { grid-template-columns: 1fr; } .gatsby-image-outer-wrapper, .gatsby-image-wrapper { position: static !important; } `; const Content = styled.div` margin: -6rem auto 6rem auto; max-width: ${palette.MAX_WIDTH}px; padding: 0px ${palette.CONTENT_PADDING} 1.45rem; position: relative; `; const Index = props => { const projectEdges = props.data.allMarkdownRemark.edges; return ( <div> <Header avatar={config.avatar} name={config.name} location={config.location} socialMedia={config.socialMedia} /> <Content> <Grid> {projectEdges.map(project => ( <Card date={project.node.frontmatter.date} title={project.node.frontmatter.title} cover={project.node.frontmatter.cover.childImageSharp.sizes} path={project.node.fields.slug} areas={project.node.frontmatter.areas} slug={project.node.fields.slug} key={project.node.fields.slug} /> ))} </Grid> </Content> </div> ); }; export default Index; /* eslint no-undef: off */ export const pageQuery = graphql` query HomeQuery { allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { edges { node { fields { slug } frontmatter { cover { childImageSharp { sizes(maxWidth: 850, quality: 90, traceSVG: { color: "#328bff" }) { ...GatsbyImageSharpSizes_withWebp_tracedSVG } } } date title areas } } } } } `; <file_sep>/src/components/Footer.js import React from 'react'; import styled from 'styled-components'; import * as palette from '../../config/Style'; const Content = styled.p` color: ${palette.SECONDARY_COLOR}; padding: 0 ${palette.CONTENT_PADDING}; text-align: center; `; const Footer = () => ( <Content> &copy; 2018 by Gatsby Starter Portfolio - Emma. Pictures by{' '} <a href="https://unsplash.com/" target="_blank" rel="noopener noreferrer"> Unsplash </a>. Design by{' '} <a href="https://www.lekoarts.de" target="_blank" rel="noopener noreferrer"> LekoArts </a>. <br /> Have a look at the{' '} <a href="https://github.com/LeKoArts/gatsby-starter-portfolio-emilia" target="_blank" rel="noopener noreferrer"> Github repository </a>! </Content> ); export default Footer; <file_sep>/content/projects/2017-12-04/index.md --- cover: "./matt-cannon.jpg" date: "2017-12-04" title: "<NAME>" areas: - Photography --- <file_sep>/README.md ![](https://i.imgur.com/xPj0ICn.png) ### Modifications from original repository - [x] Automatically add local jpg files to project page ; # Gatsby Starter Portfolio: Emilia A portfolio starter for [Gatsby](https://www.gatsbyjs.org/). The target audience are designers and photographers. [Demo Website](https://portfolio-emilia.netlify.com/) - Focus on big images - Dark theme - Image grid powered by CSS Grid - One-Page layout with sub-pages for projects ## Why? If you want to quickly bootstrap a design/photography portfolio or use it as a foundation for your personal site the *gatsby-starter-portfolio* are a perfect fit for you! The project's goal is to offer minimalistic and fast websites. I hope you like my starters and create something awesome! To see some of my work you can visit my [website](https://www.lekoarts.de) or support me on [Patreon](https://www.patreon.com/lekoarts) to get some neat rewards (4K images, project files, tutorial insights). Also check out the other *gatsby-starter-portfolio*: - [gatsby-starter-portfolio-emma](https://github.com/LeKoArts/gatsby-starter-portfolio-emma) ## Features - Configurable - Use the SiteConfig.js to easily change the most important information - Google Fonts - Use the Style.js to configure your CSS - Projects in Markdown - Element Transitions with [React Overdrive](https://github.com/berzniz/react-overdrive) - Image Grid with CSS Grid - [HeroPatterns](http://www.heropatterns.com/) Header - Styled components - Google Analytics Support - SEO - Sitemap - Schema.org JSONLD - OpenGraph Tags - Twitter Tags - Offline Support - WebApp Manifest Support - Typography.js - Responsive images - The right image size for every screen size - Traced SVG Loading (Lazy-Loading) - WebP Support ## Getting Started Check your development environment! You'll need [Node.js](https://nodejs.org/en/), the [Gatsby CLI](https://www.gatsbyjs.org/docs/) and [node-gyp](https://github.com/nodejs/node-gyp#installation) installed. The official Gatsby website also lists two articles regarding this topic: - [Gatsby on Windows](https://www.gatsbyjs.org/docs/gatsby-on-windows/) - [Check your development environment](https://www.gatsbyjs.org/tutorial/part-one/#check-your-development-environment) To copy and install this starter run this command (with "project-name" being the name of your folder you wish to install it in): ``` gatsby new project-name https://github.com/LeKoArts/gatsby-starter-portfolio-emilia npm run dev ``` ### Adding a new project - Create a new folder in ``content/projects`` with the current date (Format: YYYY-MM-DD) - Create a new markdown file, add the frontmatter (use the same date format) - Reference the image you want to be shown in the grid and as the first image on the project as ``cover`` - Add your other images below the frontmatter (you can also include text) If you're still unsure have a look at the already existing examples. ### Adding new features/plugins You can add other features by having a look at the offical [plugins page](https://www.gatsbyjs.org/docs/plugins/) ### Building your site ``` npm run build ``` Copy the content of the ``public`` folder to your webhost or use a website like Netlify which automates that for you. ## Configuration You can configure your setup in ``config/SiteConfig``: ```JS module.exports = { pathPrefix: '/', // Prefix for all links. If you deploy your site to example.com/portfolio your pathPrefix should be "portfolio" siteTitle: 'Emilia', // Navigation and Site Title siteTitleAlt: 'Emilia - Gatsby Starter Portfolio', // Alternative Site title for SEO siteUrl: 'https://upbeat-edison-0598aa.netlify.com', // Domain of your site. No trailing slash! siteLanguage: 'en', // Language Tag on <html> element siteLogo: '/logos/logo-1024.png', // Used for SEO and manifest siteDescription: 'Dark One-Page Portfolio with Cards & detailed project views', siteFBAppID: '123456789', // Facebook App ID userTwitter: 'emilia', // Twitter Username ogSiteName: 'emilia', // Facebook Site Name googleAnalyticsID: 'UA-12345689-1', // Date format used in your project // More information here: https://date-fns.org/v1.29.0/docs/format dateFormat: 'DD.MM.YYYY', // Manifest and Progress color themeColor: '#3498DB', backgroundColor: '#2b2e3c', // Settings for typography.js headerFontFamily: 'Open Sans', bodyFontFamily: 'Merriweather', baseFontSize: '16px', // Your information avatar: '/logos/social.png', name: 'LekoArts', location: 'Germany', socialMedia: [ { url: 'https://www.facebook.com/lekoarts.de', name: 'Facebook', }, { url: 'https://www.instagram.com/lekoarts.de', name: 'Instagram', }, ], }; ``` You can also configure the styling by editing the ``config/Style`` file: ```JS // You can grab your own pattern here: // http://www.heropatterns.com/ export const BG_PATTERN = `data:image/svg+xml,%3Csvg width='52' height='26' viewBox='0 0 52 26' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%2316191f' fill-opacity='0.4'%3E%3Cpath d='M10 10c0-2.21-1.79-4-4-4-3.314 0-6-2.686-6-6h2c0 2.21 1.79 4 4 4 3.314 0 6 2.686 6 6 0 2.21 1.79 4 4 4 3.314 0 6 2.686 6 6 0 2.21 1.79 4 4 4v2c-3.314 0-6-2.686-6-6 0-2.21-1.79-4-4-4-3.314 0-6-2.686-6-6zm25.464-1.95l8.486 8.486-1.414 1.414-8.486-8.486 1.414-1.414z' /%3E%3C/g%3E%3C/g%3E%3C/svg%3E`; export const BG_COLOR = '#16191f'; export const COLOR = 'white'; export const SECONDARY_COLOR = '#b6b6b6'; export const LINK_COLOR = '#328bff'; export const LINK_HOVER_COLOR = '#79a8ff'; // max-width for the index page (header + grid) export const MAX_WIDTH = '1600'; // your maxWidth for gatsby-remark-images in gatsby-config.js MUST have the same width! export const MAX_WIDTH_PROJECT_DETAIL = 1600; export const GRID_COLUMNS = '2'; export const CONTENT_PADDING = '1.0875rem'; ``` **Attention:** You also need to edit ``static/robots.txt`` to include your domain! <file_sep>/src/components/Card.js import React from 'react'; import format from 'date-fns/format'; import styled from 'styled-components'; import Img from 'gatsby-image'; import Link from 'gatsby-link'; import Overdrive from 'react-overdrive'; import config from '../../config/SiteConfig'; import * as palette from '../../config/Style'; const CardItem = styled(Link)` min-height: 500px; position: relative; overflow: hidden; box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3), 0 15px 12px rgba(0, 0, 0, 0.2); display: flex; flex-direction: column; justify-content: space-between; color: ${palette.COLOR}; transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55); &:after { content: ''; position: absolute; display: block; width: 100%; height: 100%; left: 0; right: 0; bottom: 0; background: linear-gradient( to bottom, rgba(0, 0, 0, 0.75) 0%, rgba(0, 0, 0, 0) 20%, rgba(0, 0, 0, 0) 80%, rgba(0, 0, 0, 0.75) 100% ); transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55); opacity: 0; } &:hover { transform: translateY(-15px); color: white; &:after { opacity: 1; } box-shadow: 0 35px 48px rgba(0, 0, 0, 0.3), 0 30px 20px rgba(0, 0, 0, 0.2); } `; const Cover = styled.div` width: 100%; height: 100%; position: absolute; div { overflow: hidden; } `; const Header = styled.div` display: flex; flex-direction: row; flex-wrap: no-wrap; justify-content: space-between; padding: 1rem; z-index: 10; transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55); opacity: 0; ${CardItem}:hover & { opacity: 1; } `; const DateWrapper = styled.div` font-size: 0.9rem; `; const Data = styled.div` z-index: 10; position: relative; width: 100%; `; const Content = styled.div` padding: 1rem; position: relative; transition: all 0.4s cubic-bezier(0.68, -0.55, 0.265, 1.55); opacity: 0; ${CardItem}:hover & { opacity: 1; } `; const Areas = styled.span` font-size: 0.75rem; `; const AreaItem = styled.span` &:not(:last-child) { margin-right: 0.25rem; &:after { content: ','; } } `; const Name = styled.h2` margin-top: 1.25rem; margin-bottom: 0; `; const Card = ({ path, cover, date, areas, title, slug }) => ( <Overdrive id={`${slug}-cover`}> <CardItem to={path}> <Cover> <Img sizes={cover} /> </Cover> <Header> <DateWrapper> <Date date={date} /> </DateWrapper> <Areas>{areas.map(area => <AreaItem key={area}>{area}</AreaItem>)}</Areas> </Header> <Data> <Content> <Name>{title}</Name> </Content> </Data> </CardItem> </Overdrive> ); export default Card; const Date = ({ date }) => { const formatted = format(date, config.dateFormat); return <span>{formatted}</span>; }; <file_sep>/content/projects/2017-12-02/index.md --- cover: "./mona-magnussen.jpg" date: "2017-12-02" title: "<NAME>" areas: - Photography --- <file_sep>/src/components/Header.js import React from 'react'; import styled from 'styled-components'; import Overdrive from 'react-overdrive'; import * as palette from '../../config/Style'; const Wrapper = styled.div` background-color: #000000; background-image: url("${palette.BG_PATTERN}"); display: flex; position: relative; `; const Content = styled.div` margin: 0 auto; max-width: ${palette.MAX_WIDTH}px; padding: 3rem 1.0875rem 10rem 1.0875rem; color: ${palette.SECONDARY_COLOR}; text-align: center; `; const Avatar = styled.div` height: 125px; width: 125px; margin: 0 auto; image-rendering: -moz-crisp-edges; image-rendering: -o-crisp-edges; image-rendering: -webkit-optimize-contrast; -ms-interpolation-mode: nearest-neighbor; img { border-radius: 50%; } `; const Name = styled.h1` margin: 1rem 0 0.25rem 0; color: ${palette.COLOR}; `; const Location = styled.div` font-size: 0.9rem; display: flex; align-items: center; justify-content: center; `; const SocialMedia = styled.div` margin-top: 2rem; a { margin: 0 0.3rem; } `; const Header = ({ avatar, name, location, socialMedia }) => ( <Wrapper> <Content> <Overdrive id="avatar-to-back"> <Avatar> <img src={avatar} alt={name} /> </Avatar> </Overdrive> <Overdrive id="name-to-back"> <Name>{name}</Name> </Overdrive> <Location>{location}</Location> <SocialMedia> {socialMedia.map(social => ( <a key={social.name} href={social.url} rel="noopener noreferrer" target="_blank"> {social.name} </a> ))} </SocialMedia> </Content> </Wrapper> ); export default Header;
3b751dabe68573c1e9aa2ce6889e2897273681da
[ "JavaScript", "Markdown" ]
13
JavaScript
Cethy/gatsby-starter-portfolio-emilia
23632276fd9fc18d83c591ad4c33c9aa53f749fc
c7f76ee6ff57e25ec0fe33dac985d4eb6e48a405
refs/heads/master
<repo_name>fycisc/teach<file_sep>/variables.py # -*- coding: utf-8 -*- __author__ = 'feiyicheng' import urllib2 import string deltatime = 5 classes = [ ('http://mis.teach.ustc.edu.cn/querystubykcbjh.do?tag=jg&kcbjh=011X1902&xnxq=20142&kczw=Java%C8%ED%BC%FE%BF%AA%B7%A2%BB%F9%B4%A1',100,'java' , 'http://mis.teach.ustc.edu.cn/xkgcinsert.do?xnxq=20142&kcbjbh=011X1902&kcid=2599&kclb=0&kcsx=4&cxck=0&zylx=01&gxkfl=null&xlh=1&sjpdm=35&kssjdm=null', '011X1902'), ('http://mis.teach.ustc.edu.cn/querystubykcbjh.do?tag=jg&kcbjh=011X1901&xnxq=20142&kczw=Java%C8%ED%BC%FE%BF%AA%B7%A2%BB%F9%B4%A1',60,'java' , 'http://mis.teach.ustc.edu.cn/xkgcinsert.do?xnxq=20142&kcbjbh=011X1901&kcid=2599&kclb=0&kcsx=4&cxck=0&zylx=01&gxkfl=null&xlh=1&sjpdm=25&kssjdm=null', '011X1901'), ('http://mis.teach.ustc.edu.cn/querystubykcbjh.do?tag=jg&kcbjh=022X2601&xnxq=20142&kczw=%CC%EC%CC%E5%CE%EF%C0%ED%B8%C5%B9%DB',200,'天体物理概观' , 'http://mis.teach.ustc.edu.cn/xkgcinsert.do?xnxq=20142&kcbjbh=022X2601&kcid=5326&kclb=0&kcsx=4&cxck=0&zylx=01&gxkfl=null&xlh=1&sjpdm=55&kssjdm=null','022X2601'), ('http://mis.teach.ustc.edu.cn/querystubykcbjh.do?tag=jg&kcbjh=103X0101&xnxq=20142&kczw=%B4%AB%CD%B3%BD%A1%C9%ED',30,'传统健身' , 'http://mis.teach.ustc.edu.cn/xkgcinsert.do?xnxq=20142&kcbjbh=103X0101&kcid=4707&kclb=0&kcsx=4&cxck=0&zylx=01&gxkfl=null&xlh=1&sjpdm=15&kssjdm=null','103X0101'), ('http://mis.teach.ustc.edu.cn/querystubykcbjh.do?tag=jg&kcbjh=601X3401&xnxq=20142&kczw=%B5%E7%D7%D3%D0%C5%CF%A2%BC%EC%CB%F7',100,'电子信息检索' , 'http://mis.teach.ustc.edu.cn/xkgcinsert.do?xnxq=20142&kcbjbh=601X3401&kcid=5184&kclb=0&kcsx=4&cxck=0&zylx=01&gxkfl=null&xlh=1&sjpdm=44&kssjdm=null','601X3401'), ('http://mis.teach.ustc.edu.cn/querystubykcbjh.do?tag=jg&kcbjh=103X2901&xnxq=20142&kczw=%C9%E7%BD%BB%CE%E8%B5%B8(%C4%D0%B2%BD)',28,'社交舞蹈' , 'http://mis.teach.ustc.edu.cn/xkgcinsert.do?xnxq=20142&kcbjbh=103X2901&kcid=4734&kclb=0&kcsx=4&cxck=0&zylx=01&gxkfl=null&xlh=1&sjpdm=44&kssjdm=null HTTP/1.1','103X2901'), ] headers = [ ('Host', 'mis.teach.ustc.edu.cn'), ('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), ('Cookie','JSESSIONID=08181E4764EE884E408DE31431817598; __utma=63887786.691193098.1419693077.1421477665.1421675729.11; __utmz=63887786.1419693077.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); _gscu_1103646635=19159380twnlr411'), ('User-Agent','Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/600.3.18 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.18'), ('Accept-Language','zh-cn'), ('Accept-Encoding','gzip, deflate'), ('Connection','keep-alive'), ] inserturlsample = 'http://mis.teach.ustc.edu.cn/xkgcinsert.do?xnxq=20142&kcbjbh=011X1901&kcid=2599&kclb=0&kcsx=4&cxck=0&zylx=01&gxkfl=null&xlh=1&sjpdm=25&kssjdm=null' opener = urllib2.build_opener() opener.addheaders = headers # content = opener.open(inserturlsample).read() # print(content) # print(content.find('<td class="bg5" align="center" width="10%">'+ str(101) +'</td>')) <file_sep>/testmedia.py __author__ = 'feiyicheng' import pyglet def playCelebrate(): media = pyglet.resource.media('believe_in_yourself.mp3') media.play() pyglet.app.run() def playNotify(): media = pyglet.resource.media( 'hhh.mp4' ) media.play( ) pyglet.app.run( )
bc0de97a6b46b200b2afa6dfd37bba6ec7ef536d
[ "Python" ]
2
Python
fycisc/teach
b0f669f3d3130a7bacbe5fa75f98ae0e4951303c
e43ae2eda33ece4f43db8dca5b9709423883b790
refs/heads/master
<repo_name>topherb99/note_JS<file_sep>/src/note-list-controller.js (function(exports) { function NoteListController(notelist) { noteListView = new NoteListView(notelist) }; NoteListController.prototype.addHTML = function () { element = document.getElementById("app") element.innerHTML = noteListView.return(); return element.innerHTML }; exports.NoteListController = NoteListController })(this); <file_sep>/spec/noteSpec.js function testReturnsNote() { var note = new Note("test text"); eval.isTrue(note.returnNote() === "test text"); }; testReturnsNote(); <file_sep>/spec/noteListViewSpec.js function testNoteListViewWithNoNotes() { var noteBook = new NoteBook(); var noteListView = new NoteListView(noteBook); eval.isTrue(noteListView.return() === ""); } testNoteListViewWithNoNotes(); function testNoteListViewWithOneNote() { var note1 = new Note('test note 1'); var noteBook = new NoteBook(); noteBook.addNote(note1); var noteListView = new NoteListView(noteBook); eval.isTrue(noteListView.return() === "<ul><li><div>test note 1</div></li></ul>"); } testNoteListViewWithOneNote(); function testNoteListViewWithTwoNotes() { var note1 = new Note('test note 1'); var note2 = new Note('test note 2'); var noteBook = new NoteBook(); noteBook.addNote(note1); noteBook.addNote(note2); var noteListView = new NoteListView(noteBook); eval.isTrue(noteListView.return() === "<ul><li><div>test note 1</div></li><li><div>test note 2</div></li></ul>"); } testNoteListViewWithTwoNotes(); <file_sep>/src/note-list-view.js (function(exports) { function NoteListView(noteBook) { this.notes = noteBook.returnNotes(); }; NoteListView.prototype.return = function() { if (this.notes.length === 0) { return ""; } else { return "<ul><li><div>" + this.notes.join("</div></li><li><div>") + "</div></li></ul>"; } }; exports.NoteListView = NoteListView; })(this); <file_sep>/spec/singleNoteViewSpec.js function testSingleHTML() { var note1 = new Note('test note 1'); var singleNoteView = new SingleNoteView(note1); eval.isTrue(singleNoteView.returnSingleHTML() === "<div>" + note1.text + "</div>") } testSingleHTML(); <file_sep>/spec/noteListSpec.js function testReturnsNoteList() { var note1 = new Note('text 1'); var note2 = new Note('text 2'); var noteBook = new NoteBook(); noteBook.addNote(note1); noteBook.addNote(note2); eval.isTrue(noteBook.returnNotes()[0] === "text 1"); eval.isTrue(noteBook.returnNotes()[1] === "text 2"); }; testReturnsNoteList();
8bd2e76d2e95545c62e88381e56c0428f1477565
[ "JavaScript" ]
6
JavaScript
topherb99/note_JS
b00916d5f78a3f3638d56ce029d3300ae04e3620
c4120462c527a51e19c186e5493a22308bf83250
refs/heads/master
<repo_name>touv/node-xml-distiller<file_sep>/lib/xml.js 'use strict'; var Streamer = require('./streamer.js'); exports.stringify = function (input, sep) { } exports.parse = function (input, sep) { } exports.createStream = function (options) { return new Streamer(options); } <file_sep>/bin/xmldistiller #!/usr/bin/env node /* vim: set ft=javascript: */ "use strict"; var Distiller = require(__dirname + '/..') , fs = require('fs') , CSV = require('csv-string') ; var stream = Distiller.createStream(); stream.on('data', function(data) { process.stdout.write(CSV.stringify(data)) }); process.stdin.resume(); process.stdin.setEncoding('utf8'); process.stdin.pipe(stream); <file_sep>/test/xml.js /*jshint node:true,laxcomma:true*/ /* global describe, it */ 'use strict'; var should = require('should') , cXML = require('../') , fs = require('fs') , path = require('path') , assert = require('assert') ; describe('cXML ', function () { describe('#0a', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b'); assert.equal(d[1], '1'); } else if (i === 2) { assert.equal(d[0], '/.a/<b'); assert.equal(d[1], '2'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/0a.xml")).pipe(stream) }); }); describe('#0b', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b'); assert.equal(d[1], '1'); } else if (i === 2) { assert.equal(d[0], '/.a/<b'); assert.equal(d[1], '2'); } else if (i === 2) { assert.equal(d[0], '/.a/<b'); assert.equal(d[1], '3'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/0b.xml")).pipe(stream) }); }); describe('#0c', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b/<c'); assert.equal(d[1], '1'); } else if (i === 2) { assert.equal(d[0], '/.a/.b/<c'); assert.equal(d[1], '2'); } else if (i === 3) { assert.equal(d[0], '/.a/.b/<c'); assert.equal(d[1], '3'); } else if (i === 4) { assert.equal(d[0], '/.a/<b/<c'); assert.equal(d[1], '4'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/0c.xml")).pipe(stream) }); }); describe('#1a', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b'); assert.equal(d[1], 'x1'); } else if (i === 2) { assert.equal(d[0], '/.a/.b/=c'); assert.equal(d[1], 'x2'); } else if (i === 3) { assert.equal(d[0], '/.a/|b'); assert.equal(d[1], 'x3'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/1a.xml")).pipe(stream) }); }); describe('#1b', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b'); assert.equal(d[1], 'y1'); } else if (i === 2) { assert.equal(d[0], '/.a/<b/<c'); assert.equal(d[1], 'y2'); } else if (i === 3) { assert.equal(d[0], '/.a/<b'); assert.equal(d[1], 'y3'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/1b.xml")).pipe(stream) }); }); describe('#1c', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b'); assert.equal(d[1], 'x1'); } else if (i === 2) { assert.equal(d[0], '/.a/.b/=c'); assert.equal(d[1], 'x2'); } else if (i === 3) { assert.equal(d[0], '/.a/|b'); assert.equal(d[1], 'x3'); } else if (i === 4) { assert.equal(d[0], '/.a/<b'); assert.equal(d[1], 'y1'); } else if (i === 5) { assert.equal(d[0], '/.a/<b/<c'); assert.equal(d[1], 'y2'); } else if (i === 6) { assert.equal(d[0], '/.a/<b'); assert.equal(d[1], 'y3'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/1c.xml")).pipe(stream) }); }); describe('#2a', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b/<c/@z'); assert.equal(d[1], '1'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/2a.xml")).pipe(stream) }); }); describe('#2b', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b/<c/@z'); assert.equal(d[1], '1'); } else if (i === 2) { assert.equal(d[0], '/.a/.b/.c'); assert.equal(d[1], '2'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/2b.xml")).pipe(stream) }); }); describe('#2c', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b/<c/@z'); assert.equal(d[1], '1'); } else if (i === 2) { assert.equal(d[0], '/.a/.b/.c'); assert.equal(d[1], '4'); } else if (i === 3) { assert.equal(d[0], '/.a/.b/<c/@z'); assert.equal(d[1], '2'); } else if (i === 4) { assert.equal(d[0], '/.a/.b/.c'); assert.equal(d[1], '5'); } else if (i === 5) { assert.equal(d[0], '/.a/.b/<c/@z'); assert.equal(d[1], '3'); } else if (i === 5) { assert.equal(d[0], '/.a/.b/.c'); assert.equal(d[1], '3'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/2c.xml")).pipe(stream) }); }); describe('#2d', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b/<c/@z'); assert.equal(d[1], '1'); } else if (i === 2) { assert.equal(d[0], '/.a/.b/<c/@z'); assert.equal(d[1], '2'); } else if (i === 3) { assert.equal(d[0], '/.a/.b/<c/@z'); assert.equal(d[1], '3'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/2d.xml")).pipe(stream) }); }); describe('#3a', function () { it('should', function(done) { var i = 0, stream = cXML.createStream(); stream.on('data', function(d) { i++; if (i === 1) { assert.equal(d[0], '/<a/<b/<c'); assert.equal(d[1], '1'); } else if (i === 2) { assert.equal(d[0], '/.a/.b/<d'); assert.equal(d[1], '2'); } else if (i === 3) { assert.equal(d[0], '/.a/<b/<c'); assert.equal(d[1], '3'); } else if (i === 4) { assert.equal(d[0], '/.a/.b/<d'); assert.equal(d[1], '4'); } }); stream.on('finish', function() { done(); }); fs.createReadStream(path.resolve(__dirname, "../dataset/3a.xml")).pipe(stream) }); }); }); <file_sep>/README.md # XML as array FIXME ## Contributors * [<NAME>](https://github.com/touv) # Installation With [npm](http://npmjs.org) do: $ npm install xml-array # Tests Use [mocha](https://github.com/visionmedia/mocha) to run the tests. $ npm install mocha $ mocha test # API Documentation # Also FIXME # License [MIT/X11](https://github.com/touv/node-xml-array/blob/master/LICENSE) <file_sep>/index.js module.exports = require('./lib/xml.js'); <file_sep>/bin/xmlpresser #!/usr/bin/env node /* vim: set ft=javascript: */ "use strict"; var/* coXML = require(__dirname + '/..') , */ debug = function(){} , fs = require('fs') , CSV = require('csv-string') ; var xmlfile = require("path").join(process.cwd(), process.argv[2]) var input = fs.createReadStream(xmlfile, { encoding: "utf8" }) function print (c) { if (!process.stdout.write(CSV.stringify(c))) { input.pause(); } } process.stdout.on("drain", function () { input.resume(); }) /* var stream = coXML.createStream(); stream.on('data', function(data) { print(CSV.stringify(data)) }); input.pipe(stream); */ var options; options = options || {}; options.specialChar = options.specialChar || '$'; var self = { saxStream: null }; var CC = { "normal" : function () { return "/."; }, "newone" : function () { return "/<"; }, "inside" : function () { return "/="; }, "inline" : function () { return "/|"; }, "attr" : function () { return "/@"; }, "comment" : function () { return "/#"; }, } function normalize (x) { return x.replace(CC.newone(), CC.normal()); } var depth = 0, stack = [], open = false; function cvalue(v) { var val = [stack.join(''), v]; debug('cvalue', v, stack); print(val); stack = stack.map(normalize); } self.saxStream = require("sax").createStream(false, {lowercasetags:true, trim:true}) // self.saxStream = require("sax").createStream(true, {trim : true, xmlns : false, position: false}) self.saxStream.on("opentag", function (node) { var oldname = stack[depth]; debug('opentag(1)', depth, stack, oldname); stack = stack.slice(0, depth); ++depth; if (oldname && oldname.slice(2) === node.name) { stack.push(oldname) } else { var cc = open ? CC.inside() : CC.newone() stack.push(cc + node.name); } debug('opentag(2)', depth, stack); Object.keys(node.attributes).forEach(function(key) { stack.push(CC.attr() + key); cvalue(node.attributes[key]); stack.pop(); }); // if (node.isSelfClosing === true) { // --depth; // } }); self.saxStream.on("text", function (value) { open = true; cvalue(value); }); self.saxStream.on("closetag", function (name) { debug('closetag(1)', depth, stack); --depth; open = false; debug('>>>>', stack[depth].slice(0, 2)); if (stack[depth].slice(0, 2) == CC.inside()) { stack.pop(); stack[stack.length-1] = CC.inline() + stack[stack.length-1].slice(2) } else { stack[depth] = CC.newone() + stack[depth].slice(2) } debug('closetag(2)', depth, stack); }); self.saxStream.on("comment", function (value) { print (['#', value]); }); self.saxStream.on("opencdata", function (node) { }); self.saxStream.on("cdata", function (value) { cvalue(value); }); self.saxStream.on("closecdata", function () { }); self.saxStream.on("error", function (e) { // an error happened. console.error('error', e); // clear the error this._parser.error = null this._parser.resume() }); input.pipe(self.saxStream);
e7b201edf247f07dc8b5aadb97097f5b3a149b6e
[ "JavaScript", "Markdown" ]
6
JavaScript
touv/node-xml-distiller
3e1e8488dadf6750c249ea38698adaf12712d8a7
40422d630f4a49f266729111dd6857e1f3ad24f7
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace AdminPanel { public partial class UpdateApplicationForm : Form { LoginInfomation Login; ApplicationData App; public UpdateApplicationForm(LoginInfomation l, ApplicationData a) { InitializeComponent(); Login = l; App = a; } private void UpdateApplicationForm_Load(object sender, EventArgs e) { richTextBox1.Text = App.Changelog; this.Text = string.Format("Update Application ({0})", App.Name); } private void button1_Click(object sender, EventArgs e) { using(OpenFileDialog ofd = new OpenFileDialog()) { ofd.Filter = "Exe|*.exe"; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) filePath.Text = ofd.FileName; } } private void button2_Click(object sender, EventArgs e) { if(!File.Exists(filePath.Text)) { MessageBox.Show("Invalid file."); return; } richTextBox1.Enabled = false; progressBar1.Value = 0; button1.Enabled = false; button2.Enabled = false; using(WebClient wc = new WebClient()) { wc.UploadFileCompleted += wc_UploadFileCompleted; wc.UploadProgressChanged += wc_UploadProgressChanged; wc.UploadFileAsync(new Uri(string.Format("{0}?username={1}&password={2}&changelog={3}&q=updateapplication&id={4}", Login.Server, Login.Username, Login.Password, richTextBox1.Text, App.ID)), filePath.Text); } } void wc_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; } void wc_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e) { try { string resp = System.Text.Encoding.UTF8.GetString(e.Result); XDocument xDoc = XDocument.Parse(resp); var updater = xDoc.Element("updater"); var respEl = updater.Element("response"); throw new Exception(respEl.Attribute("Message").Value); } catch(Exception ex) { MessageBox.Show(ex.Message); this.DialogResult = System.Windows.Forms.DialogResult.OK; } } } } <file_sep><?php include("sqlconnect.php"); include("func.php"); if(empty($_GET["username"]) || (empty($_GET["password"]) && empty($_GET["passwordhash"]))) DieXml("Missing login infomation"); $username = strtolower($_GET["username"]); $password = ""; if(!empty($_GET["password"])) $password = md5($_GET["password"]); else $password = $_GET["passwordhash"]; if($username != $AdminUsername || $password != $AdminPasswordHash) DieXml("Bad login credentials."); //Logged in successfully if(!file_exists($application_storage_folder)) { if(!mkdir($application_storage_folder)) DieXml("Failed to create application_storage_folder: " . $application_storage_folder); } //application_storage_folder folder exists $xml = new SimpleXMLElement("<updater></updater>"); $rXml = $xml->addChild('response'); $query = ""; if(empty($_GET["q"])) DieXml("No query"); $query = strtolower($_GET["q"]); switch($query) { case "checklogin": DieXml("Login success", "1"); break; case "addapplication": if(empty($_GET["name"])) DieXml("No application name."); $name = $_GET["name"]; $pdo_query = $pdo->prepare("SELECT * FROM Applications WHERE ApplicationName=?"); $pdo_query->execute($name); if($pdo_query->rowCount > 0) DieXml("Application alredy exists."); $md5 = md5($name.rand()); if($pdo->exec("SELECT * FROM Applications WHERE AppID='$md5'")->rowCount != 0) $md5 = md5($name.rand()); $pdo_query = $pdo->prepare("INSERT INTO Applications SET AppID=?, ApplicationName=?, ApplicationFileName='Not set'"); $pdo_query->execute(array($md5, $name)); if(!$query_result) DieXml("Failed to add application."); if(!file_exists($application_storage_folder . "/" . $name)) mkdir($application_storage_folder . "/" . $name); $rXml->addAttribute("Success", "1"); $rXml->addAttribute("Key", $md5); die($rXml->asXml()); break; case "listapplications": $table = $sqli->query("SELECT * FROM Applications"); $rXml->addAttribute("Success", "1"); $appList = $rXml->addChild("Applications"); while($row = $table->fetch_row()) { if(!file_exists($application_storage_folder . "/" . $row[0])) mkdir($application_storage_folder . "/" . $row[0]); $location = $application_storage_folder . "/" . $row[0]. "/" .$row[2]; $appXml = $appList->addChild("Application"); $appXml->addAttribute("ApplcationName", $row[0]); $appXml->addAttribute("AppID", $row[1]); $appXml->addAttribute("ApplicationFileName", $row[2]); $appXml->addChild("Changelog", $row[3]); } die($rXml->asXml()); break; case "deleteapplication": if(empty($_GET["id"])) DieXml("No id."); $id = strip_tags(htmlentities($_GET["id"])); $sqli_query = $sqli->prepare("SELECT * FROM Applications WHERE AppID=?"); $sqli_query->bind_param('s', $id); $query_result = $sqli_query->execute(); if($query_result->num_rows < 1) DieXml("Invalid application id" ); $application = $query_result->fetch_array(); if(file_exists($application_storage_folder . "/" . $application["ApplicationName"])) rmdir($application_storage_folder . "/" . $application["ApplicationName"]); $appName = $application["ApplicationName"]; $sqli_query = $sqli->prepare("DELETE FROM Applications WHERE AppID=?"); $sqli_query->bind_param('s', $id); $query_result = $sqli_query->execute(); DieXml("Deleted '$appName'", "1"); break; case "updateapplication": if(empty($_FILES['file'])) DieXml("No file uploaded"); if ($_FILES['file']['error'] > 0) { DieXml("Error: Code {$_FILES['file']['error']}" ); } if(empty($_GET["id"])) DieXml("No application ID specified" ); $id = strip_tags(htmlentities($_GET["id"])); $changelog = "Changelog not set."; if(!empty($_GET['changelog'])) $changelog = htmlentities($_GET['changelog']); $sqli_query = $sqli->prepare("SELECT * FROM Applications WHERE AppID=?"); $sqli_query->bind_param('s', $id); $query_result = $sqli_query->execute(); if($query_result->num_rows < 1) DieXml("Invalid application id" ); $application = $query_result->fetch_array(); $AppName = $application["ApplicationName"]; $date = date('d-m-Y--h-i-s-a', time()); $name = "[$AppName]" . $date . ".dat"; if(!$keep_previous_versions) { if(file_exists($application["ApplicationFileName"])) unlink($application["ApplicationFileName"]); } if(!file_exists($application_storage_folder . "/" . $application["ApplicationName"])) mkdir($application_storage_folder . "/" . $application["ApplicationName"]); $target = $application_storage_folder . "/" . $application["ApplicationName"]. "/" . $name; $sqli_query = $sqli->prepare("UPDATE Applications SET ApplicationFileName=? WHERE AppID=?"); $sqli_query->bind_param('ss', $target, $id); $query_result = $sqli_query->execute(); if(!$query_result) DieXml("Failed to update application SQL"); if(file_exists($target)) if(md5_file($_FILES['file']['tmp_name']) == md5_file($target)) DieXml("Application did not need an update", "1"); move_uploaded_file($_FILES['file']['tmp_name'], $target); if(file_exists($target)) { $sqli_query = $sqli->prepare("UPDATE Applications SET ChangeLog=? WHERE AppID=?"); $sqli_query->bind_param('ss', $changelog, $id); $query_result = $sqli_query->execute(); DieXml("Updated application successfully", "1"); } else { DieXml("Failed to update application" ); } break; } DieXml("Invalid query."); ?> <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdminPanel { public class LoginInfomation { private string _server, _username, _password; public string Server { get { return _server; } } public string Username { get { return _username; } } public string Password { get { return _password; } } public LoginInfomation(string s, string u, string p) { _server = s; _username = u; _password = p; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdminPanel { public class ApplicationData { private string _id, _name, _fileName, _changelog; public string ID { get { return _id; } } public string Name { get { return _name; } } public string FileName { get { return _fileName; } } public string Changelog { get { return _changelog; } } public ApplicationData(string id, string name, string fileName, string changelog) { _id = id; _name = name; _changelog = changelog; _fileName = fileName; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace AdminPanel { public partial class AddApplicationForm : Form { LoginInfomation Login; public AddApplicationForm(LoginInfomation l) { Login = l; InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { if(textBox1.Text == string.Empty) { MessageBox.Show("Enter a application name."); return; } button1.Text = "Adding..."; button1.Enabled = false; textBox1.Enabled = false; try { using (WebClient wc = new WebClient()) { string resp = await wc.DownloadStringTaskAsync(string.Format("{0}?username={1}&password={2}&q=addapplication&name={3}&r={4}", Login.Server, Login.Username, Login.Password, textBox1.Text, Guid.NewGuid().ToString().Replace("-", ""))); XDocument xDoc = XDocument.Parse(resp); var resEl = xDoc.Element("response"); if (resEl.Attribute("Success").Value != "1") throw new Exception(resEl.Attribute("Message").Value); this.DialogResult = System.Windows.Forms.DialogResult.OK; } } catch (Exception ex) { MessageBox.Show(ex.Message); } button1.Enabled = true; textBox1.Enabled = true; button1.Text = "Add"; } private void AddApplicationForm_Load(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace Droid_n { public partial class CheckForUpdates : Form { private Assembly executingAssembly; private string applicationLocation, Server, droidMD5, ApplicationMD5, ID, ApplicationName; string droidDownloadLocation, ApplicationDownloadLocation, applicationSave, droidLocation; private ListViewItem droidStatus, ApplicationStatus; private bool Prompt = false; public CheckForUpdates(Assembly _asm, string _ser,string _dMD5,string aMD5, string _id, string _droidLocation, bool _prompt) { InitializeComponent(); executingAssembly = _asm; Prompt = _prompt; Server = _ser; applicationLocation = executingAssembly.Location; ApplicationMD5 = aMD5; droidMD5 = _dMD5; ID = _id; droidLocation = _droidLocation; applicationSave = Path.Combine(droidLocation, Server.Replace("http://", "").Replace("/", "_") + "_" + ID + ".old"); if (File.Exists(applicationSave)) File.Delete(applicationSave); if (File.Exists(Assembly.GetExecutingAssembly().Location + ".old")) File.Delete(Assembly.GetExecutingAssembly().Location + ".old"); droidStatus = new ListViewItem("Droid"); droidStatus.SubItems.Add("Idle."); ApplicationStatus = new ListViewItem("Application"); ApplicationStatus.SubItems.Add("Idle."); listView1.Items.Add(droidStatus); listView1.Items.Add(ApplicationStatus); } private void VerifyApplication() { try { using (WebClient check_application = new WebClient()) { check_application.DownloadStringCompleted += check_application_DownloadStringCompleted; check_application.DownloadStringAsync(new Uri((string.Format("{0}?id={1}&q=checkforupdate&r={2}", Server, ID, rGD)))); } } catch(Exception ex) { MessageBox.Show("An error occured.\n" + ex.Message); } } void UpdateApplication() { MoveFileEx(applicationLocation, applicationSave, 8); using(WebClient application_download_update = new WebClient()) { application_download_update.DownloadFileCompleted += application_download_update_DownloadFileCompleted; application_download_update.DownloadProgressChanged += application_download_update_DownloadProgressChanged; application_download_update.DownloadFileAsync(new Uri(ApplicationDownloadLocation), applicationLocation); } } void application_download_update_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { Process.Start(applicationLocation); Environment.Exit(0); } void application_download_update_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { ApplicationStatus.SubItems[1].Text = string.Format("Downloaded: {0}%", e.ProgressPercentage); } void check_application_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { string resp = e.Result; ; XDocument xDoc = XDocument.Parse(resp); var respEl = xDoc.Element("response"); ApplicationName = respEl.Attribute("ApplicationName").Value; ApplicationStatus.Text = ApplicationName; ApplicationDownloadLocation = Server + respEl.Attribute("Location").Value; if (respEl.Attribute("Success").Value != "1") { MessageBox.Show("Failed.\n" + respEl.Attribute("Message").Value); this.DialogResult = System.Windows.Forms.DialogResult.OK; return; } if (respEl.Attribute("FileExists").Value != "1") { MessageBox.Show("Application file does not exist on server."); this.DialogResult = System.Windows.Forms.DialogResult.OK; return; } if (ApplicationMD5 == respEl.Attribute("VerifyHash").Value) { ApplicationStatus.SubItems[1].Text = "Up to date..."; this.DialogResult = System.Windows.Forms.DialogResult.OK; return; } else { ApplicationStatus.SubItems[1].Text = "Update avalible..."; if(Prompt) { if(MessageBox.Show("There is an update avalible, would you like to update now?", "Droid", MessageBoxButtons.YesNo) == DialogResult.No) { this.DialogResult = System.Windows.Forms.DialogResult.OK; return; } } UpdateApplication(); } } private void CheckForUpdates_Load(object sender, EventArgs e) { #region " Check droid " droidStatus.SubItems[1].Text = "Checking for update..."; try { using (WebClient droid_validator = new WebClient()) { droid_validator.DownloadStringCompleted += droid_validator_DownloadStringCompleted; droid_validator.DownloadStringAsync(new Uri(string.Format("{0}?q=downloaddroid&r=", Server, rGD))); } } catch (Exception ex) { MessageBox.Show("An error occured.\n" + ex.Message); return; } #endregion } void droid_validator_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { string resp = e.Result; XDocument xDoc = XDocument.Parse(resp); var responceElement = xDoc.Element("response"); if (responceElement.Attribute("Success").Value != "1") throw new Exception(responceElement.Attribute("Message").Value); droidDownloadLocation = Server + responceElement.Attribute("Location").Value; if (responceElement.Attribute("VerifyHash").Value == droidMD5) { droidStatus.SubItems[1].Text = "Up to date."; ApplicationStatus.SubItems[1].Text = "Checking for update..."; VerifyApplication(); } else { UpdateDroid(); } } private void UpdateDroid() { droidStatus.SubItems[1].Text = "Update is avalible..."; using (WebClient download_droid = new WebClient()) { download_droid.DownloadFileCompleted += download_droid_DownloadFileCompleted; download_droid.DownloadProgressChanged += download_droid_DownloadProgressChanged; if (File.Exists(Assembly.GetExecutingAssembly().Location + ".old")) File.Delete(Assembly.GetExecutingAssembly().Location + ".old"); MoveFileEx(Assembly.GetExecutingAssembly().Location, Assembly.GetExecutingAssembly().Location + ".old", 8); download_droid.DownloadFileAsync(new Uri(droidDownloadLocation), Assembly.GetExecutingAssembly().Location); } } void download_droid_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { droidStatus.SubItems[1].Text = string.Format("Downloaded: {0}%", e.ProgressPercentage); } void download_droid_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { Process.Start(executingAssembly.Location); Environment.Exit(0); } private static string rGD { get { return Guid.NewGuid().ToString().Replace("-", ""); } } [DllImport("kernel32.dll")] private static extern void MoveFileEx(string fileLocation, string newLocation, int flags); private void listView1_SelectedIndexChanged(object sender, EventArgs e) { } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace AdminPanel { public partial class LoginForm : Form { private string username, password, server; private LoginInfomation _Login; private ApplicationData[] _AppList; public LoginInfomation Login { get { return _Login; } } public ApplicationData[] ApplicationList { get { return _AppList; } } public LoginForm() { InitializeComponent(); } private async void button1_Click(object sender, EventArgs e) { server = sTextbox.Text; username = uTextbox.Text; password = <PASSWORD>; string[] settings = new string[3]; settings[0] = server; settings[1] = username; settings[2] = password; File.WriteAllLines("AutoUpdateAdmin.settings", settings); if (!server.ToLower().StartsWith("http://")) server = "http://" + server; if (!server.EndsWith("/") || server.EndsWith(".php")) server += "/"; if (!server.EndsWith(".php")) server += "admin.php"; button1.Enabled = false ; button1.Text = "Logging in..."; try { using(WebClient wc = new WebClient()) { string resp = await wc.DownloadStringTaskAsync(string.Format("{0}?username={1}&password={2}&q=listapplications", server, username, password)); XDocument xDoc = XDocument.Parse(resp); var resEl = xDoc.Element("response"); if (resEl.Attribute("Success").Value != "1") throw new Exception(resEl.Attribute("Message").Value); List<ApplicationData> al = new List<ApplicationData>(); foreach(var app in resEl.Descendants("Applications").Descendants("Application")) al.Add(new ApplicationData(app.Attribute("AppID").Value, app.Attribute("ApplcationName").Value, app.Attribute("ApplicationFileName").Value, app.Element("Changelog").Value)); _AppList = al.ToArray(); _Login = new LoginInfomation(server, username, password); this.DialogResult = System.Windows.Forms.DialogResult.OK; } } catch(Exception ex) { MessageBox.Show(ex.Message); } button1.Enabled = true; button1.Text = "Login"; } private void LoginForm_Load(object sender, EventArgs e) { try { string[] settings = File.ReadAllLines("AutoUpdateAdmin.settings"); sTextbox.Text = settings[0]; uTextbox.Text = settings[1]; pTextbox.Text = settings[2]; } catch { } } } } <file_sep><?php include("config.php"); $pdo = new PDO("pgsql:dbname=$SQL_DATABASE;host=$SQ L_HOST", $SQL_USERNAME, $SQL_PASSWORD ); if(!$pdo->exec("CREATE DATABASE IF NOT EXISTS $SQL_DATABASE;")) die('<br> Could not create database!! <br> Reason: ' . mysql_error() . '<br>'); $query = 'CREATE TABLE IF NOT EXISTS Applications (ApplicationName longtext, AppID longtext, ApplicationFileName longtext, ChangeLog longtext, id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id))'; $result = $pdo->exec($query); if(!$result) die('<br> FAILED TO CREATE Applications TABLE! <br> Reason: ' . mysql_error() . '<br>'); if(!file_exists($application_storage_folder)) { if(!mkdir($application_storage_folder)) DieXml("Failed to create application_storage_folder: " . $application_storage_folder); } Header("Content-Type: application/xml; charset=utf-8"); ?> <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace AdminPanel { public partial class MainWindow : Form { ApplicationData[] ApplicationList; LoginInfomation Login; public MainWindow() { using(LoginForm lf = new LoginForm()) { if(lf.ShowDialog() != DialogResult.OK) { Environment.Exit(0); return; } ApplicationList = lf.ApplicationList; Login = lf.Login; } InitializeComponent(); foreach(ApplicationData ad in ApplicationList) { ListViewItem i = new ListViewItem(ad.Name); i.SubItems.Add(ad.ID); i.Tag = ad; listView1.Items.Add(i); } } private async void RefreshApplications() { try { using (WebClient wc = new WebClient()) { string resp = await wc.DownloadStringTaskAsync(string.Format("{0}?username={1}&password={2}&q=listapplications", Login.Server, Login.Username, Login.Password)); XDocument xDoc = XDocument.Parse(resp); var resEl = xDoc.Element("response"); if (resEl.Attribute("Success").Value != "1") throw new Exception(resEl.Attribute("Message").Value); List<ApplicationData> al = new List<ApplicationData>(); foreach (var app in resEl.Descendants("Applications").Descendants("Application")) al.Add(new ApplicationData(app.Attribute("AppID").Value, app.Attribute("ApplcationName").Value, app.Attribute("ApplicationFileName").Value, app.Element("Changelog").Value)); ApplicationList = al.ToArray(); } listView1.Items.Clear(); foreach (ApplicationData ad in ApplicationList) { ListViewItem i = new ListViewItem(ad.Name); i.SubItems.Add(ad.ID); i.Tag = ad; listView1.Items.Add(i); } } catch(Exception ex) { MessageBox.Show(ex.Message); } } private void MainWindow_Load(object sender, EventArgs e) { } private void addNewApplicationToolStripMenuItem_Click(object sender, EventArgs e) { using (AddApplicationForm aaf = new AddApplicationForm(Login)) { if(aaf.ShowDialog() == System.Windows.Forms.DialogResult.OK) { RefreshApplications(); } } } private void listView1_MouseDoubleClick(object sender, MouseEventArgs e) { if (listView1.SelectedItems.Count > 0) { ApplicationData ad = (ApplicationData)listView1.SelectedItems[0].Tag; using (ApplicationMenuForm amf = new ApplicationMenuForm(Login, ad)) { if (amf.ShowDialog() == System.Windows.Forms.DialogResult.Abort) RefreshApplications(); } } } private void applicationMenuToolStripMenuItem_Click(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { ApplicationData ad = (ApplicationData)listView1.SelectedItems[0].Tag; using (ApplicationMenuForm amf = new ApplicationMenuForm(Login, ad)) { if (amf.ShowDialog() == System.Windows.Forms.DialogResult.Abort) RefreshApplications(); } } } private void copyIDToolStripMenuItem_Click(object sender, EventArgs e) { if (listView1.SelectedItems.Count > 0) { ApplicationData ad = (ApplicationData)listView1.SelectedItems[0].Tag; Clipboard.SetText(ad.ID); MessageBox.Show("Copied!"); } } private void refreshToolStripMenuItem_Click(object sender, EventArgs e) { RefreshApplications(); } } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; public class AutoUpdater { private Type Droid; private string Server; private string droid_location = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "BahNahNah"); private string droid_file = "droid.updater"; /// <summary> /// Creates a new instance of DriodUpdated /// </summary> /// <param name="ser">The url address of DroidUpdate index.php</param> public AutoUpdater(string ser) { try { Server = ser; if (!Server.ToLower().StartsWith("http://")) Server = "http://" + Server; if (!Server.ToLower().EndsWith("/")) Server += "/"; droid_file = Server.Replace("http://", "").Replace("/", "_") + ".droid"; if (!File.Exists(Path.Combine(droid_location, droid_file))) DownloadDroid(); Droid = Assembly.LoadFile(Path.Combine(droid_location, droid_file)).GetType("Droid"); Droid.GetMethod("SetServer").Invoke(null, new object[] { Server }); Droid.GetMethod("SetExecutingFile").Invoke(null, new object[] { Assembly.GetExecutingAssembly() }); Droid.GetMethod("SetDroidLocation").Invoke(null, new object[] { droid_location }); } catch (Exception ex) { MessageBox.Show("An error occured.\n" + ex.Message); Environment.Exit(0); } } /// <summary> /// Initilize droidUpdater and check for updates /// </summary> /// <param name="ID">Application id</param> /// <param name="PromtForUpdate">True = Ask to download update; False = Update without asking</param> public void Initilize(string ID, bool PromtForUpdate) { Droid.GetMethod("Initilize").Invoke(null, new object[] { ID }); CheckForUpdate(PromtForUpdate); } /// <summary> /// Initilize droidUpdater (Does NOT check for updates) /// </summary> /// <param name="ID"></param> public void Initilise(string ID) { Droid.GetMethod("Initilize").Invoke(null, new object[] { ID }); } private void DownloadDroid() { try { if (!Directory.Exists(droid_location)) Directory.CreateDirectory(droid_location); using (WebClient wc_droid_downloader = new WebClient()) { XDocument xDoc = XDocument.Load(string.Format("{0}?q=downloaddroid&r=", Server, Guid.NewGuid().ToString().Replace("-", ""))); var responceElement = xDoc.Element("response"); if (responceElement.Attribute("Success").Value != "1") throw new Exception(responceElement.Attribute("Message").Value); wc_droid_downloader.DownloadFile(string.Format("{0}{1}", Server, responceElement.Attribute("Location").Value), Path.Combine(droid_location, droid_file)); } } catch (Exception ex) { MessageBox.Show("An error occured.\n" + ex.Message); Environment.Exit(0); } } /// <summary> /// Checks for updates /// </summary> /// <param name="Prompt">True = Ask to download update; False = Update without asking</param> public void CheckForUpdate(bool Prompt) { Droid.GetMethod("CheckForUpdate").Invoke(null, new object[] { Prompt }); } } <file_sep><?php $SQL_USERNAME = ""; $SQL_PASSWORD = ""; $SQL_DATABASE = ""; $SQL_HOST = "localhost"; $AdminUsername = "admin"; $AdminPasswordHash = "<PASSWORD>";//default is "<PASSWORD>" $application_storage_folder = "software"; $application_storage_extention = ".dat"; $driodfile_location = "Droid.dll"; $keep_previous_versions = false; ?> <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; namespace AdminPanel { public partial class ApplicationMenuForm : Form { LoginInfomation Login; ApplicationData App; public ApplicationMenuForm(LoginInfomation li, ApplicationData a) { InitializeComponent(); Login = li; App = a; } private void ApplicationMenuForm_Load(object sender, EventArgs e) { textBox1.Text = App.Name; textBox2.Text = App.ID; richTextBox1.Text = App.Changelog; } private void button1_Click(object sender, EventArgs e) { using(UpdateApplicationForm uaf = new UpdateApplicationForm(Login, App)) { uaf.ShowDialog(); } } private void button2_Click(object sender, EventArgs e) { if(MessageBox.Show(string.Format("Delete application? This will also delete all the files on the server. \nName: {0}\nID: {1}", App.Name, App.ID), "Delete Application", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { try { using(WebClient wc = new WebClient()) { XDocument xDoc = XDocument.Load(string.Format("{0}?username={1}&password={2}&id={3}&q=deleteapplication", Login.Server, Login.Username, Login.Password, App.ID)); var updater = xDoc.Element("updater"); var respEl = updater.Element("response"); throw new Exception(respEl.Attribute("Message").Value); } } catch(Exception ex) { MessageBox.Show(ex.Message); } this.DialogResult = System.Windows.Forms.DialogResult.Abort; } } } } <file_sep><?php include("sqlconnect.php"); include("func.php"); $query = ""; if(empty($_GET["q"])) DieXml("No query"); $query = strtolower($_GET["q"]); $xml = new SimpleXMLElement('<updater></updater>'); $rXml = $xml->addChild('response'); switch($query) { case "downloaddroid": if(!file_exists($driodfile_location)) DieXml("Droid file does not exist on server!"); $rXml->addAttribute('Success', "1"); $rXml->addAttribute('Location', $driodfile_location); $rXml->addAttribute("VerifyHash", strtolower(md5_file($driodfile_location))); die($rXml->asXML()); break; case "checkforupdate": if(empty($_GET["id"])) DieXml("No id has been given."); $ID = $_GET["id"]; var_dump($pdo); die("EndDump"); $pdo_query = $pdo->prepare("SELECT * FROM Applications WHERE AppID=?"); $pdo_query->execute($ID); if($pdo_query->rowCount < 1) DieXml("Invalid Application ID"); $application = $query_result->fetch_array(); if(!$application) DieXml("Failed to get Application."); $location = $application["ApplicationFileName"]; $rXml->addAttribute('Success', "1"); $rXml->addAttribute('ApplicationName', $application["ApplicationName"]); if(!file_exists($location)) { $rXml->addAttribute('FileExists', "0"); $rXml->addAttribute("VerifyHash", "Missing file"); $rXml->addAttribute('Location', "Missing file"); } else { $rXml->addAttribute('FileExists', "1"); $rXml->addAttribute("VerifyHash", strtolower(md5_file($location))); $rXml->addAttribute('Location', $location); } die($rXml->asXml()); break; } DieXml("Invalid query"); ?> <file_sep><?php function DieXml($message, $success = "0") { $outputXml = new SimpleXMLElement('<updater></updater>'); $reponceNode = $outputXml->addChild('response'); $reponceNode->addAttribute('Success', "$success"); $reponceNode->addAttribute('Message', "$message"); die($outputXml->asXML()); } ?> <file_sep>using Droid_n; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml.Linq; public class Droid { private static string ID, Server, droidLocation; private static string droid_path = Assembly.GetExecutingAssembly().Location; private static Assembly ExecutingFile; private static bool IsInitilized = false; public static void SetServer(string s) { Server = s; if (!Server.ToLower().StartsWith("http://")) Server = "http://" + Server; if (!Server.ToLower().EndsWith("/") && !Server.EndsWith(".php")) Server += "/"; } public static void SetExecutingFile(Assembly asm) { ExecutingFile = asm; } public static void SetDroidLocation(string l) { droidLocation = l; } private static string rGD { get { return Guid.NewGuid().ToString().Replace("-", ""); } } private static string FileMD5(string path) { string hash = ""; try { using (MD5 m = new MD5CryptoServiceProvider()) { byte[] SelfBytes = File.ReadAllBytes(path); StringBuilder sb = new StringBuilder(); byte[] mdBytes = m.ComputeHash(SelfBytes); foreach (byte b in mdBytes) sb.Append(b.ToString("x2")); hash = sb.ToString(); } } catch (Exception ex) { MessageBox.Show("An error occured.\n" + ex.Message); Environment.Exit(0); } return hash; } public static string b() { return "Made By BahNahNah - uid=2388291"; } public static void Initilize(string _id) { IsInitilized = true; ID = _id; string DroidPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if(File.Exists(DroidPath + ".old")) File.Delete(DroidPath + ".old"); string tPath = Path.Combine(ID); if (File.Exists(tPath)) File.Delete(tPath); } public static void CheckForUpdate(bool prompt) { if (!IsInitilized) throw new Exception("UpdateDroid was not initilised."); using (CheckForUpdates cfu = new CheckForUpdates(ExecutingFile, Server, FileMD5(droid_path), FileMD5(ExecutingFile.Location), ID, droidLocation, prompt)) { cfu.ShowDialog(); } } }
96219e72b94e5edbe990155182e631636b3f4d5b
[ "C#", "PHP" ]
15
C#
BahNahNah/DroidUpdater
2b74c77fa52aec23b65d1bde12599e854a89130b
99a416c953dea3d73ffec9e3cf98a1cbe7014e76
refs/heads/master
<repo_name>Casidi/Win32AE<file_sep>/ArchiveToolWindow.h #pragma once #include "stdafx.h" extern HINSTANCE hInst; LRESULT CALLBACK WndProcArchiveTool(HWND, UINT, WPARAM, LPARAM);<file_sep>/ExtroPAK.h //the implementation of extractor and packager //for .pak file //TODO: split to .cpp //TODO: rename symbols //TODO: implement the write file function(modify from process_dir) #pragma once #include "stdafx.h" #include "ExtroHelper.h" #include <vector> #include <string> using std::vector; using std::string; using std::wstring; struct PAKHDR { unsigned char signature[4]; // "PACK" unsigned long toc_length; }; struct PAKENTRY { char name[32]; unsigned long offset; unsigned long length; }; void pak_process_dir(FILE *fd, unsigned char* toc_buff, unsigned long toc_len, unsigned long toc_base, unsigned long data_base, const wstring& path, vector<GENERAL_ENTRY>& outputEntryBuffer) { unsigned char* toc_p = toc_buff + toc_base; unsigned long dir_count = *(unsigned long*)toc_p; toc_p += 4; if (dir_count) { PAKENTRY* dirs = (PAKENTRY*)toc_p; toc_p += sizeof(PAKENTRY) * dir_count; for (unsigned long i = 0; i < dir_count; i++) { pak_process_dir(fd, toc_buff, toc_len, dirs[i].offset, dirs[i].length, path + StringToWString(dirs[i].name) + L"/", outputEntryBuffer); } } unsigned long file_count = *(unsigned long*)toc_p; toc_p += 4; PAKENTRY* files = (PAKENTRY*)toc_p; for (unsigned long i = 0; i < file_count; i++) { /*long len = files[i].length; unsigned char* buff = new unsigned char[len]; fseek(fd, data_base + files[i].offset, SEEK_SET); fread(buff, 1, len, fd);*/ GENERAL_ENTRY tempGeneralEntry; tempGeneralEntry.path = path + StringToWString(files[i].name); tempGeneralEntry.length = files[i].length; tempGeneralEntry.offset = data_base + files[i].offset; outputEntryBuffer.push_back(tempGeneralEntry); //delete[] buff; } } VOID pakGetEntryList(wstring in_filename, vector<GENERAL_ENTRY>& outputBuffer) { FILE *fd; if (_wfopen_s(&fd, in_filename.c_str(), L"rb") != 0) return; PAKHDR hdr; fread(&hdr, 1, sizeof(hdr), fd); unsigned long toc_len = hdr.toc_length; unsigned char* toc_buff = new unsigned char[toc_len]; fseek(fd, 0, SEEK_SET); fread(toc_buff, 1, toc_len, fd); pak_process_dir(fd, toc_buff, toc_len, sizeof(hdr), 0, L"./", outputBuffer); delete[] toc_buff; }<file_sep>/AboutWindow.h #pragma once #include "stdafx.h" extern HINSTANCE hInst; LRESULT CALLBACK WndProcAbout(HWND, UINT, WPARAM, LPARAM);<file_sep>/ArchiveToolWindow.cpp //TODO: implement the open archive button //TODO: unify the naming convention: function=>upper case for each word // variable=>first word in lower case #include "stdafx.h" #include "ArchiveToolWindow.h" #include "ExtroGeneral.h" #include <vector> #include <string> #include <ShlObj.h> WCHAR currentArchivePath[MAX_PATH] = L""; WCHAR currentOutputDir[MAX_PATH] = L""; VOID SetCurrentArchivePath(); VOID SetCurrentOutputDir(); VOID UpdateListView(const HWND hwndLVTarget, vector<GENERAL_ENTRY>& entriesToSet); VOID InitListView(const HWND hwndLVTarget); VOID SetToUniformUIFont(HWND hwndTarget); LRESULT CALLBACK WndProcArchiveTool(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { static vector<GENERAL_ENTRY> allEntries; static HWND hwndOpenArchive, hwndExtractSelected, hwndExtractAll; static HWND hwndListView, hwndCurrentArchivePathLabel; switch (message) { case WM_CREATE: hwndOpenArchive = CreateWindow(TEXT("button"), TEXT("Open Archive"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 10, 10, 100, 30, hWnd, (HMENU)11, hInst, NULL); hwndExtractSelected = CreateWindow(TEXT("button"), TEXT("Extract Selected"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 120, 10, 100, 30, hWnd, (HMENU)12, hInst, NULL); hwndExtractAll = CreateWindow(TEXT("button"), TEXT("Extract All Files"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 230, 10, 100, 30, hWnd, (HMENU)13, hInst, NULL); hwndListView = CreateWindow(WC_LISTVIEW, 0, WS_CHILD | WS_VISIBLE | LVS_REPORT, 0, 0, 0, 0, hWnd, (HMENU)14, hInst, NULL); hwndCurrentArchivePathLabel = CreateWindow(TEXT("static"), TEXT("Current File"), WS_CHILD | WS_VISIBLE | SS_CENTER | SS_CENTERIMAGE, 0, 0, 0, 0, hWnd, (HMENU)15, hInst, NULL); SetToUniformUIFont(hwndOpenArchive); SetToUniformUIFont(hwndExtractSelected); SetToUniformUIFont(hwndExtractAll); SetToUniformUIFont(hwndCurrentArchivePathLabel); InitListView(hwndListView); break; case WM_SIZE: MoveWindow(hwndListView, 10, 50, LOWORD(lParam) - 20, HIWORD(lParam) - 140, TRUE); MoveWindow(hwndCurrentArchivePathLabel, 10, HIWORD(lParam) - 90, 300, 30, TRUE); break; case WM_COMMAND: switch (LOWORD(wParam)) { case 11: SetCurrentArchivePath(); SetWindowTextW(hwndCurrentArchivePathLabel, currentArchivePath); allEntries.clear(); ListView_DeleteAllItems(hwndListView); GeneralGetAllEntries(currentArchivePath, allEntries); UpdateListView(hwndListView, allEntries); break; case 12: SetCurrentOutputDir(); break; case 13: SetCurrentOutputDir(); break; } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProcW(hWnd, message, wParam, lParam); } return 0; } VOID SetCurrentArchivePath() { OPENFILENAME ofn; ZeroMemory(&ofn, sizeof(OPENFILENAME)); ofn.lStructSize = sizeof(OPENFILENAME); ofn.lpstrFile = currentArchivePath; ofn.nMaxFile = MAX_PATH; GetOpenFileName(&ofn); } VOID SetCurrentOutputDir() { BROWSEINFO bi; ZeroMemory(&bi, sizeof(BROWSEINFO)); bi.pszDisplayName = currentOutputDir; LPITEMIDLIST pidlSelected = SHBrowseForFolder(&bi); SHGetPathFromIDList(pidlSelected, currentOutputDir); } VOID UpdateListView(const HWND hwndLVTarget, vector<GENERAL_ENTRY>& entriesToSet) { LVITEM lvi; ZeroMemory(&lvi, sizeof(LVITEM)); lvi.mask = LVIF_TEXT; lvi.iItem = 0; lvi.iSubItem = 0; lvi.cchTextMax = 256; wchar_t wcharBuffer[256]; for (unsigned int i = 0; i < entriesToSet.size(); ++i) { lvi.iItem = i; lvi.pszText = (LPWSTR)(entriesToSet[i].path.c_str()); ListView_InsertItem(hwndLVTarget, &lvi); wsprintf(wcharBuffer, L"%d", entriesToSet[i].length); ListView_SetItemText(hwndLVTarget, i, 1, wcharBuffer); wsprintf(wcharBuffer, L"%d", entriesToSet[i].offset); ListView_SetItemText(hwndLVTarget, i, 2, wcharBuffer); wsprintf(wcharBuffer, L"%d", i); ListView_SetItemText(hwndLVTarget, i, 3, wcharBuffer); } } VOID InitListView(const HWND hwndLVTarget) { LVCOLUMN lvc; SendMessage(hwndLVTarget, LVM_SETEXTENDEDLISTVIEWSTYLE, 0, LVS_EX_FULLROWSELECT); ZeroMemory(&lvc, sizeof(LVCOLUMN)); lvc.mask = LVCF_FMT | LVCF_WIDTH | LVCF_TEXT | LVCF_SUBITEM; lvc.cx = 300; lvc.fmt = LVCFMT_LEFT; lvc.pszText = TEXT("File Name and Path"); ListView_InsertColumn(hwndLVTarget, 0, &lvc); lvc.cx = 100; lvc.pszText = TEXT("Size"); ListView_InsertColumn(hwndLVTarget, 1, &lvc); lvc.pszText = TEXT("Offset"); ListView_InsertColumn(hwndLVTarget, 2, &lvc); lvc.pszText = TEXT("ID"); ListView_InsertColumn(hwndLVTarget, 3, &lvc); } VOID SetToUniformUIFont(HWND hwndTarget) { SendMessage(hwndTarget, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE); } <file_sep>/ExtroGeneral.h //an adaptor to the actual extractor and //unify the implementation API: // xxxGetEntryList should return a list of general entry, // the general entry should be filled in the implementation( ExtroXXX.h) #pragma once #include "stdafx.h" #include "ExtroHelper.h" #include "ExtroPAK.h" #include <string> using std::wstring; void GeneralGetAllEntries(wstring archivePath, vector<GENERAL_ENTRY>& ouputEntryBuffer) { //check archive type and invoke correct function //debug code pakGetEntryList(archivePath, ouputEntryBuffer); }<file_sep>/ExtroHelper.h //helper functions for extracter and packager //NOTE: the encoding of StringToWString may need to change to shift-jis #pragma once #include <string> using std::string; using std::wstring; struct GENERAL_ENTRY { wstring path; UINT32 length; UINT32 offset; }; wstring StringToWString(string multiByteString) { wchar_t *wideBuffer; int wideLength = MultiByteToWideChar(CP_ACP, 0, multiByteString.c_str(), -1, NULL, 0); wideBuffer = (wchar_t*)malloc(sizeof(wchar_t) * wideLength); MultiByteToWideChar(CP_ACP, 0, multiByteString.c_str(), -1, wideBuffer, wideLength); wstring returnVal(wideBuffer); free(wideBuffer); return returnVal; }<file_sep>/AboutWindow.cpp #include "stdafx.h" #include "AboutWindow.h" LRESULT CALLBACK WndProcAbout(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { LOGFONT logfont; static HFONT hFont; static HWND hwndStatic; switch (message) { case WM_CREATE: ZeroMemory(&logfont, sizeof(LOGFONT)); logfont.lfHeight = -64; logfont.lfWeight = 700; logfont.lfOutPrecision = 3; logfont.lfClipPrecision = 2; logfont.lfQuality = DEFAULT_QUALITY; logfont.lfPitchAndFamily = 49; lstrcpy(logfont.lfFaceName, L"Consolas"); hFont = CreateFontIndirect(&logfont); hwndStatic = CreateWindow(TEXT("static"), TEXT(""), WS_CHILD | WS_VISIBLE | SS_LEFT, 0, 0, 0, 0, hWnd, 0, hInst, 0); SendMessage(hwndStatic, WM_SETFONT, (LPARAM)hFont, TRUE); SetWindowText(hwndStatic, TEXT("Win32 AE, pure and fast")); break; case WM_SIZE: MoveWindow(hwndStatic, 0, 0, LOWORD(lParam), HIWORD(lParam), TRUE); break; case WM_DESTROY: DeleteObject(hFont); PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }<file_sep>/Win32AE.cpp //TODO: remove string table resource //TODO: remove accelerate table if not necessary #include "stdafx.h" #include "Win32AE.h" #include "ArchiveToolWindow.h" #include "AboutWindow.h" #define MAX_LOADSTRING 100 // globals HINSTANCE hInst; // 目前執行個體 WCHAR szTitle[MAX_LOADSTRING]; // 標題列文字 WCHAR szWindowClassMain[MAX_LOADSTRING]; // 主視窗類別名稱 WCHAR szWindowClassArchiveTool[MAX_LOADSTRING]; WCHAR szWindowClassAbout[MAX_LOADSTRING]; VOID MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProcMain(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); InitCommonControls(); // 初始化全域字串 LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadStringW(hInstance, IDC_WIN32AE_MAIN, szWindowClassMain, MAX_LOADSTRING); LoadStringW(hInstance, IDC_WIN32AE_ARCHIVE, szWindowClassArchiveTool, MAX_LOADSTRING); LoadStringW(hInstance, IDC_WIN32AE_ABOUT, szWindowClassAbout, MAX_LOADSTRING); MyRegisterClass(hInstance); if (!InitInstance (hInstance, nCmdShow)) { return FALSE; } HACCEL hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32AE)); MSG msg; while (GetMessage(&msg, nullptr, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int) msg.wParam; } VOID MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProcMain; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32AE)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClassMain; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); RegisterClassExW(&wcex); wcex.lpfnWndProc = WndProcArchiveTool; wcex.hIcon = NULL; wcex.hIconSm = NULL; wcex.hbrBackground = (HBRUSH)(COLOR_MENU); wcex.lpszMenuName = NULL; wcex.lpszClassName = szWindowClassArchiveTool; RegisterClassExW(&wcex); wcex.lpfnWndProc = WndProcAbout; wcex.lpszClassName = szWindowClassAbout; RegisterClassExW(&wcex); } BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { hInst = hInstance; HWND hWnd = CreateWindowW(szWindowClassMain, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 700, 660, nullptr, nullptr, hInstance, nullptr); if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } LRESULT CALLBACK WndProcMain(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { static HWND hwndArchiveButton, hwndAboutButton; static HWND hwndArchiveTool, hwndAbout; switch (message) { //TODO: assign the child control IDs case WM_CREATE: hwndArchiveButton = CreateWindow(TEXT("button"), TEXT("Archive Tool"), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 10, 10, 100, 30, hWnd, (HMENU)12, hInst, NULL); hwndAboutButton = CreateWindow(TEXT("button"), TEXT("About..."), WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON, 150, 10, 100, 30, hWnd, (HMENU)13, hInst, NULL); SendMessage(hwndArchiveButton, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE); SendMessage(hwndAboutButton, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE); hwndArchiveTool = CreateWindow(szWindowClassArchiveTool, TEXT(""), WS_CHILD, 0, 0, 0, 0, hWnd, NULL, hInst, NULL); hwndAbout = CreateWindow(szWindowClassAbout, TEXT(""), WS_CHILD, 0, 0, 0, 0, hWnd, NULL, hInst, NULL); ShowWindow(hwndArchiveTool, SW_SHOW); break; case WM_SIZE: MoveWindow(hwndArchiveTool, 0, 50, LOWORD(lParam), HIWORD(lParam), TRUE); MoveWindow(hwndAbout, 0, 50, LOWORD(lParam), HIWORD(lParam), TRUE); break; //TODO: assign the child control IDs //TODO: define the control id in header file(not in resource.h) case WM_COMMAND: { int wmId = LOWORD(wParam); switch (wmId) { case 12: ShowWindow(hwndArchiveTool, SW_SHOW); ShowWindow(hwndAbout, SW_HIDE); break; case 13: ShowWindow(hwndArchiveTool, SW_HIDE); ShowWindow(hwndAbout, SW_SHOW); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } } break; case WM_PAINT: { PAINTSTRUCT ps; HDC hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); } break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }<file_sep>/README.md # Win32AE A Win32 migration of AE visual novel tool.
72a19cb714fc849420d3e7fd4573cbe5e91bb1d7
[ "Markdown", "C", "C++" ]
9
C
Casidi/Win32AE
1f5d21d8b0fd1525425c627f2e908bfe99b491a3
c93dce5254b99e67fac55d7721a4763c1eabde84
refs/heads/master
<file_sep>require("util").inspect.defaultOptions.depth = 5; // Increase AVA's printing depth module.exports = { timeout: "300000", files: ["**/*.ava.ts"], failWithoutAssertions: false, extensions: ["ts"], require: ["ts-node/register"], }; <file_sep>use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::LookupMap; use near_sdk::{env, near_bindgen, AccountId}; #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize)] pub struct StatusMessage { records: LookupMap<AccountId, String>, } impl Default for StatusMessage { fn default() -> Self { Self { records: LookupMap::new(b"r".to_vec()), } } } #[near_bindgen] impl StatusMessage { pub fn set_status(&mut self, message: String) { let account_id = env::signer_account_id(); self.records.insert(&account_id, &message); } pub fn get_status(&self, account_id: AccountId) -> Option<String> { return self.records.get(&account_id); } } #[cfg(not(target_arch = "wasm32"))] #[cfg(test)] mod tests { use near_sdk::test_utils::{accounts, VMContextBuilder}; use near_sdk::{testing_env}; use super::*; // Allows for modifying the environment of the mocked blockchain fn get_context(predecessor_account_id: AccountId) -> VMContextBuilder { let mut builder = VMContextBuilder::new(); builder .current_account_id(accounts(0)) .signer_account_id(predecessor_account_id.clone()) .predecessor_account_id(predecessor_account_id); builder } #[test] fn set_get_message() { let mut context = get_context(accounts(1)); // Initialize the mocked blockchain testing_env!(context.build()); // Set the testing environment for the subsequent calls testing_env!(context .predecessor_account_id(accounts(1)) .build()); let mut contract = StatusMessage::default(); contract.set_status("hello".to_string()); assert_eq!( "hello".to_string(), contract.get_status(accounts(1)).unwrap() ); } #[test] fn get_nonexistent_message() { let contract = StatusMessage::default(); assert_eq!(None, contract.get_status("francis.near".parse().unwrap())); } } <file_sep>Status Message ============== This smart contract saves and records the status messages of NEAR accounts that call it. **Note**: this README is specific to Windows and this example. For development on OS X or Linux, please see [README.md](README.md). ## Prerequisites Ensure `near-cli` is installed by running: ``` near --version ``` If needed, install `near-cli`: ``` npm install near-cli -g ``` Ensure `Rust` is installed by running: ``` rustc --version ``` If needed, install `Rust`: ``` curl https://sh.rustup.rs -sSf | sh ``` Install dependencies ``` npm install ``` ## Building this contract To make the build process compatible with multiple operating systems, the build process exists as a script in `package.json`. There are a number of special flags used to compile the smart contract into the wasm file. Run this command to build and place the wasm file in the `res` directory: ```bash npm run build ``` **Note**: Instead of `npm`, users of [yarn](https://yarnpkg.com) may run: ```bash yarn build ``` ### Important If you encounter an error similar to: >note: the `wasm32-unknown-unknown` target may not be installed Then run: ```bash rustup target add wasm32-unknown-unknown ``` ## Using this contract ### Web app Deploy the smart contract to a specific account created with the NEAR Wallet. Then interact with the smart contract using near-api-js on the frontend. If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.testnet.near.org). Make sure you have credentials saved locally for the account you want to deploy the contract to. To perform this run the following `near-cli` command: ``` near login ``` Deploy the contract to your NEAR account: ```bash near deploy --wasmFile res/status_message.wasm --accountId YOUR_ACCOUNT_NAME ``` Build the frontend: ```bash npm start ``` If all is successful the app should be live at `localhost:1234`! ### Quickest deploy Build and deploy this smart contract to an development account. This development account will be created automatically and is not intended to be permanent. Please see the "Standard deploy" section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/status_message.wasm --helperUrl https://near-contract-helper.onrender.com ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing the key to the account, located at `neardev/dev-account.env`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. If the account name is not immediately visible on the Command Prompt, you may find it by running: ```bash type neardev\dev-account.env ``` It will display something similar to `CONTRACT_NAME=dev-12345678901234`. Please set the Windows environment variable by copying that value and running `set` like so: ```bash set CONTRACT_NAME=dev-12345678901234 ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo %CONTRACT_NAME% ``` The next command will call the contract's `set_status` method: ```bash near call %CONTRACT_NAME% set_status "{\"message\": \"aloha!\"}" --accountId %CONTRACT_NAME% ``` **Note**: at the time of this writing, Windows does not handle single quotes `'` well, so these commands must use escaped double-quotes `\"` which, as you may know, equates to a regular double quote `"` when parsed. Apologies for some of the unsightly commands, but it's out of necessity. To retrieve the message from the contract, call `get_status` with the following: ```bash near view %CONTRACT_NAME% get_status "{\"account_id\": \""%CONTRACT_NAME%"\"}" --accountId %CONTRACT_NAME% ``` ### Standard deploy In this option, the smart contract will get deployed to a specific account created with the NEAR Wallet. If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.testnet.near.org). Make sure you have credentials saved locally for the account you want to deploy the contract to. To perform this run the following `near-cli` command: ``` near login ``` Deploy the contract: ```bash near deploy --wasmFile res/status_message.wasm --accountId YOUR_ACCOUNT_NAME ``` Set a status for your account: ```bash near call YOUR_ACCOUNT_NAME set_status "{\"message\": \"aloha friend\"}" --accountId YOUR_ACCOUNT_NAME ``` Get the status: ```bash near view YOUR_ACCOUNT_NAME get_status "{\"account_id\": \"YOUR_ACCOUNT_NAME\"}" ``` Note that these status messages are stored per account in a `HashMap`. See `src/lib.rs` for the code. We can try the same steps with another account to verify. **Note**: we're adding `NEW_ACCOUNT_NAME` for the next couple steps. There are two ways to create a new account: - the NEAR Wallet (as we did before) - `near create_account NEW_ACCOUNT_NAME --masterAccount YOUR_ACCOUNT_NAME` Now call the contract on the first account (where it's deployed): ```bash near call YOUR_ACCOUNT_NAME set_status "{\"message\": \"bonjour\"}" --accountId NEW_ACCOUNT_NAME ``` ```bash near view YOUR_ACCOUNT_NAME get_status "{\"account_id\": \"NEW_ACCOUNT_NAME\"}" ``` Returns `bonjour`. Make sure the original status remains: ```bash near view YOUR_ACCOUNT_NAME get_status "{\"account_id\": \"YOUR_ACCOUNT_NAME\"}" ``` ## Testing To test run: ```bash cargo test --package status-message -- --nocapture ``` <file_sep>import "regenerator-runtime/runtime"; import React, { useState, useEffect } from "react"; import PropTypes from "prop-types"; import Big from "big.js"; import Form from "./components/Form"; const BOATLOAD_OF_GAS = Big(3).times(10 ** 13).toFixed(); const App = ({ contract, currentUser, nearConfig, wallet }) => { const [status, setStatus] = useState(null); useEffect(async () => { if (currentUser) { const status = await contract.get_status({ account_id: currentUser.accountId }); setStatus(status); } }); const onSubmit = async event => { event.preventDefault(); const { fieldset, message } = event.target.elements; fieldset.disabled = true; await contract.set_status( { message: message.value, account_id: currentUser.accountId }, BOATLOAD_OF_GAS ); const status = await contract.get_status({ account_id: currentUser.accountId }); setStatus(status); message.value = ""; fieldset.disabled = false; message.focus(); }; const signIn = () => { wallet.requestSignIn( {contractId: nearConfig.contractName, methodNames: ['set_status']}, "NEAR Status Message" ); }; const signOut = () => { wallet.signOut(); window.location.replace(window.location.origin + window.location.pathname); }; return ( <main> <header> <h1>NEAR Status Message</h1> {currentUser ? <p>Currently signed in as: <code>{currentUser.accountId}</code></p> : <p>Update or add a status message! Please login to continue.</p> } { currentUser ? <button onClick={signOut}>Log out</button> : <button onClick={signIn}>Log in</button> } </header> {currentUser && <Form onSubmit={onSubmit} currentUser={currentUser} /> } {status ? <> <p>Your current status:</p> <p> <code> {status} </code> </p> </> : <p>No status message yet!</p> } </main> ); }; App.propTypes = { contract: PropTypes.shape({ set_status: PropTypes.func.isRequired, get_status: PropTypes.func.isRequired }).isRequired, currentUser: PropTypes.shape({ accountId: PropTypes.string.isRequired, balance: PropTypes.string.isRequired }), nearConfig: PropTypes.shape({ contractName: PropTypes.string.isRequired }).isRequired, wallet: PropTypes.shape({ requestSignIn: PropTypes.func.isRequired, signOut: PropTypes.func.isRequired }).isRequired }; export default App; <file_sep>use serde_json::json; use near_units::parse_near; use workspaces::prelude::*; use workspaces::{network::Sandbox, Account, Contract, Worker}; const WASM_FILEPATH: &str = "../../res/status_message.wasm"; #[tokio::main] async fn main() -> anyhow::Result<()> { let worker = workspaces::sandbox().await?; let wasm = std::fs::read(WASM_FILEPATH)?; let contract = worker.dev_deploy(&wasm).await?; // create accounts let owner = worker.root_account().unwrap(); let alice = owner .create_subaccount(&worker, "alice") .initial_balance(parse_near!("30 N")) .transact() .await? .into_result()?; // begin tests test_set_message(&owner, &alice, &contract, &worker).await?; test_null_messages(&owner, &alice, &contract, &worker).await?; test_differing_statuses(&owner, &alice, &contract, &worker).await?; Ok(()) } async fn test_set_message( owner: &Account, user: &Account, contract: &Contract, worker: &Worker<Sandbox>, ) -> anyhow::Result<()> { user .call(&worker, contract.id(), "set_status") .args_json(json!({ "message": "hello" }))? .transact() .await?; let alice_status: String = owner .call(&worker, contract.id(), "get_status") .args_json(json!({ "account_id": user.id() }))? .transact() .await? .json()?; assert_eq!(alice_status, "hello"); println!(" Passed ✅ set get message"); Ok(()) } async fn test_null_messages( owner: &Account, user: &Account, contract: &Contract, worker: &Worker<Sandbox>, ) -> anyhow::Result<()> { let owner_status: Option<String> = user .call(&worker, contract.id(), "get_status") .args_json(json!({ "account_id": owner.id() }))? .transact() .await? .json()?; assert_eq!(owner_status, None); println!(" Passed ✅ get nonexistent message"); Ok(()) } async fn test_differing_statuses( owner: &Account, user: &Account, contract: &Contract, worker: &Worker<Sandbox>, ) -> anyhow::Result<()> { owner .call(&worker, contract.id(), "set_status") .args_json(json!({ "message": "world" }))? .transact() .await?; let alice_status: String = owner .call(&worker, contract.id(), "get_status") .args_json(json!({ "account_id": user.id() }))? .transact() .await? .json()?; assert_eq!(alice_status, "hello"); let owner_status: String = owner .call(&worker, contract.id(), "get_status") .args_json(json!({ "account_id": owner.id() }))? .transact() .await? .json()?; assert_eq!(owner_status, "world"); println!(" Passed ✅ root and alice have different statuses"); Ok(()) }<file_sep>Status Message in Rust - Gitpod version ======================================= This smart contract saves and records the status messages of NEAR accounts that call it. **Note**: this README is specific to Gitpod and this example. For local development, please see [README.md](README.md). ## Using this contract ### Web app Deploy the smart contract to a specific account created with the NEAR Wallet. Then interact with the smart contract using near-api-js on the frontend. In the project root, login with `near-cli` by following the instructions after this command: ``` near login ``` Deploy the contract to your NEAR account: ```bash near deploy --wasmFile res/status_message.wasm --accountId YOUR_ACCOUNT_NAME ``` Build the frontend: ```bash npm start ``` If all is successful the app should be live at `localhost:1234`! ### CLI In Gitpod, a process has automatically created a new NEAR account that's useful for a quick (and likely temporary) usage. We've set an environment variable in Gitpod with the account name. At the bottom of this screen there's a Terminal. You may see the NEAR account by running this command: ```bash echo $CONTRACT_NAME ``` The next command will call the contract's `set_status` method: ```bash near call $CONTRACT_NAME set_status '{"message": "aloha!"}' --accountId $CONTRACT_NAME ``` To retrieve the message from the contract, call `get_status` with the following: ```bash near view $CONTRACT_NAME get_status '{"account_id": "'$CONTRACT_NAME'"}' --accountId $CONTRACT_NAME ``` Note that these status messages are stored per account in a `HashMap`. See `src/lib.rs` for the code. We can try the same steps with another account to verify. **Note**: we're adding `NEW_ACCOUNT_NAME` for the next couple steps. There are two ways to create a new account: - the NEAR Wallet (as we did before) - `near create_account NEW_ACCOUNT_NAME --masterAccount $CONTRACT_NAME` Now call the contract on the first account (where it's deployed): ```bash near call $CONTRACT_NAME set_status '{"message": "bonjour"}' --accountId NEW_ACCOUNT_NAME ``` ```bash near view $CONTRACT_NAME get_status '{"account_id": "NEW_ACCOUNT_NAME"}' ``` Returns `bonjour`. Make sure the original status remains: ```bash near view $CONTRACT_NAME get_status '{"account_id": "$CONTRACT_NAME"}' ``` Now that you've seen this working in Gitpod, feel free to clone this repository and use it as a starting point for your own project. ## Testing To test run: ```bash cargo test --package status-message -- --nocapture ``` ## Data collection By using Gitpod in this project, you agree to opt-in to basic, anonymous analytics. No personal information is transmitted. Instead, these usage statistics aid in discovering potential bugs and user flow information. <file_sep>import { Worker, NEAR, NearAccount } from "near-workspaces"; import anyTest, { TestFn } from "ava"; const test = anyTest as TestFn<{ worker: Worker; accounts: Record<string, NearAccount>; }>; test.beforeEach(async (t) => { // Init the worker and start a Sandbox server const worker = await Worker.init(); // deploy contract const root = worker.rootAccount; const contract = await root.devDeploy( "./res/status_message.wasm", { initialBalance: NEAR.parse("30 N").toJSON() } ); // some test accounts const alice = await root.createSubAccount("alice", { initialBalance: NEAR.parse("30 N").toJSON(), }); const bob = await root.createSubAccount("bob", { initialBalance: NEAR.parse("30 N").toJSON(), }); const charlie = await root.createSubAccount("charlie", { initialBalance: NEAR.parse("30 N").toJSON(), }); // Save state for test runs, it is unique for each test t.context.worker = worker; t.context.accounts = { root, contract, alice, bob, charlie }; }); test.afterEach(async (t) => { // Stop Sandbox server await t.context.worker.tearDown().catch((error) => { console.log("Failed to stop the Sandbox:", error); }); }); test("set get message", async (t) => { const { contract, alice } = t.context.accounts; await alice.call(contract, "set_status", { message: "hello" }); const aliceStatus = await contract.view("get_status", { account_id: alice }); t.is(aliceStatus, "hello"); }); test("get nonexistent message", async (t) => { const { root, contract } = t.context.accounts; const message: null = await contract.view("get_status", { account_id: root, }); t.is(message, null); }); test("root and alice have different statuses", async (t) => { const { root, contract, alice } = t.context.accounts; await root.call(contract, "set_status", { message: "world" }); const rootStatus = await contract.view("get_status", { account_id: root }); t.is(rootStatus, "world"); const aliceStatus = await contract.view("get_status", { account_id: alice }); t.is(aliceStatus, null); }); <file_sep>Status Message ============== [![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/near-examples/rust-status-message) <!-- MAGIC COMMENT: DO NOT DELETE! Everything above this line is hidden on NEAR Examples page --> This smart contract saves and records the status messages of NEAR accounts that call it. Windows users: please visit the [Windows-specific README file](README-Windows.md). ## Prerequisites Ensure `near-cli` is installed by running: ``` near --version ``` If needed, install `near-cli`: ``` npm install near-cli -g ``` Ensure `Rust` is installed by running: ``` rustc --version ``` If needed, install `Rust`: ``` curl https://sh.rustup.rs -sSf | sh ``` Install dependencies ``` npm install ``` ## Quick Start To run this project locally: 1. Prerequisites: Make sure you have Node.js ≥ 12 installed (https://nodejs.org), then use it to install yarn: `npm install --global yarn` (or just `npm i -g yarn`) 2. Run the local development server: `yarn && yarn dev` (see package.json for a full list of scripts you can run with yarn) Now you'll have a local development environment backed by the NEAR TestNet! Running yarn dev will tell you the URL you can visit in your browser to see the app. ## Building this contract To make the build process compatible with multiple operating systems, the build process exists as a script in `package.json`. There are a number of special flags used to compile the smart contract into the wasm file. Run this command to build and place the wasm file in the `res` directory: ```bash npm run build ``` **Note**: Instead of `npm`, users of [yarn](https://yarnpkg.com) may run: ```bash yarn build ``` ### Important If you encounter an error similar to: >note: the `wasm32-unknown-unknown` target may not be installed Then run: ```bash rustup target add wasm32-unknown-unknown ``` ## Using this contract ### Web app Deploy the smart contract to a specific account created with the NEAR Wallet. Then interact with the smart contract using near-api-js on the frontend. If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.testnet.near.org). Make sure you have credentials saved locally for the account you want to deploy the contract to. To perform this run the following `near-cli` command: ``` near login ``` Deploy the contract to your NEAR account: ```bash near deploy --wasmFile res/status_message.wasm --accountId YOUR_ACCOUNT_NAME ``` Build the frontend: ```bash npm start ``` If all is successful the app should be live at `localhost:1234`! ### Quickest deploy Build and deploy this smart contract to an development account. This development account will be created automatically and is not intended to be permanent. Please see the "Standard deploy" section for creating a more personalized account to deploy to. ```bash near dev-deploy --wasmFile res/status_message.wasm --helperUrl https://near-contract-helper.onrender.com ``` Behind the scenes, this is creating an account and deploying a contract to it. On the console, notice a message like: >Done deploying to dev-1234567890123 In this instance, the account is `dev-1234567890123`. A file has been created containing the key to the account, located at `neardev/dev-account`. To make the next few steps easier, we're going to set an environment variable containing this development account id and use that when copy/pasting commands. Run this command to the environment variable: ```bash source neardev/dev-account.env ``` You can tell if the environment variable is set correctly if your command line prints the account name after this command: ```bash echo $CONTRACT_NAME ``` The next command will call the contract's `set_status` method: ```bash near call $CONTRACT_NAME set_status '{"message": "aloha!"}' --accountId $CONTRACT_NAME ``` To retrieve the message from the contract, call `get_status` with the following: ```bash near view $CONTRACT_NAME get_status '{"account_id": "'$CONTRACT_NAME'"}' ``` ### Standard deploy In this option, the smart contract will get deployed to a specific account created with the NEAR Wallet. If you do not have a NEAR account, please create one with [NEAR Wallet](https://wallet.testnet.near.org). Make sure you have credentials saved locally for the account you want to deploy the contract to. To perform this run the following `near-cli` command: ``` near login ``` Deploy the contract: ```bash near deploy --wasmFile res/status_message.wasm --accountId YOUR_ACCOUNT_NAME ``` Set a status for your account: ```bash near call YOUR_ACCOUNT_NAME set_status '{"message": "aloha friend"}' --accountId YOUR_ACCOUNT_NAME ``` Get the status: ```bash near view YOUR_ACCOUNT_NAME get_status '{"account_id": "YOUR_ACCOUNT_NAME"}' ``` Note that these status messages are stored per account in a `HashMap`. See `src/lib.rs` for the code. We can try the same steps with another account to verify. **Note**: we're adding `NEW_ACCOUNT_NAME` for the next couple steps. There are two ways to create a new account: - the NEAR Wallet (as we did before) - `near create_account NEW_ACCOUNT_NAME --masterAccount YOUR_ACCOUNT_NAME` Now call the contract on the first account (where it's deployed): ```bash near call YOUR_ACCOUNT_NAME set_status '{"message": "bonjour"}' --accountId NEW_ACCOUNT_NAME ``` ```bash near view YOUR_ACCOUNT_NAME get_status '{"account_id": "NEW_ACCOUNT_NAME"}' ``` Returns `bonjour`. Make sure the original status remains: ```bash near view YOUR_ACCOUNT_NAME get_status '{"account_id": "YOUR_ACCOUNT_NAME"}' ``` ## Testing To test run: ```bash cargo test --package status-message -- --nocapture ``` <file_sep>#!/bin/bash echo ==== Quick Deploy ==== TEXT=$(printf 'y\n' | near dev-deploy --wasmFile res/status_message.wasm --helperUrl https://near-contract-helper.onrender.com) if [[ ! "$TEXT" =~ .*"Done deploying to".* ]]; then echo -e "\033[0;31m FAIL \033[0m" exit 1 else echo -e "\033[0;32m SUCCESS \033[0m" fi echo ==== Set dev account env variable ==== source neardev/dev-account.env TEXT=$(echo $CONTRACT_NAME) if [[ ! "$TEXT" =~ .*"dev-".* ]]; then echo -e "\033[0;31m FAIL \033[0m" exit 1 else echo -e "\033[0;32m SUCCESS \033[0m" fi echo ==== Set status ==== TEXT=$(near call $CONTRACT_NAME set_status '{"message": "aloha!"}' --accountId $CONTRACT_NAME) if [[ ! "$TEXT" =~ .*"To see the transaction in the transaction explorer".* ]]; then echo -e "\033[0;31m FAIL \033[0m" exit 1 else echo -e "\033[0;32m SUCCESS \033[0m" fi echo ==== Get status ==== TEXT=$(near view $CONTRACT_NAME get_status '{"account_id": "'$CONTRACT_NAME'"}') if [[ ! "$TEXT" =~ .*"aloha!".* ]]; then echo -e "\033[0;31m FAIL \033[0m" exit 1 else echo -e "\033[0;32m SUCCESS \033[0m" fi <file_sep>[package] name = "status-message" version = "0.1.0" authors = ["Near Inc <<EMAIL>>"] edition = "2018" [lib] crate-type = ["cdylib", "rlib"] [dependencies] serde = { version = "*", features = ["derive"] } serde_json = "*" near-sdk = "4.0.0" [profile.release] codegen-units = 1 # Tell `rustc` to optimize for small code size. opt-level = "z" lto = true debug = false panic = "abort" # Opt into extra safety checks on arithmetic operations https://stackoverflow.com/a/64136471/249801 overflow-checks = true <file_sep>import React from 'react'; import PropTypes from 'prop-types'; export default function Form({ onSubmit, currentUser }) { return ( <form onSubmit={onSubmit}> <fieldset id="fieldset"> <p>Add or update your status message!</p> <p className="highlight"> <label htmlFor="message">Message:</label> <input autoComplete="off" autoFocus id="message" required /> </p> <button type="submit"> Update </button> </fieldset> </form> ); } Form.propTypes = { onSubmit: PropTypes.func.isRequired, currentUser: PropTypes.shape({ accountId: PropTypes.string.isRequired }) }; <file_sep>FROM gitpod/workspace-full RUN bash -cl "rustup toolchain install stable && rustup target add wasm32-unknown-unknown" RUN bash -c ". .nvm/nvm.sh \ && nvm install v12 && nvm alias default v12"
453cfee62eacd77d49cb2e86c84fba690b73d9f1
[ "JavaScript", "Markdown", "TOML", "Rust", "TypeScript", "Dockerfile", "Shell" ]
12
JavaScript
near-examples/rust-status-message
dca9bf2c080345c7efe8dc2ff13f9b4efd45065e
c28f511caf239eb0b5e72e351f46fc323451de46
refs/heads/master
<file_sep>all: pyramid pyramid: main.o imageloader.o g++ main.o imageloader.o -w -lGL -lGLU -lglut -o pyramid main.o: main.cpp g++ -c main.cpp -w -lGL -lGLU -lglut imageloader.o: imageloader.cpp g++ -c imageloader.cpp -w -lGL -lGLU -lglut clean: rm -rf *o pyramid<file_sep>#include <iostream> #include <stdlib.h> #include <unistd.h> #include <GL/glut.h> #include "imageloader.h" using namespace std; // współczynnik skalowania GLfloat scale = 0.5; // kąty obrotu piramidy GLfloat rotatex = -30.0; GLfloat rotatey = 0.0; //tekstura GLuint texture; GLuint getTexture(Image *image) { GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); //Mapujemy obraz na teksture glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB, image->width, image->height, 0, GL_RGB, GL_UNSIGNED_BYTE, image->pixels ); return texture; } //Ustawia renderowanie sceny void initRendering() { glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); glEnable(GL_NORMALIZE); Image* image = loadBMP("assets/brick.bmp"); texture = getTexture(image); delete image; } //Obsluga zmiany rozmiaru okna void handleResize(int w, int h) { glViewport(0, 0, w, h); //Przechodzimy do ustawiania kamery glMatrixMode(GL_PROJECTION); //Ustawienie kamery glLoadIdentity(); gluPerspective( 0.0, (double)w / (double)h, 1.0, 200.0 ); } //Rysowanie sceny void drawScene() { //Czyscimy ekan glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0f, -0.4f, 0.0f); //<NAME> glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glColor3f(1.0f, 1.0f, 1.0f); glScalef(scale, scale, scale); glRotatef(rotatex, 1.0, 0, 0); glRotatef(rotatey, 0, 1.0, 0); glBegin(GL_QUADS); glVertex3f(-1.0, 0.0, 1.0); glVertex3f(1.0, 0.0, 1.0); glVertex3f(1.0, 0.0, -1.0); glVertex3f(-1.0, 0.0, -1.0); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0, 0.0, 1.0); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0, 0.0, 1.0); glTexCoord2f(0.5f, 1.0f); glVertex3f(0.0, 2.0, 0.0); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0, 0.0, 1.0); glTexCoord2f(1.0f, 0.0f); glVertex3f(1.0, 0.0, -1.0); glTexCoord2f(0.5f, 1.0f); glVertex3f(0.0, 2.0, 0.0); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(1.0, 0.0, -1.0); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0, 0.0, -1.0); glTexCoord2f(0.5f, 1.0f); glVertex3f(0.0, 2.0, 0.0); glEnd(); glBegin(GL_TRIANGLES); glNormal3f(0.0f, 0.0f, 1.0f); glTexCoord2f(0.0f, 0.0f); glVertex3f(-1.0, 0.0, -1.0); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1.0, 0.0, 1.0); glTexCoord2f(0.5f, 1.0f); glVertex3f(0.0, 2.0, 0.0); glEnd(); glutSwapBuffers(); } void update(int value) { rotatey -= 0.5; if (rotatey <= -360) { rotatey = 0; } glutPostRedisplay(); glutTimerFunc(25, update, 0); } int main(int argc, char** argv) { //Uruchamiamy GLUT glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 400); //Wielkosc okna //Tworzymy okno glutCreateWindow("PPG - Piramida - Projekt zaliczeniowy"); initRendering(); //Podlaczamy handlery glutDisplayFunc(drawScene); glutReshapeFunc(handleResize); glutTimerFunc(25, update, 0); glutMainLoop(); return 0; } <file_sep> #include <GLTools.h> // OpenGL toolkit #include <GLShaderManager.h> #include <GLFrustum.h> #include <GLBatch.h> #include <GLFrame.h> #include <GLMatrixStack.h> #include <GLGeometryTransform.h> #include <StopWatch.h> #include <glu.h> #define FREEGLUT_STATIC #include "glut.h" // Windows FreeGlut equivalent //------------------------------------------------------------------------------------------------------------ GLuint shader; M3DMatrix44f mtxModelView; GLint modelViewMtxLoc; GLFrame cameraFrame; GLFrustum viewFrustum; M3DMatrix44f mtxCamera; float fAngle; void SetUpFrame(GLFrame &frame, const M3DVector3f origin, const M3DVector3f forward, const M3DVector3f up) { frame.SetOrigin(origin); frame.SetForwardVector(forward); M3DVector3f side,oUp; m3dCrossProduct3(side,forward,up); m3dCrossProduct3(oUp,side,forward); frame.SetUpVector(oUp); frame.Normalize(); } void LookAt(GLFrame &frame, const M3DVector3f eye, const M3DVector3f at, const M3DVector3f up) { M3DVector3f forward; m3dSubtractVectors3(forward, at, eye); SetUpFrame(frame, eye, forward, up); } void ChangeSize(int w, int h) { glViewport(0, 0, w, h); viewFrustum.SetPerspective(60.0f,(float)w/h,0.1f,10.f); } void SetupRC() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); shader = gltLoadShaderPairWithAttributes("shaders\\shader.vp", "shaders\\shader.fp", 2, GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_COLOR, "vColor"); fprintf(stdout, "GLT_ATTRIBUTE_VERTEX : %d\nGLT_ATTRIBUTE_COLOR : %d \n", GLT_ATTRIBUTE_VERTEX, GLT_ATTRIBUTE_COLOR); modelViewMtxLoc = glGetUniformLocation(shader, "MVMatrix"); if(modelViewMtxLoc==-1) { fprintf(stderr,"uniform MVMatrix could not be found\n"); } M3DVector3f forward = {-5.0f, -5.0f, -5.0f}; M3DVector3f origin = {5.0f, 5.0f, 5.0f}; M3DVector3f up = {0.0f, 0.0f, 1.0f}; SetUpFrame(cameraFrame, origin, forward, up); fAngle = 0; glEnable(GL_DEPTH_TEST); } void makePyramid() { glBegin(GL_QUADS); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.3, 0.3, 0.3); glVertex3f(-1.5f, -1.5f, 0.0f); glVertex3f( 1.5f, -1.5f, 0.0f); glVertex3f( 1.5f, 1.5f, 0.0f); glVertex3f(-1.5f, 1.5f, 0.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 0.0, 0.0); glVertex3f(-1.5f, -1.5f, 0.0f); glVertex3f( 1.5f, -1.5f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.0, 1.0, 0.0); glVertex3f(1.5f, -1.5f, 0.0f); glVertex3f(1.5f, 1.5f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 1.0, 0.0); glVertex3f( 1.5f, 1.5f, 0.0f); glVertex3f(-1.5f, 1.5f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.0, 0.0, 1.0); glVertex3f(-1.5f, 1.5f, 0.0f); glVertex3f(-1.5f,-1.5f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.0f); glEnd(); } void RenderScene(void) { // Clear the window glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); glUseProgram(shader); float eye[3]; float at[]={0,0,0},up[]={0,0,5}; eye[0]=5.8f*cos(fAngle); eye[1]=4.8f*sin(fAngle); eye[2]=5.0f; fAngle+= -0.01; if(fAngle<1) { fAngle=360; } LookAt(cameraFrame,eye,at,up); cameraFrame.GetCameraMatrix(mtxCamera); M3DMatrix44f ViewProjectionMatrix; m3dMatrixMultiply44(ViewProjectionMatrix,viewFrustum.GetProjectionMatrix(),mtxCamera); glUniformMatrix4fv(modelViewMtxLoc,1,GL_FALSE,ViewProjectionMatrix); makePyramid(); // Make buffer swap to display back buffer glutSwapBuffers(); } void timerFunction(int param) { glutPostRedisplay(); glutTimerFunc(16, timerFunction, 0); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(800, 600); glutCreateWindow("proj2"); glutReshapeFunc(ChangeSize); glutDisplayFunc(RenderScene); glutTimerFunc(0, timerFunction, 0); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return 1; } SetupRC(); glutMainLoop(); return 0; } <file_sep>#include "draw.h" #include <GLTools.h> #include <glu.h> #define FREEGLUT_STATIC #include "glut.h" void drawPyramid() { glBegin(GL_QUADS); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.3, 0.3, 0.3); glVertex3f(-1.0f, -1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 0.0f); glVertex3f( 1.0f, 1.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 0.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.0, 1.0, 0.0); glVertex3f(-1.0f, -1.0f, 0.0f); glVertex3f( 1.0f, -1.0f, 0.0f); glVertex3f( 0.0f, 0.0f, 2.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 0.0, 0.0); glVertex3f(1.0f, -1.0f, 0.0f); glVertex3f(1.0f, 1.0f, 0.0f); glVertex3f(0.0f, 0.0f, 2.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 1.0, 0.0); glVertex3f( 1.0f, 1.0f, 0.0f); glVertex3f(-1.0f, 1.0f, 0.0f); glVertex3f( 0.0f, 0.0f, 2.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.0, 0.0, 1.0); glVertex3f(-1.0f, 1.0f, 0.0f); glVertex3f(-1.0f,-1.0f, 0.0f); glVertex3f( 0.0f, 0.0f, 2.0f); glEnd(); } void drawSmallPyramid() { glBegin(GL_QUADS); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.3, 0.3, 0.3); glVertex3f(-0.5f, -0.5f, 0.0f); glVertex3f( 0.5f, -0.5f, 0.0f); glVertex3f( 0.5f, 0.5f, 0.0f); glVertex3f(-0.5f, 0.5f, 0.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.0, 1.0, 0.0); glVertex3f(-0.5f, -0.5f, 0.0f); glVertex3f( 0.5f, -0.5f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 0.0, 0.0); glVertex3f(0.5f, -0.5f, 0.0f); glVertex3f(0.5f, 0.5f, 0.0f); glVertex3f(0.0f, 0.0f, 1.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 1.0, 1.0, 0.0); glVertex3f( 0.5f, 0.5f, 0.0f); glVertex3f(-0.5f, 0.5f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.0f); glEnd(); glBegin(GL_TRIANGLES); glVertexAttrib3f(GLT_ATTRIBUTE_COLOR, 0.0, 0.0, 1.0); glVertex3f(-0.5f, 0.5f, 0.0f); glVertex3f(-0.5f,-0.5f, 0.0f); glVertex3f( 0.0f, 0.0f, 1.0f); glEnd(); }<file_sep>#ifndef DRAW_H_ #define DRAW_H_ void drawPyramid(); void drawSmallPyramid(); #endif<file_sep># Hello World - - - <NAME>
e39e3f9037877b556e68f8fccefdfb57f9583e09
[ "Markdown", "C", "Makefile", "C++" ]
6
Makefile
codepik/Procesory-Graf
6ab451b9e3e19e5707d024d8f35bf069c4f80bb0
78b1c6c31ae054c1926a794c140987fee12bb6ac
refs/heads/main
<file_sep>--- title: "datacleaning_5" output: html_document --- Making some changes to test pushes ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` crtl/alt/i is the keyboard shortcut for a new chunk ``` {r librarycalls, message = FALSE} library(dplyr) library(tidyr) library(readr) ``` ## Data Sources Read in the data from [KNB] https://knb.ecoinformatics.org/knb/d1/mn/v2/object/df35b.302.1" ```{r} catch_original <- read.csv("https://knb.ecoinformatics.org/knb/d1/mn/v2/object/df35b.302.1") glimpse(catch_original) ``` ## Clean and Reshape Data *remove unnecessary columns *check column types *reshape data ```{r} catch_data <- catch_original %>% # select(Region, Year, Chinook, Sockeye, Coho, Pink, Chum) select(-All, -notesRegCode) glimpse(catch_data) ``` ```{r} catch_clean <- catch_data %>% mutate(Chinook = as.integer(Chinook)) ``` error, 1 chinook was coerced into n/a--code below detects where the issue is ```{r} i <- which(is.na(catch_clean$Chinook)) i ``` Fixing it: First, replacing the I with 1, then, changing case type to integer ```{r} catch_clean <- catch_data %>% mutate(Chinook = if_else(Chinook == "I", "1", Chinook)) %>% mutate(Chinook = as.integer(Chinook)) ``` ```{r} catch_long <- catch_clean %>% pivot_longer(cols = -c(Region, Year), names_to = "species", values_to = "catch") ``` ```{r} catch_wide <- catch_long %>% pivot_wider(names_from = Region, values_from = catch) ``` ```{r} #catch_long <- catch_long %>% #rename(catch_thousands = catch) #mutate(catch_thousands = catch_thousands * 1000) ``` ```{r} mean_region <- catch_long %>% group_by(Region) %>% summarise(catch_mean = mean(catch)) ``` ```{r} region_defs <- read.csv("https://knb.ecoinformatics.org/knb/d1/mn/v2/object/df35b.303.1") %>% select(code, mgmtArea) ``` ```{r} catch_joined <- left_join(catch_long, region_defs, by = c("Region" = "code")) ``` ```{r} region_defs <- region_defs %>% rename(Region = code, Region_Name = mgmtArea) ``` ```{r} catch_joined <- left_join(catch_long, region_defs, by = c("Region")) head(catch_joined) ``` ```{r} sites_df <- data.frame(site = c("HAW-101", "HAW-103", "OAH-320", "OAH-219", "MAI-039")) sites_df %>% separate(site, c("island", "site_number"), "-") ``` ```{r} cities_df <- data.frame(city = c("Juneau AK", "Sitka AK", "Anchorage AK")) cities_df %>% separate(city, c("city", "state_code"), " ") ``` ```{r} dates_df <- data.frame(year = c("1930", "1930", "1930"), month = c("12", "12", "12"), day = c("14", "15", "16")) dates_df %>% unite(date, year, month, day, sep = "-") ``` ## Join to Regions and Definitions <file_sep>library(dplyr) ##emp_wq <- read.csv('https://portal.edirepository.org/nis/dataviewer?packageid=edi.458.4&entityid=98b400de8472d2a3d2e403141533a2cc') ##emp_stations <- read.csv('https://portal.edirepository.org/nis/dataviewer?packageid=edi.458.4&entityid=827aa171ecae79731cc50ae0e590e5af') integratedwq <- read.csv('https://portal.edirepository.org/nis/dataviewer?packageid=edi.731.1&entityid=6c5f35b1d316e39c8de0bfadfb3c9692') ybp_chloro <- read.csv('https://github.com/jessicaguo/swg-21-connectivity/blob/dc9c19018e43f3e2dccc39afba5e0a2628e15bd0/data/YBFMP_Nutrients_Chlorophyll_2009_2019.csv') library(lubridate) devtools::install_github("ryanpeek/wateRshedTools") library(wateRshedTools) integrated_wq_filtered_WET <- integratedwq %>% mutate(Date=ymd(Date)) %>% mutate(Month=month(Date)) %>% filter(Month==c(10, 11, 12, 1, 2, 3, 4, 5)) %>% filter(!is.na(Chlorophyll)) %>% filter(Date>ymd("1998-01-01")) wet_lm <- lm(integrated_wq_filtered_WET$Chlorophyll~integrated_wq_filtered_WET$Date) plot(integrated_wq_filtered_WET$Chlorophyll~integrated_wq_filtered_WET$Date) summary(wet_lm) integrated_wq_filtered_ALL <- integratedwq %>% mutate(Date=ymd(Date)) %>% mutate(Month=month(Date)) %>% filter(!is.na(Chlorophyll)) %>% filter(Date>ymd("1998-01-01")) ##lm(formula = integrated_wq_filtered_ALL$Chlorophyll ~ integrated_wq_filtered_ALL$Date) ##Residuals: ## Min 1Q Median 3Q Max ##-7.067 -3.373 -1.867 0.344 255.067 ##Coefficients: ## Estimate Std. Error t value Pr(>|t|) ##(Intercept) 1.189e+01 4.354e-01 27.31 <2e-16 *** ## integrated_wq_filtered_ALL$Date -4.419e-04 2.956e-05 -14.95 <2e-16 *** ## --- ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ##Residual standard error: 9.035 on 17652 degrees of freedom ##Multiple R-squared: 0.01251, Adjusted R-squared: 0.01245 ##F-statistic: 223.5 on 1 and 17652 DF, p-value: < 2.2e-16 integrated_wq_filtered_ALL <- integratedwq %>% mutate(Date=ymd(Date)) %>% mutate(Month=month(Date)) %>% filter(!is.na(Chlorophyll)) ALL_lm <- lm(integrated_wq_filtered_ALL$Chlorophyll~integrated_wq_filtered_ALL$Date) plot(integrated_wq_filtered_ALL$Chlorophyll~integrated_wq_filtered_ALL$Date) summary(ALL_lm) ##Residuals: ## Min 1Q Median 3Q Max ##-7.240 -3.504 -2.052 0.085 148.210 ##Coefficients: ## Estimate Std. Error t value Pr(>|t|) ##(Intercept) 13.1231811 1.5475808 8.480 < 2e-16 *** ## integrated_wq_filtered_WET$Date -0.0005163 0.0001052 -4.909 1.02e-06 *** --- ## Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1 ##Residual standard error: 9.319 on 1480 degrees of freedom ##Multiple R-squared: 0.01602, Adjusted R-squared: 0.01536 ##F-statistic: 24.1 on 1 and 1480 DF, p-value: 1.017e-06 ##Adding Water Year Info integrated_wq_filtered_ALL <- add_WYD(integrated_wq_filtered_ALL, "Date") plot(integrated_wq_filtered_ALL$Chlorophyll~integrated_wq_filtered_ALL$Date) integrated_wq_filtered_1998 <- integrated_wq_filtered_ALL %>% mutate(Date=ymd(Date)) %>% filter(!is.na(Chlorophyll)) %>% filter(Date>ymd("1998-01-01")) plot(integrated_wq_filtered_1998$Chlorophyll~integrated_wq_filtered_1998$Date) plot(integrated_wq_filtered_1998$Chlorophyll~integrated_wq_filtered_1998$Temperature) plot(integrated_wq_filtered_1998$Chlorophyll~integrated_wq_filtered_1998$Salinity) boxplot(integrated_wq_filtered_1998$Chlorophyll~integrated_wq_filtered_1998$Source, outline=FALSE) boxplot(integrated_wq_filtered_1998$Date~integrated_wq_filtered_1998$Source) chloro_time <- lm(integrated_wq_filtered_1998$Chlorophyll~integrated_wq_filtered_1998$Date) summary(chloro_time) unique(integrated_wq_filtered_1998[c("Source")]) ##October 1st-May 30--Filter by month usbr_wq_filtered <- integrated_wq_filtered_1998 %>% filter(Station==c('USBR 16', 'USBR 34', 'USBR 44')) ##16, 34 and 44 are downstream ##2012-2019 ##Only yields 5 stations usgs_wq <- integrated_wq_filtered_1998 %>% filter(Source=="USGS") usgs_wq_657 <- integrated_wq_filtered_1998 <- integratedwq %>% mutate(Date=ymd(Date)) %>% filter(!is.na(Chlorophyll)) %>% filter(Date>ymd("1998-01-01")) %>% filter(Source=="USGS")%>% filter(Station=="USGS 657") usgs_wq_649 <- integrated_wq_filtered_1998 <- integratedwq %>% mutate(Date=ymd(Date)) %>% filter(!is.na(Chlorophyll)) %>% filter(Date>ymd("1998-01-01")) %>% filter(Source=="USGS")%>% filter(Station=="USGS 649") emp_wq <- integrated_wq_filtered_1998 %>% filter(Source=="EMP") plot(usgs_wq_657$Chlorophyll~usgs_wq_657$Date, ylim=c(0,10)) plot(usgs_wq_649$Chlorophyll~usgs_wq_649$Date, ylim=c(0,10)) usgs_lm <- lm(usgs_wq_649$Chlorophyll~usgs_wq_649$Date) summary(usgs_lm) unique(usgs_wq[c("Station")]) emp_wq <- integrated_wq_filtered_1998 <- integratedwq %>% mutate(Date=ymd(Date)) %>% filter(!is.na(Chlorophyll)) %>% filter(Date>ymd("1998-01-01")) %>% filter(Source=="EMP") boxplot() usbr_wq <- integrated_wq_filtered <- integratedwq %>% mutate(Date=ymd(Date)) %>% filter(!is.na(Chlorophyll)) %>% filter(Date>ymd("2013-10-01")) %>% filter(Source=="USBR") ###MAP CODE library(sf) library(mapview) mapviewOptions(fgb=TRUE) ##USBR all sites map df_cl_sf <- usbr_wq %>% filter(!is.na(Latitude)) %>% st_as_sf(coords=c("Longitude", "Latitude"), crs=4326, remove=FALSE) %>% distinct(Station, .keep_all = T) mapview(df_cl_sf, zcol="Station") ##EMP df_cl_sf <- emp_wq %>% filter(!is.na(Latitude)) %>% st_as_sf(coords=c("Longitude", "Latitude"), crs=4326, remove=FALSE) %>% distinct(Station, .keep_all = T) mapview(df_cl_sf, zcol="Station") ##******** ##************ ##**************SPATIAL AUTOCORRELATION library(ape) <file_sep>--- title: "chapple_RMD_training" output: html_document --- ~~sarah test~~ ```{r setup, include=FALSE} knitr::opts_chunk$set(echo = TRUE) ``` ```{r} y <- 3+3 z <- 4+4 z ``` ctrl + alt + i for a new chunk play button runs all lines in chunk blue yarn at top is knitting to create final RMD doc ```{r} ```
88221bd46ddf6d4cff7768ef726ad968d66069f9
[ "R", "RMarkdown" ]
3
RMarkdown
dylanchapple1/training_dchapple
a7ade28fbfc858dcd936abc691272f0724ae0c00
9a6f9c263f4236dab94a4eca4c24d40e455c98d9
refs/heads/master
<repo_name>ofiriluz/clogger<file_sep>/src/CWriters/CSysLogWriter.cpp /** * @brief * * @file CSysLogWriter.cpp * @author <NAME> * @date 2018-07-10 */ #include <CLogger/CWriters/CSysLogWriter.h> namespace CLogger { CSysLogWriter::CSysLogWriter(const CWriterConfig & config) :CWriter(config) { syslog_name_ = config.get_option_default(CWriterOption::WO_CONSOLE_DISABLE_COLOR, "CLogger"); } CSysLogWriter::~CSysLogWriter() { } void CSysLogWriter::write(const CLog & log, const CChannelPtr & channel) { // Check if the stream is not null if(log.get_stream()) { // Create a temp buffer for date time formatting char dtf[1024]; // Format the log time std::time_t time = std::chrono::system_clock::to_time_t(log.get_time_created()); std::strftime(dtf, sizeof(dtf), "[%d/%m/%Y %H:%M:%S]",std::localtime(&time));; std::stringstream ss; ss << dtf << "[" << channel->get_channel_name() << "][" << CLog::level_to_string(log.get_log_level()) << "]: " << log.get_stream()->str(); // Write to syslog openlog(syslog_name_.c_str(), LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1); syslog(LOG_INFO, ss.str().c_str(), NULL); closelog(); } } } <file_sep>/include/CLogger/CLog.h /** * @brief * * @file CLog.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CLOG_H_ #define CLOGGER_CLOG_H_ #include <iostream> #include <sstream> #include <string> #include <chrono> namespace CLogger { class CLogger; enum class CLogLevel : uint8_t { LL_DEBUG, LL_INFO, LL_NOTICE, LL_WARNING, LL_ERROR }; class CLog { private: std::ostringstream *stream_; CLogLevel log_level_; const CLogger &logger_; std::chrono::time_point<std::chrono::system_clock> time_created_; private: /** * @brief * Private Constructor, Only the logger can create Logs * * @param log_level * @param logger */ CLog(const CLogLevel &log_level, const CLogger &logger); public: /** * @brief Destroy the PSLog object * */ virtual ~CLog(); /** * @brief * Converts a given log level to string representation * * @param level * @return std::string */ static std::string level_to_string(const CLogLevel &level); /** * @brief * Converts a given log level string to its enum * * @param level_str * @return CLogLevel */ static CLogLevel string_to_level(const std::string &level_str); /** * @brief * Getter for this log's creation time * * @return const std::chrono::time_point<std::chrono::system_clock>& */ const std::chrono::time_point<std::chrono::system_clock> &get_time_created() const; /** * @brief * Getter for this log's stream * * @return const std::ostringstream* */ const std::ostringstream *get_stream() const; /** * @brief * Getter for this log's level * * @return CLogLevel */ const CLogLevel &get_log_level() const; /** * @brief * Writer stream operator * * @tparam T * @param value * @return CLog */ template <class T> CLog &operator<<(const T &value) { if (stream_) { *stream_ << value; } return *this; } friend class CLogger; }; } #endif /* CLOGGER_CLOG_H_ */ <file_sep>/src/CWriters/CConsoleWriter.cpp /** * @brief * * @file CConsoleWriter.cpp * @author <NAME> * @date 2018-07-10 */ #include <CLogger/CWriters/CConsoleWriter.h> namespace CLogger { void CConsoleWriter::configure_log_color(const CLogLevel & log_level) { switch (log_level) { case CLogLevel::LL_DEBUG: std::cout << "\e[32m"; break; case CLogLevel::LL_INFO: std::cout << "\e[36m"; break; case CLogLevel::LL_NOTICE: std::cout << "\e[34m"; break; case CLogLevel::LL_WARNING: std::cout << "\e[33m"; break; case CLogLevel::LL_ERROR: std::cout << "\e[31m"; break; } } void CConsoleWriter::reset_log_color() { std::cout << "\e[39m"; } CConsoleWriter::CConsoleWriter(const CWriterConfig & config) :CWriter(config) { disable_console_color_ = static_cast<bool>(config.get_option_default(CWriterOption::WO_CONSOLE_DISABLE_COLOR,0)); } CConsoleWriter::~CConsoleWriter() { } void CConsoleWriter::write(const CLog & log, const CChannelPtr & channel) { // Check if the stream is not null if(log.get_stream()) { // Create a temp buffer for date time formatting char dtf[1024]; // Set output buffer if(!disable_console_color_) { configure_log_color(log.get_log_level()); } // Format the log time std::time_t time = std::chrono::system_clock::to_time_t(log.get_time_created()); std::strftime(dtf, sizeof(dtf), "[%d/%m/%Y %H:%M:%S]",std::localtime(&time));; // Output to console std::cout << dtf << "[" << channel->get_channel_name() << "][" << CLog::level_to_string(log.get_log_level()) << "]: " << log.get_stream()->str(); // Reset output color if(!disable_console_color_) { reset_log_color(); } std::cout << std::endl; } } } <file_sep>/include/CLogger/CWriters/CWriter.h /** * @brief * * @file CWriter.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CWRITERS_CWRITER_H_ #define CLOGGER_CWRITERS_CWRITER_H_ #include <CLogger/CChannel.h> #include <CLogger/CConfig.h> namespace CLogger { class CWriter { private: const CWriterConfig config_; protected: /** * @brief * Protected Getter for the writer config * Only inherited writers may see the config and use it * * @return const CWriterConfig& */ const CWriterConfig &get_config() const; public: /** * @brief Construct a new CWriter object * * @param config */ CWriter(const CWriterConfig &config); /** * @brief Destroy the CWriter object * */ virtual ~CWriter(); /** * @brief * Writes the contents of a given log and its channel to this writer * @param log * @param channel */ virtual void write(const CLog &log, const CChannelPtr &channel) = 0; }; typedef std::shared_ptr<CWriter> CWriterPtr; } #endif /* CLOGGER_CWRITERS_CWRITER_H_ */ <file_sep>/src/CConfig.cpp /** * @brief * * @file CConfig.cpp * @author <NAME> * @date 2018-07-11 */ #include <CLogger/CConfig.h> namespace CLogger { CWriterConfig::CWriterConfig(const std::string &writer_name, const CWriterType &writer_type) : writer_type_(writer_type), writer_name_(writer_name) { } CWriterConfig::~CWriterConfig() { } void CWriterConfig::set_option(const CWriterOption &option, const std::string &value) { options_[option] = value; } void CWriterConfig::set_option(const CWriterOption &option, int value) { set_option(option, CConfig::convert_from<int>(value)); } void CWriterConfig::set_option(const CWriterOption &option, double value) { set_option(option, CConfig::convert_from<double>(value)); } bool CWriterConfig::remove_option(const CWriterOption &option) { if (has_option(option)) { options_.erase(option); return true; } return false; } bool CWriterConfig::has_option(const CWriterOption &option) const { return options_.find(option) != options_.end(); } bool CWriterConfig::get_option(const CWriterOption &option, std::string &value) const { if (has_option(option)) { value = options_.at(option); return true; } return false; } bool CWriterConfig::get_option(const CWriterOption &option, int &value) const { std::string s; if (get_option(option, s)) { try { value = CConfig::convert_to<int>(s); return true; } catch (...) { return false; } } return false; } bool CWriterConfig::get_option(const CWriterOption &option, double &value) const { std::string s; if (get_option(option, s)) { try { value = CConfig::convert_to<double>(s); return true; } catch (...) { return false; } } return false; } std::string CWriterConfig::get_option_default(const CWriterOption &option, const std::string &default_value) const { if (has_option(option)) { return options_.at(option); } return default_value; } int CWriterConfig::get_option_default(const CWriterOption &option, int default_value) const { std::string s = get_option_default(option, CConfig::convert_from<int>(default_value)); try { int i = CConfig::convert_to<int>(s); return i; } catch (...) { return default_value; } } double CWriterConfig::get_option_default(const CWriterOption &option, double default_value) const { std::string s = get_option_default(option, CConfig::convert_from<double>(default_value)); try { double i = CConfig::convert_to<double>(s); return i; } catch (...) { return default_value; } } std::string CWriterConfig::get_writer_name() const { return writer_name_; } CWriterType CWriterConfig::get_writer_type() const { return writer_type_; } CConfig::CConfig() { } CConfig::~CConfig() { } void CConfig::set_option(const CLoggerOption &option, const std::string &value) { logger_options_[option] = value; } void CConfig::set_option(const CLoggerOption &option, int value) { set_option(option, convert_from<int>(value)); } void CConfig::set_option(const CLoggerOption &option, double value) { set_option(option, convert_from<double>(value)); } bool CConfig::has_writer(const std::string &writer_name) const { for (auto &&w : writer_configs_) { if (w.get_writer_name() == writer_name) { return true; } } return false; } const std::vector<CWriterConfig> &CConfig::get_writers() const { return writer_configs_; } void CConfig::add_writer(const CWriterConfig &writer) { writer_configs_.push_back(writer); } bool CConfig::remove_option(const CLoggerOption &option) { if (!has_option(option)) { return false; } logger_options_.erase(option); return true; } bool CConfig::has_option(const CLoggerOption &option) const { return logger_options_.find(option) != logger_options_.end(); } bool CConfig::get_option(const CLoggerOption &option, std::string &value) const { if (has_option(option)) { value = logger_options_.at(option); return true; } return false; } bool CConfig::get_option(const CLoggerOption &option, int &value) const { std::string s; if (get_option(option, s)) { value = convert_to<int>(s); return true; } return false; } bool CConfig::get_option(const CLoggerOption &option, double &value) const { std::string s; if (get_option(option, s)) { value = convert_to<double>(s); return true; } return false; } void CConfig::remove_writer(const std::string &writer_name) { for (size_t i = 0; i < writer_configs_.size(); i++) { if (writer_configs_[i].get_writer_name() == writer_name) { writer_configs_.erase(writer_configs_.begin() + i); return; } } } } <file_sep>/src/CWriters/CWriter.cpp /** * @brief * * @file CWriter.cpp * @author <NAME> * @date 2018-07-11 */ #include <CLogger/CWriters/CWriter.h> namespace CLogger { const CWriterConfig &CWriter::get_config() const { return config_; } CWriter::CWriter(const CWriterConfig &config) : config_(config) { } CWriter::~CWriter() { } } <file_sep>/src/CWriters/CWriterFactory.cpp /** * @brief * * @file CWriterFactory.cpp * @author <NAME> * @date 2018-07-11 */ #include <CLogger/CWriters/CWriterFactory.h> namespace CLogger { CWriterFactory::CWriterFactory() { } CWriterFactory &CWriterFactory::get_instance() { static CWriterFactory factory; return factory; } CWriterFactory::~CWriterFactory() { } CWriterPtr CWriterFactory::create_writer(const CWriterConfig &writer_config) { if (writer_config.get_writer_type() == CWriterType::LW_CONSOLE_WRITER) { return CWriterPtr(new CConsoleWriter(writer_config)); } else if (writer_config.get_writer_type() == CWriterType::LW_FILE_WRITER) { return CWriterPtr(new CFileWriter(writer_config)); } else if(writer_config.get_writer_type() == CWriterType::LW_SYSLOG_WRITER) { return CWriterPtr(new CSysLogWriter(writer_config)); } return CWriterPtr(); } } <file_sep>/src/CLogger.cpp /** * @brief * * @file CLogger.cpp * @author your name * @date 2018-07-11 */ #include <CLogger/CLogger.h> #include <CLogger/CManager.h> namespace CLogger { void CLogger::write_log(const CLog &log) const { CManager::get_instance().write(log, logger_channel_); } CLogger::CLogger(const std::string &channel) { logger_channel_ = CManager::get_instance().get_channel(channel); } CLogger::~CLogger() { } const CChannelPtr &CLogger::get_logger_channel() const { return logger_channel_; } CLog CLogger::debug() { return CLog(CLogLevel::LL_DEBUG, *this); } CLog CLogger::info() { return CLog(CLogLevel::LL_INFO, *this); } CLog CLogger::notice() { return CLog(CLogLevel::LL_NOTICE, *this); } CLog CLogger::warning() { return CLog(CLogLevel::LL_WARNING, *this); } CLog CLogger::error() { return CLog(CLogLevel::LL_ERROR, *this); } }<file_sep>/cmake/CLoggerConfig.cmake.in get_filename_component(CLogger_CMAKE_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH) include(CMakeFindDependencyMacro) list(APPEND CMAKE_MODULE_PATH ${CLogger_CMAKE_DIR}) list(REMOVE_AT CMAKE_MODULE_PATH -1) if(NOT TARGET CLogger::CLogger) include("${CLogger_CMAKE_DIR}/CLoggerTargets.cmake") endif() set(CLogger_LIBRARIES CLogger::CLogger)<file_sep>/CMakeLists.txt CMAKE_MINIMUM_REQUIRED(VERSION 3.5) PROJECT(clogger VERSION 1.1.0 LANGUAGES CXX) INCLUDE_DIRECTORIES(include) ADD_LIBRARY(clogger src/CChannel.cpp src/CConfig.cpp src/CLog.cpp src/CLogger.cpp src/CManager.cpp src/CWriters/CWriter.cpp src/CWriters/CConsoleWriter.cpp src/CWriters/CFileWriter.cpp src/CWriters/CSysLogWriter.cpp src/CWriters/CWriterFactory.cpp) ADD_LIBRARY(CLogger::clogger ALIAS clogger) TARGET_INCLUDE_DIRECTORIES(clogger PUBLIC $<INSTALL_INTERFACE:include> $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include> PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src ) TARGET_COMPILE_FEATURES(clogger PRIVATE cxx_auto_type) TARGET_COMPILE_OPTIONS(clogger PRIVATE $<$<CXX_COMPILER_ID:GNU>:-Wall>) INCLUDE(GNUInstallDirs) SET(INSTALL_CONFIGDIR ${CMAKE_INSTALL_LIBDIR}/cmake/CLogger) INSTALL(TARGETS clogger EXPORT clogger-targets LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} ) SET_TARGET_PROPERTIES(clogger PROPERTIES EXPORT_NAME CLogger) INSTALL(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) INSTALL(EXPORT clogger-targets FILE CLoggerTargets.cmake NAMESPACE CLogger:: DESTINATION ${INSTALL_CONFIGDIR} ) INCLUDE(CMakePackageConfigHelpers) WRITE_BASIC_PACKAGE_VERSION_FILE( ${CMAKE_CURRENT_BINARY_DIR}/CLoggerConfigVersion.cmake VERSION ${PROJECT_VERSION} COMPATIBILITY AnyNewerVersion ) INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/CLoggerConfig.cmake ${CMAKE_CURRENT_BINARY_DIR}/CLoggerConfigVersion.cmake DESTINATION ${INSTALL_CONFIGDIR} ) CONFIGURE_PACKAGE_CONFIG_FILE( ${CMAKE_CURRENT_LIST_DIR}/cmake/CLoggerConfig.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/CLoggerConfig.cmake INSTALL_DESTINATION ${INSTALL_CONFIGDIR} ) EXPORT(EXPORT clogger-targets FILE ${CMAKE_CURRENT_BINARY_DIR}/CLoggerTargets.cmake NAMESPACE CLogger::) EXPORT(PACKAGE CLogger) ADD_SUBDIRECTORY(tests)<file_sep>/include/CLogger/CWriters/CConsoleWriter.h /** * @brief * * @file CConsoleWriter.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CWRITERS_CCONSOLEWRITER_H_ #define CLOGGER_CWRITERS_CCONSOLEWRITER_H_ #include <CLogger/CWriters/CWriter.h> #include <iostream> namespace CLogger { class CConsoleWriter : public CWriter { private: bool disable_console_color_; private: /** * Changes the console log color for the fitting level * @param log_level */ void configure_log_color(const CLogLevel &log_level); /** * Resets the log color */ void reset_log_color(); public: /** * Constructor * @param config */ CConsoleWriter(const CWriterConfig &config); /** * Destructor */ virtual ~CConsoleWriter(); /** * Writes the contents of the log to the console * @see CWriter::write * @param log * @param channel */ virtual void write(const CLog &log, const CChannelPtr &channel); }; } #endif /* CLOGGER_CWRITERS_CCONSOLEWRITER_H_ */ <file_sep>/src/CChannel.cpp /** * @brief * * @file CChannel.cpp * @author <NAME> * @date 2018-07-11 */ #include <CLogger/CChannel.h> namespace CLogger { CChannel::CChannel(const std::string &channel_name, const CLogLevel &channel_level) : channel_name_(channel_name), channel_level_(channel_level) { } CChannel::~CChannel() { } CLogLevel CChannel::get_log_level() const { return channel_level_; } void CChannel::set_log_level(const CLogLevel &channel_level) { channel_level_ = channel_level; } std::string CChannel::get_channel_name() const { return channel_name_; } } <file_sep>/include/CLogger/CWriters/CFileWriter.h /** * @brief * * @file CFileWriter.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CWRITERS_CFILEWRITER_H_ #define CLOGGER_CWRITERS_CFILEWRITER_H_ #include <CLogger/CWriters/CWriter.h> #include <iomanip> #include <ctime> #include <sys/stat.h> #include <string.h> #include <dirent.h> #include <libgen.h> #include <fstream> namespace CLogger { class CFileWriter : public CWriter { private: class CFile { public: std::ofstream stream; uint32_t index; CFile(); virtual ~CFile(); }; private: std::string folder_name_prefix_; std::string log_path_; long size_per_file_; uint32_t max_files_; std::map<std::string, std::shared_ptr<CFile>> current_files_; bool seperate_channel_to_files_; private: /** * @brief * * @param dir * @param mode * @return int */ int recursive_folder_creation(const char *dir, mode_t mode); /** * @brief * Creates the log path which files will be written to, saves it to mLogPath * Appends the current time to the name aswell */ void create_log_path(); /** * @brief * Creates the log directory if does not exist */ void create_log_directory(); /** * @brief * Switches to a new stream when the file size has reached the max * The old stream will saved and closed and a new stream will be opened for a new file * * @param channel */ void switch_stream(const std::string &channel); public: /** * @brief Construct a new CFileWriter object * * @param config */ CFileWriter(const CWriterConfig &config); /** * @brief Destroy the CFileWriter object * */ virtual ~CFileWriter(); /** * @brief * Writes the contents of the log to file / files * @see CWriter::write * * @param log * @param channel */ virtual void write(const CLog & log, const CChannelPtr & channel); }; } #endif /* CLOGGER_CWRITERS_CFILEWRITER_H_ */ <file_sep>/include/CLogger/CChannel.h /** * @brief * * @file CChannel.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CCHANNEL_H_ #define CLOGGER_CCHANNEL_H_ #include <CLogger/CLog.h> #include <thread> namespace CLogger { class CChannel { private: std::string channel_name_; CLogLevel channel_level_; public: /** * @brief Construct a new CChannel object * * @param channel_name * @param channel_level */ CChannel(const std::string &channel_name, const CLogLevel &channel_level); /** * @brief Destroy the CChannel object * */ virtual ~CChannel(); /** * @brief * Getter For this channel log level * Depending on the Logger log level this channel will be outputted or not * * @return CLogLevel */ CLogLevel get_log_level() const; /** * @brief * Setter For this channel log level * Depending on the Logger log level this channel will be outputted or not * * @param channel_level */ void set_log_level(const CLogLevel &channel_level); /** * @brief * Getter for the channel name * Will be represented on the log * * @return std::string */ std::string get_channel_name() const; friend class CManager; }; typedef std::shared_ptr<CChannel> CChannelPtr; } #endif /* CLOGGER_CCHANNEL_H_ */ <file_sep>/include/CLogger/CLogger.h /** * @brief * * @file CLogger.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CLOGGER_H_ #define CLOGGER_CLOGGER_H_ #include <CLogger/CChannel.h> #include <mutex> #include <stdexcept> namespace CLogger { class CLogger { private: CChannelPtr logger_channel_; private: /** * @brief * Writes the log to the needed channel through the logger manager * * @param log */ void write_log(const CLog &log) const; public: /** * @brief Construct a new CLogger object * * @param channel */ CLogger(const std::string &channel); /** * @brief Destroy the CLogger object * */ virtual ~CLogger(); /** * @brief * Getter for this loggers channel * * @return const PSChannelPtr& */ const CChannelPtr &get_logger_channel() const; /** * @brief * Getter for the debug logger * Will write the contents of this log when it dies * * @return CLog */ CLog debug(); /** * @brief * Getter for the info logger * Will write the contents of this log when it dies * * @return CLog */ CLog info(); /** * @brief * Getter for the notice logger * Will write the contents of this log when it dies * * @return CLog */ CLog notice(); /** * @brief * Getter for the warning logger * Will write the contents of this log when it dies * * @return CLog */ CLog warning(); /** * @brief * Getter for the error logger * Will write the contents of this log when it dies * * @return CLog */ CLog error(); friend class CLog; }; } #endif /* CLOGGER_CLOGGER_H_ */ <file_sep>/tests/src/test.cpp /** * @brief * * @file test.cpp * @author <NAME> * @date 2018-07-11 */ #include <CLogger/CManager.h> #include <CLogger/CLogger.h> #include <CLogger/CConfig.h> #include <unistd.h> int main(int argc, char **argv) { CLogger::CLogger logger("Test"); std::shared_ptr<CLogger::CConfig> config(new CLogger::CConfig()); CLogger::CWriterConfig file_writer_config("File", CLogger::CWriterType::LW_FILE_WRITER); CLogger::CWriterConfig console_writer_config("Console", CLogger::CWriterType::LW_CONSOLE_WRITER); CLogger::CWriterConfig syslog_writer_config("Syslog", CLogger::CWriterType::LW_SYSLOG_WRITER); file_writer_config.set_option(CLogger::CWriterOption::WO_FILE_LOG_FILES_PATH, "/tmp/test"); config->add_writer(file_writer_config); config->add_writer(console_writer_config); config->add_writer(syslog_writer_config); CLogger::CManager::get_instance().configure(config); logger.debug() << "Debug"; logger.info() << "Info"; logger.notice() << "Notice"; logger.warning() << "Warning"; logger.error() << "Error"; // Stream Test for(size_t i=0;i<100000;i++) { logger.debug() << "Message = " << i; } } <file_sep>/src/CManager.cpp /** * @brief * * @file CManager.cpp * @author <NAME> * @date 2018-07-11 */ #include <CLogger/CManager.h> namespace CLogger { CManager::CManager() : config_(new CConfig()), default_log_level_(CLogLevel::LL_DEBUG) { } CManager &CManager::get_instance() { static CManager manager; return manager; } CManager::~CManager() { clear_writers(); clear_channels(); } CChannelPtr CManager::get_channel(const std::string &name) { if (channels_.find(name) == channels_.end()) { channels_[name] = CChannelPtr(new CChannel(name, default_log_level_)); } return channels_[name]; } void CManager::configure(const CConfigPtr &config) { clear_writers(); config_ = config; // Change the default level if requested by config if (config_->has_option(CLoggerOption::LG_DEFAULT_CHANNEL_LEVEL)) { int default_level; if (config_->get_option(CLoggerOption::LG_DEFAULT_CHANNEL_LEVEL, default_level)) { default_log_level_ = static_cast<CLogLevel>(default_level); } } // Create all the writers for (auto &&writer_config : config_->get_writers()) { CWriterPtr writer = CWriterFactory::get_instance().create_writer(writer_config); if (writer) { writers_.push_back(writer); } } } void CManager::write(const CLog &log, const CChannelPtr &channel) { std::lock_guard<std::mutex> lock(writers_mutex_); for (auto &&writer : writers_) { writer->write(log, channel); } } void CManager::clear_writers() { writers_.clear(); } void CManager::clear_channels() { channels_.clear(); } } <file_sep>/include/CLogger/CConfig.h /** * @brief * * @file CConfig.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CCONFIG_H_ #define CLOGGER_CCONFIG_H_ #include <string> #include <vector> #include <map> #include <thread> #include <sstream> namespace CLogger { /** * @brief * Defines the Options available to configure the Logger */ enum class CLoggerOption : uint8_t { LG_DEFAULT_CHANNEL_LEVEL }; /** * @brief * Defines the options for specific writers */ enum class CWriterOption : uint8_t { WO_CONSOLE_DISABLE_COLOR, WO_FILE_LOG_FILES_PATH, WO_FILE_SIZE_PER_LOG_FILE, WO_FILE_MAX_LOG_FILES, WO_FILE_LOG_FOLDER_PREFIX, WO_FILE_SEPERATE_CHANNEL_FILES, WO_SYSLOG_NAME }; /** * @brief * Defines the available writes for the logger */ enum class CWriterType : uint8_t { LW_FILE_WRITER, LW_CONSOLE_WRITER, LW_SYSLOG_WRITER }; class CWriterConfig { private: std::map<CWriterOption, std::string> options_; CWriterType writer_type_; std::string writer_name_; public: /** * @brief Construct a new CWriterConfig object * * @param writer_name * @param writer_type */ CWriterConfig(const std::string &writer_name, const CWriterType &writer_type); /** * @brief Destroy the CWriterConfig object * */ virtual ~CWriterConfig(); /** * @brief * Setter for an option with a given value, will override old option * * @param option * @param value */ void set_option(const CWriterOption &option, const std::string &value); /** * @brief * Setter for an option with a given value, if this option is applicable for int * Will override old option * * @param option * @param value */ void set_option(const CWriterOption &option, int value); /** * @brief * Setter for an option with a given value, if this option is applicable for double * Will override old option * * @param option * @param value */ void set_option(const CWriterOption &option, double value); /** * @brief * Removes an option if exists * * @param option */ bool remove_option(const CWriterOption &option); /** * @brief * Checks if an option exists * * @param option * @return */ bool has_option(const CWriterOption &option) const; /** * @brief * Getter for an option, puts it in the value and returns true if exists * * @param option * @param value * @return true * @return false */ bool get_option(const CWriterOption &option, std::string &value) const; /** * @brief Get the Option object * Getter for an option, puts it in the value and returns true if exists * * @param option * @param value * @return true * @return false */ bool get_option(const CWriterOption &option, int &value) const; /** * Getter for an option, puts it in the value and returns true if exists * * @param option * @param value * @return */ bool get_option(const CWriterOption &option, double &value) const; /** * @brief * Getter for an option with default value * * @param option * @param default_value * @return std::string */ std::string get_option_default(const CWriterOption &option, const std::string &default_value) const; /** * @brief * Getter for an option with default value * * @param option * @param default_value * @return int */ int get_option_default(const CWriterOption &option, int default_value) const; /** * @brief * Getter for an option with default value * * @param option * @param default_value * @return double */ double get_option_default(const CWriterOption &option, double default_value) const; /** * @brief * Getter for the writer name * * @return std::string */ std::string get_writer_name() const; /** * @brief * Getter for the writer type * * @return PSWriterType */ CWriterType get_writer_type() const; }; class CConfig { private: std::vector<CWriterConfig> writer_configs_; std::map<CLoggerOption, std::string> logger_options_; private: /** * @brief * Converts a given input to template T * * @tparam T * @param input * @return */ template <class T> static T convert_to(const std::string &input) { std::stringstream convertor; convertor << input; T out; convertor >> out; return out; } /** * @brief * Converts a given T to string * T must implement << operator * * @tparam T * @param input * @return */ template <class T> static std::string convert_from(const T &input) { std::stringstream convertor; convertor << input; return convertor.str(); } public: /** * @brief Construct a new CConfig object * */ CConfig(); /** * @brief Destroy the CConfig object * */ virtual ~CConfig(); /** * @brief * Setter for a given logger option * * @param option * @param value */ void set_option(const CLoggerOption &option, const std::string &value); /** * @brief * Setter for a given logger option for int (only some options will be permitted) * * @param option * @param value */ void set_option(const CLoggerOption &option, int value); /** * @brief * Setter for a given logger option for double (only some options will be permitted) * * @param option * @param value */ void set_option(const CLoggerOption &option, double value); /** * @brief * Checks if a given writer exists * * @param writer_name * @return true * @return false */ bool has_writer(const std::string &writer_name) const; /** * @brief * Getter for the list of writers * * @return const std::vector<CWriterConfig>& */ const std::vector<CWriterConfig> &get_writers() const; /** * @brief * Adds a writer to the writer list * * @param config */ void add_writer(const CWriterConfig &config); /** * @brief * Removes a writer by name * * @param writer_name */ void remove_writer(const std::string &writer_name); /** * @brief * Removes an option from the config if exists * * @param option * @return true * @return false */ bool remove_option(const CLoggerOption &option); /** * @brief * Checks if an option exists * * @param option * @return true * @return false */ bool has_option(const CLoggerOption &option) const; /** * @brief * Getter for an option's value for a given option * * @param option * @param value * @return true * @return false */ bool get_option(const CLoggerOption &option, std::string &value) const; /** * @brief * Getter for an option's value for a given option * @param option * @param value * @return true * @return false */ bool get_option(const CLoggerOption &option, int &value) const; /** * @brief * Getter for an option's value for a given option * * @param option * @param value * @return true * @return false */ bool get_option(const CLoggerOption &option, double &value) const; friend class CWriterConfig; }; typedef std::shared_ptr<CConfig> CConfigPtr; } #endif /* CLOGGER_CCONFIG_H_ */ <file_sep>/src/CLog.cpp /** * @brief * * @file CLog.cpp * @author <NAME> * @date 2018-07-11 */ #include <CLogger/CLog.h> #include <CLogger/CLogger.h> namespace CLogger { CLog::CLog(const CLogLevel &log_level, const CLogger &logger) : stream_(nullptr), log_level_(log_level), logger_(logger) { if (log_level_ >= logger.get_logger_channel()->get_log_level()) { stream_ = new std::ostringstream(); } } CLog::~CLog() { if (stream_) { time_created_ = std::chrono::system_clock::now(); logger_.write_log(*this); delete stream_; } } std::string CLog::level_to_string(const CLogLevel &level) { switch (level) { case CLogLevel::LL_DEBUG: return "Debug"; case CLogLevel::LL_INFO: return "Info"; case CLogLevel::LL_NOTICE: return "Notice"; case CLogLevel::LL_WARNING: return "Warning"; default: return "Error"; } } CLogLevel CLog::string_to_level(const std::string &level_str) { if (level_str == "Info") { return CLogLevel::LL_INFO; } if (level_str == "Debug") { return CLogLevel::LL_DEBUG; } if (level_str == "Notice") { return CLogLevel::LL_NOTICE; } if (level_str == "Warning") { return CLogLevel::LL_WARNING; } else if (level_str == "Error") { return CLogLevel::LL_ERROR; } throw std::runtime_error("Invalid Log Level String"); } const std::chrono::time_point<std::chrono::system_clock> &CLog::get_time_created() const { return time_created_; } const std::ostringstream *CLog::get_stream() const { return stream_; } const CLogLevel &CLog::get_log_level() const { return log_level_; } } <file_sep>/include/CLogger/CManager.h /** * @brief * * @file CManager.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CMANAGER_H_ #define CLOGGER_CMANAGER_H_ #include <CLogger/CLog.h> #include <CLogger/CChannel.h> #include <CLogger/CConfig.h> #include <CLogger/CWriters/CWriterFactory.h> #include <mutex> namespace CLogger { class CManager { private: std::map<std::string, CChannelPtr> channels_; std::vector<CWriterPtr> writers_; std::mutex writers_mutex_; CConfigPtr config_; CLogLevel default_log_level_; private: /** * @brief * Deleted Copy Constructor, Singleton Manager * * @param other */ CManager(const CManager &other) = delete; /** * @brief * Delete Equals Operator, Singleton Manager * * @param other * @return CManager */ CManager &operator=(const CManager &other) = delete; /** * @brief Construct a new CManager object * */ CManager(); public: /** * @brief * Getter for the singleton instance of the manager * * @return CManager */ static CManager &get_instance(); /** * @brief Destroy the CManager object * */ virtual ~CManager(); /** * @brief * Getter for a channel for a given name if exists * * @param name * @return CChannelPtr */ CChannelPtr get_channel(const std::string &name); /** * @brief * Configures the manager for the given configuration * * @param config */ void configure(const CConfigPtr &config); /** * @brief * Writes a given log and channel to all the writers who can accept the level * * @param log * @param channel */ void write(const CLog &log, const CChannelPtr &channel); /** * @brief * Clears all the writers */ void clear_writers(); /** * @brief * Clears all the channels */ void clear_channels(); }; } #endif /* CLOGGER_CMANAGER_H_ */ <file_sep>/tests/CMakeLists.txt ADD_EXECUTABLE(clogger_test src/test.cpp) TARGET_COMPILE_FEATURES(clogger_test PRIVATE cxx_auto_type) TARGET_LINK_LIBRARIES(clogger_test CLogger::clogger)<file_sep>/include/CLogger/CWriters/CSysLogWriter.h /** * @brief * * @file CSysLogWriter.h * @author <NAME> * @date 2018-07-10 */ #ifndef CLOGGER_CWRITERS_CSYSLOGWRITER_H_ #define CLOGGER_CWRITERS_CSYSLOGWRITER_H_ #include <CLogger/CWriters/CWriter.h> #include <iostream> #include <syslog.h> namespace CLogger { class CSysLogWriter : public CWriter { private: std::string syslog_name_; public: /** * Constructor * @param config */ CSysLogWriter(const CWriterConfig &config); /** * Destructor */ virtual ~CSysLogWriter(); /** * Writes the contents of the log to the console * @see CWriter::write * @param log * @param channel */ virtual void write(const CLog &log, const CChannelPtr &channel); }; } #endif /* CLOGGER_CWRITERS_CCONSOLEWRITER_H_ */ <file_sep>/include/CLogger/CWriters/CWriterFactory.h /* * PSWriterFactory.h * * Created on: Mar 14, 2018 * Author: root */ #include <string> #include <thread> #include <CLogger/CWriters/CFileWriter.h> #include <CLogger/CWriters/CConsoleWriter.h> #include <CLogger/CWriters/CSysLogWriter.h> namespace CLogger { class CWriterFactory { private: /** * @brief * Singleton factory, Copy constructor deleted * @param other */ CWriterFactory(const CWriterFactory &other) = delete; /** * @brief * Singleton Factory, Deleted copy operator * * @param other * @return CWriterFactory */ CWriterFactory operator=(const CWriterFactory &other) = delete; /** * @brief * Private Constructor, Singleton Factory */ CWriterFactory(); public: /** * @brief * Singleton Getter * * @return CWriterFactory */ static CWriterFactory &get_instance(); /** * @brief Destroy the CWriterFactory object * */ virtual ~CWriterFactory(); /** * @brief * Creates a writer for a given config * * @param writer_config * @return CWriterPtr */ CWriterPtr create_writer(const CWriterConfig &writer_config); }; }
fc451cffd3198b5397f9bfabfc7448834613ee3c
[ "CMake", "C++" ]
23
C++
ofiriluz/clogger
160b69995cebc361d1eb63b84ce3162af438111d
78a048c03e6f32c9a97546f83e4076653ecdabdb
refs/heads/master
<repo_name>ciborg003/BloggerApp<file_sep>/src/main/resources/application.properties #spring.datasource.url = jdbc:mysql://localhost:3306/bloger? #spring.datasource.username=root #spring.datasource.password=<PASSWORD> #spring.jpa.show-sql=true #spring.jpa.hibernate.ddl-auto=update <file_sep>/src/main/kotlin/com/baeldung/kotlin/web/WebConfig.kt package com.baeldung.kotlin.web import com.baeldung.kotlin.mvc.ApplicationWebConfig import org.springframework.context.MessageSource import org.springframework.context.annotation.Bean import org.springframework.context.support.ReloadableResourceBundleMessageSource import org.springframework.web.servlet.config.annotation.EnableWebMvc import org.springframework.web.servlet.config.annotation.WebMvcConfigurer import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer import java.util.* /** *Created by <NAME> on 12/23/2017 8:20 PM */ @EnableWebMvc open class WebConfig: AbstractAnnotationConfigDispatcherServletInitializer { constructor() : super() // @Bean // fun messageSource(): MessageSource { // val msgSource = ReloadableResourceBundleMessageSource() // msgSource.setBasename("classpath:validation") // msgSource.setDefaultEncoding("UTF-8") // // return msgSource // } override fun getServletMappings(): Array<String> { return Array<String>(1) {"/"} } override fun getServletConfigClasses(): Array<Class<*>> { return Array<Class<*>>(1) {ApplicationWebConfig::class.java} } override fun getRootConfigClasses(): Array<Class<*>>? { return null; } }<file_sep>/src/main/kotlin/com/baeldung/kotlin/BlogApplication.kt package com.baeldung.kotlin //import com.baeldung.kotlin.dao.UserRepository import com.baeldung.kotlin.model.User import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication /** *Created by <NAME> on 12/22/2017 10:08 PM */ @SpringBootApplication open class BlogApplication{ } fun main(args: Array<String>) { SpringApplication.run(BlogApplication::class.java, *args) }<file_sep>/src/main/kotlin/com/baeldung/kotlin/dao/UserDAO.kt package com.baeldung.kotlin.dao import com.baeldung.kotlin.model.User //import org.springframework.data.repository.CrudRepository import org.springframework.stereotype.Repository //@Repository //interface UserRepository: CrudRepository<User, Long> { //}<file_sep>/src/main/kotlin/com/baeldung/kotlin/mvc/ApplicationWebConfig.kt package com.baeldung.kotlin.mvc import org.springframework.context.ApplicationContext import org.springframework.context.ApplicationContextAware import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.servlet.config.annotation.ViewControllerRegistry import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter import org.thymeleaf.spring4.SpringTemplateEngine import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver import org.thymeleaf.spring4.view.ThymeleafViewResolver import org.thymeleaf.templatemode.TemplateMode import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver @Configuration class ApplicationWebConfig : WebMvcConfigurerAdapter(), ApplicationContextAware { private var applicationContext: ApplicationContext? = null override fun setApplicationContext(applicationContext: ApplicationContext?) { this.applicationContext = applicationContext } @Bean fun templateResolver(): ClassLoaderTemplateResolver { val resolver = ClassLoaderTemplateResolver() .apply { prefix = "templates/" } .apply { suffix = ".html" } .apply { isCacheable = false } .apply { templateMode = TemplateMode.HTML } .apply { characterEncoding = "UTF-8" } return resolver; } @Bean fun templateEngine(): SpringTemplateEngine { return SpringTemplateEngine() .apply { setTemplateResolver(templateResolver()) } } @Bean fun viewResolver(): ThymeleafViewResolver{ return ThymeleafViewResolver() .apply { templateEngine = templateEngine() } .apply { characterEncoding = "UTF-8" }; } override fun addViewControllers(registry: ViewControllerRegistry?) { if (registry != null) { registry.addViewController("/").setViewName("index") }; } }<file_sep>/src/main/kotlin/com/baeldung/kotlin/validation/UserValidator.kt //package com.baeldung.kotlin.validation // ////import com.baeldung.kotlin.dao.UserRepository //import com.baeldung.kotlin.model.User //import org.apache.commons.validator.EmailValidator //import org.springframework.beans.factory.annotation.Autowired //import org.springframework.stereotype.Component //import org.springframework.validation.Errors //import org.springframework.validation.ValidationUtils //import org.springframework.validation.Validator // //@Component //class UserValidator: Validator { // //// @Autowired //// lateinit var userRepository: UserRepository // // val emailValidator: EmailValidator = EmailValidator.getInstance() // // override fun validate(p0: Any?, p1: Errors?) { // val user = p0 as User // // ValidationUtils.rejectIfEmptyOrWhitespace(p1, "login", "NotEmpty.user.userName") // ValidationUtils.rejectIfEmptyOrWhitespace(p1, "password", "<PASSWORD>") // ValidationUtils.rejectIfEmptyOrWhitespace(p1, "firstName", "NotEmpty.user.firstName") // ValidationUtils.rejectIfEmptyOrWhitespace(p1, "lastName", "NotEmpty.user.lastName") // // if (this.emailValidator.isValid(user.email)){ // if (p1 != null) { // p1.rejectValue("email", "Pattern.user.email") // } // } else if (user.id == -1L) { //// val dbUser = userRepository.findOne(user.id) // if (user != null){ // if (p1 != null) { // p1.rejectValue("email", "Duplicate.user.email") // } // } // } // // if (p1 != null) { // if (!p1.hasFieldErrors("userName")) { //// val dbUser = userRepository.findOne(1L) //// if (dbUser != null) { // // Username is not available. //// p1.rejectValue("userName", "Duplicate.appUserForm.userName") //// } // } // } // } // // override fun supports(p0: Class<*>?): Boolean { // return p0 == User::class // } //}<file_sep>/src/test/kotlin/com/baeldung/kotlin/allopen/SimpleConfigurationTest.kt package com.baeldung.kotlin.allopen // //import com.sun.tools.javac.util.AbstractDiagnosticFormatter //import org.junit.Test //import org.junit.runner.RunWith //import org.springframework.test.context.ContextConfiguration //import org.springframework.test.context.junit4.SpringJUnit4ClassRunner //import org.springframework.test.context.support.AnnotationConfigContextLoader // //@RunWith(SpringJUnit4ClassRunner::class) //@ContextConfiguration( // loader = AnnotationConfigContextLoader::class, // classes = arrayOf(AbstractDiagnosticFormatter.SimpleConfiguration::class)) //class SimpleConfigurationTest { // // @Test // fun contextLoads() { // } // //}<file_sep>/src/main/kotlin/com/baeldung/kotlin/service/UserService.kt package com.baeldung.kotlin.service import com.baeldung.kotlin.model.User interface UserService{ fun signUp(user: User); }<file_sep>/src/main/kotlin/com/baeldung/kotlin/security/WebSecurityConfig.kt package com.baeldung.kotlin.security import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter import org.springframework.security.core.userdetails.UserDetailsService import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder import org.springframework.security.crypto.password.PasswordEncoder @Configuration @EnableWebSecurity class WebSecurityConfig: WebSecurityConfigurerAdapter() { @Autowired lateinit var userDetailService: UserDetailsService @Bean fun passwordEncoder(): PasswordEncoder { val encoder = BCryptPasswordEncoder() return encoder } override fun configure(http: HttpSecurity?) { // super.configure(http) if (http != null) { http.csrf().disable() http .exceptionHandling().accessDeniedPage("/access-denied") .and() .authorizeRequests() .antMatchers("","/resources/**","/login","/sign-up").permitAll() .antMatchers("/room/**").hasRole("USER") .anyRequest().authenticated() .and() .formLogin().loginPage("/login") .and() .logout() } @Autowired @Throws(Exception::class) fun configureGlobal(auth: AuthenticationManagerBuilder) { auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()) } } }<file_sep>/src/main/kotlin/com/baeldung/kotlin/model/User.kt package com.baeldung.kotlin.model import java.util.* import javax.persistence.* //@Entity //@Table data class User( //class User( // @Id // @GeneratedValue(strategy = GenerationType.AUTO) var id: Long = -1, var login: String = "", var password: String = "", var firstName: String = "", var lastName: String = "", var email: String = "", val dob: Date = Date(System.currentTimeMillis())) { }<file_sep>/src/main/kotlin/com/baeldung/kotlin/controller/SignUpController.kt package com.baeldung.kotlin.controller import com.baeldung.kotlin.model.User //import com.baeldung.kotlin.service.UserService //import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.ModelAttribute import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.RequestMapping @Controller @RequestMapping("/sign-up") class SignUpController { // @Autowired // lateinit var userService: UserService @GetMapping("") fun signUp(model: Model): String{ val user = User() model.addAttribute("user", user) return "sign-up" } @PostMapping(value = ["/register"]) fun register(@ModelAttribute user: User): String{ println("User:") println(user.login) println(user.password) println(user.lastName) println(user.firstName) return "redirect:/" } }<file_sep>/src/main/kotlin/com/baeldung/kotlin/service/impl/UserServiceImpl.kt package com.baeldung.kotlin.service.impl //import com.baeldung.kotlin.dao.UserRepository import com.baeldung.kotlin.model.User import com.baeldung.kotlin.service.UserService import org.springframework.beans.factory.annotation.Autowired import org.springframework.stereotype.Service @Service class UserServiceImpl: UserService { // @Autowired // lateinit var userRepository: UserRepository // override fun signUp(user: User) { // userRepository.save(user) } }<file_sep>/src/main/kotlin/com/baeldung/kotlin/controller/BlogController.kt package com.baeldung.kotlin.controller import com.baeldung.kotlin.model.User import org.springframework.stereotype.Controller import org.springframework.ui.Model import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse /** *Created by <NAME> on 12/22/2017 10:27 PM */ @Controller @RequestMapping("/") class BlogController{ @RequestMapping(method = arrayOf(RequestMethod.GET)) fun doIndexGet(model: Model): String { model.addAttribute("user", "Some User Name") return "welcome"; } @GetMapping(value = "/profile") fun getProfile(model: Model): String{ return "profile" } }<file_sep>/src/main/resources/validation.properties NotEmpty.user.userName=User name is required NotEmpty.user.firstName=First Name is required NotEmpty.user.lastName=Last name is required NotEmpty.user.email=Email is required NotEmpty.user.password=<PASSWORD> NotEmpty.user.confirmPassword=Confirm Password is required Pattern.user.email=Invalid email Duplicate.user.email=Email has been used by another account Duplicate.user.userName=Username is not available
6776d57a2dbccf842e2e50bb270dd99606301b3f
[ "Kotlin", "INI" ]
14
INI
ciborg003/BloggerApp
b64a2c15c18ff0e58265edf49c88932badb8ec8e
1cadaf7c0ba70341a671d1c86bf0c281f9762995
refs/heads/master
<file_sep>#pragma once #include "rasterization.h" #define MAX(a, b) a > b ? a : b class RendererController { public: RendererController(int width, int height, std::string path, TGAImage& _outFrame); ~RendererController(); void run(); private: Model *_model = NULL; Rasterization *_rasterize; IShader * _modelShader = NULL; IShader *_depthShader = NULL; TGAImage& _outFrame; const int _width; const int _height; const int _depth; vec3 _direction_light; vec3 _camera; vec3 _center; float * _zbuffer = NULL; float * _shadowBuffer = NULL; };<file_sep>#include "model.h" #include <iostream> #include <fstream> #include <sstream> Model::Model(std::string filename) : verts(), vertFaces() { std::string objName = filename + ".obj"; std::ifstream in; in.open(objName, std::ifstream::in); if (in.fail()) return; std::string line; while (!in.eof()) { std::getline(in, line); std::istringstream iss(line.c_str()); char trash; if (!line.compare(0, 2, "v ")) { iss >> trash; vec3 v; for (int i = 0; i < 3; i++) iss >> v[i]; verts.push_back(v); } else if (!line.compare(0, 3, "vt ")) { iss >> trash >> trash; vec2 vt; for (int i = 0; i < 2; i++) iss >> vt[i]; uverts.push_back(vt); } else if (!line.compare(0, 3, "vn ")) { iss >> trash >> trash; vec3 n; for (int i = 0; i < 3; i++) iss >> n[i]; normalverts.push_back(n); } else if (!line.compare(0, 2, "f ")) { std::vector<int> f; std::vector<int> uvFace; std::vector<int> normalFace; int itrash, idx, texIdx, normalIdx; iss >> trash; while (iss >> idx >> trash >> texIdx >> trash >> normalIdx) { idx--; // in wavefront obj all indices start at 1, not zero texIdx--; normalIdx--; f.push_back(idx); uvFace.push_back(texIdx); normalFace.push_back(normalIdx); } vertFaces.push_back(f); uvFaces.push_back(uvFace); normalFaces.push_back(normalFace); } } std::string diffuseName = filename + "_diffuse.tga"; diffuseTexture.read_tga_file(diffuseName.c_str()); diffuseTexture.flip_vertically(); std::string normalMapName = filename + "_nm.tga"; normalTexture.read_tga_file(normalMapName.c_str()); normalTexture.flip_vertically(); std::string tNormalMapName = filename + "_nm_tangent.tga"; if(!tNormalTexture.read_tga_file(tNormalMapName.c_str())) assert(0); tNormalTexture.flip_vertically(); std::string specMapName = filename + "_spec.tga"; if (!specTexture.read_tga_file(specMapName.c_str())) assert(0); specTexture.flip_vertically(); std::string glowMapName = filename + "_glow.tga"; glowTexture.read_tga_file(glowMapName.c_str()); glowTexture.flip_vertically(); std::cerr << "# v# " << verts.size() << " f# " << vertFaces.size() << std::endl; } Model::~Model() { } int Model::nverts() { return (int)verts.size(); } int Model::nfaces() { return (int)vertFaces.size(); } std::vector<int> Model::vertFace(int idx) { return vertFaces[idx]; } std::vector<int> Model::uvFace(int idx) { return uvFaces[idx]; } std::vector<int> Model::normalFace(int idx) { return normalFaces[idx]; } vec3 Model::vert(int i) { return verts[i]; } vec2 Model::uvert(int i) { return uverts[i]; } vec3 Model::normalvert(int i) { return normalverts[i]; } TGAColor Model::diffuse(vec2 uv) { return diffuseTexture.get( diffuseTexture.get_width() * uv.u, diffuseTexture.get_height() * uv.v); } TGAImage* Model::getDiffuseTexture() { return &diffuseTexture; } TGAImage* Model::getNormalTexture() { return &normalTexture; } TGAImage* Model::getTangentNormalTexture() { return &tNormalTexture; } TGAImage* Model::getSpecularTexture() { return &specTexture; } TGAImage* Model::getGlowTexture() { return &glowTexture; } <file_sep>#include "shader.h" #include <cstdlib> IShader::~IShader() { } ModelShader::~ModelShader() { } void ModelShader::setUniform(UniformBlock& block) { model = block.model; view = block.view; projection = block.projection; lightDir = block.lightDir; viewPos = block.viewPos; diffuseTexture = block.diffuseTexture; normalTexture = block.normalTexture; specTexture = block.specTexture; glowTexture = block.glowTexture; lightSpace = block.lightSpace; shadowBuffer = block.shadowBuffer; shadowW = block.shadowW; shadowH = block.shadowH; lightDir = (lightDir * (-1.0f)).normalize(); } vec4 ModelShader::vertex(vec3 position) { vec4 gl_Position = projection * view * model * vec4(position); return gl_Position; // transform it to screen coordinates } bool ModelShader::fragment(vec2 uvCoord, vec3 normal, TGAColor& fragColor) { float intensity = std::max((double)0.0f, normal.normalize() * (lightDir * (-1.0f)).normalize()); fragColor = diffuseTexture->get(diffuseTexture->get_width() * uvCoord.u, diffuseTexture->get_height() * uvCoord.v) * intensity; for (int i = 0; i < 3; i++) { fragColor.raw[i] = std::min(fragColor.raw[i], (unsigned char)255); } return false; } bool ModelShader::fragment(vec3 worldCoord, vec2 uvCoord, mat<3, 3> TBN, TGAColor& fragColor) { vec3 nColor = normalTexture->texture(uvCoord.u, uvCoord.v); vec3 diffColor = diffuseTexture->texture(uvCoord.u, uvCoord.v); vec3 specColor = specTexture->texture(uvCoord.u, uvCoord.v); vec3 glowColor = glowTexture->texture(uvCoord.u, uvCoord.v); vec3 tangentNormal( nColor.r * 2 - 1, nColor.g * 2 - 1, nColor.b * 2 - 1 ); tangentNormal = (TBN * tangentNormal.normalize()).normalize(); //float shadowFactor = 1.0f; float shadowFactor = (1.0 -calculateShadow(lightSpace * embed<4>(worldCoord, 1.0f))); float ambient = 1 / 255.0; double diff = std::max(0.0, tangentNormal * lightDir); vec3 reflectDir = (tangentNormal * (tangentNormal * lightDir) * 2 - lightDir).normalize(); vec3 viewDir = (viewPos - worldCoord).normalize(); vec3 halfway = (viewDir + lightDir).normalize(); //double spec = pow(std::max(viewDir*reflectDir, 0.0), 5 + specColor[0] * 255); double spec = pow(std::max(halfway * tangentNormal, 0.0), 5 + specColor.r * 255); vec3 vfragColor = diffColor * (ambient + shadowFactor * (2 * diff + 2 * spec)) + glowColor * 20; vec3 result = vec3(1.0, 1.0, 1.0) - vec3(std::exp(-vfragColor.x * 1.0), std::exp(-vfragColor.y * 1.0), std::exp(-vfragColor.z * 1.0)); fragColor = TGAColor::transform(result); return false; } float ModelShader::calculateShadow(vec4 fragPos) { vec3 projCoords = proj<3>(fragPos / fragPos.w); // transform to [0,1] range projCoords.x = std::max(0.0, std::min(1.0 * shadowW, projCoords.x)); projCoords.y = std::max(0.0, std::min(1.0 * shadowH, projCoords.y)); // get closest depth value from light's perspective (using [0,1] range fragPosLight as coords) float closestDepth = shadowBuffer[int(projCoords.x + shadowW * projCoords.y)]; // get depth of current fragment from light's perspective float currentDepth = projCoords.z; // calculate bias (based on depth map resolution and slope) //vec3 normal = normalize(fs_in.Normal); //vec3 lightDir = normalize(lightPos - fs_in.FragPos); //float bias = max(0.05 * (1.0 - dot(normal, lightDir)), 0.005); if (currentDepth > 1.0f) return 0.0; if (closestDepth > 10.0) { return 1.0; } return currentDepth > 0.05 + closestDepth; } DepthShader::~DepthShader() { } void DepthShader::setUniform(UniformBlock& block) { model = block.model; view = block.view; projection = block.projection; } vec4 DepthShader::vertex(vec3 position) { vec4 gl_Position = projection * view * model * vec4(position); return gl_Position; // transform it to screen coordinates }<file_sep>#include "rasterization.h" #include "shader.h" Rasterization::Rasterization(IShader* modelShader, IShader* depthShader) { this->modelShader = modelShader; this->depthShader = depthShader; } Rasterization::~Rasterization() { } void Rasterization::viewPort(int x, int y, int w, int h) { viewport = mat<4, 4>::identity(); viewport[0][3] = x + w / 2.f; viewport[1][3] = y + h / 2.f; viewport[0][0] = w / 2.f; viewport[1][1] = h / 2.f; this->x = x; this->y = y; this->width = w; this->height = h; //std::cerr << viewport << "\n"; } void Rasterization::line(int x0, int y0, int x1, int y1, TGAImage& image, TGAColor color) { bool steep = false; if (std::abs(x0 - x1) < std::abs(y0 - y1)) { std::swap(x0, y0); std::swap(x1, y1); steep = true; } if (x0 > x1) { std::swap(x0, x1); std::swap(y0, y1); } int dx = x1 - x0; int dy = y1 - y0; int derror2 = std::abs(dy) * 2; int error2 = 0; int y = y0; for (int x = x0; x <= x1; x++) { if (steep) { image.set(y, x, color); } else { image.set(x, y, color); } error2 += derror2; if (error2 > dx) { y += (y1 > y0 ? 1 : -1); error2 -= dx * 2; } } } vec3 Rasterization::baryCentric(vec3* clipPts, vec3 P) { vec3 u = vec3::cross(vec3(clipPts[2][0] - clipPts[0][0], clipPts[1][0] - clipPts[0][0], clipPts[0][0] - P[0]), vec3(clipPts[2][1] - clipPts[0][1], clipPts[1][1] - clipPts[0][1], clipPts[0][1] - P[1])); /* `clipPts` and `P` has integer value as coordinates so `abs(u[2])` < 1 means `u[2]` is 0, that means triangle is degenerate, in this case return something with negative coordinates */ if (std::abs(u[2]) < 1e-5) return vec3(-1, 1, 1); return vec3(1.f - (u.x + u.y) / u.z, u.y / u.z, u.x / u.z); } void Rasterization::triangle(vec2 t0, vec2 t1, vec2 t2, TGAImage& image, TGAColor color) { if (t1.y > t2.y) { std::swap(t1, t2); } if (t0.y > t2.y) { std::swap(t0, t2); } if (t0.y > t1.y) { std::swap(t0, t1); } float totalHeight = t2.y - t0.y + 1; float segmentHeight1 = t1.y - t0.y; float segmentHeight2 = t2.y - t1.y; float alpha; vec2 A; for (int i = t0.y; i < t2.y; i++) { if (i < t1.y) { alpha = (i - t0.y) / segmentHeight1; A = t0 + (t1 - t0) * alpha; } else { alpha = (i - t1.y) / segmentHeight2; A = t1 + (t2 - t1) * alpha; } float beta = (i - t0.y) / totalHeight; vec2 B = t0 + (t2 - t0) * beta; if (A.x > B.x) std::swap(A, B); for (int x = A.x; x < B.x; x++) { image.set(x, i, color); } } } void Rasterization::triangle(vec3* clipPts, float* zbuffer, TGAImage& image, TGAColor color) { if (clipPts[0].y == clipPts[1].y && clipPts[0].y == clipPts[2].y) return; vec2 bboxmin(width - 1, height - 1); vec2 bboxmax(0, 0); for (int i = 0; i < 3; i++) { bboxmin.x = std::max(x, std::min(bboxmin.x, clipPts[i][0])); bboxmin.y = std::max(y, std::min(bboxmin.y, clipPts[i][1])); bboxmax.x = std::min(width-1, std::max(bboxmax.x, clipPts[i][0])); bboxmax.y = std::min(height-1, std::max(bboxmax.y, clipPts[i][1])); } vec3 P; for (P.x = bboxmin.x; P.x <= bboxmax.x; P.x++) { for (P.y = bboxmin.y; P.y <= bboxmax.y; P.y++) { vec3 bc_screen = baryCentric(clipPts, P); if (bc_screen.x < 0 || bc_screen.y < 0 || bc_screen.z < 0) continue; P.z = 0; for (int i = 0; i < 3; i++) P.z += clipPts[i][2] * bc_screen[i]; if (zbuffer[int(P.x + P.y * width)] < P.z) { zbuffer[int(P.x + P.y * width)] = P.z; image.set(P.x, P.y, color); } } } } void Rasterization::triangle(Model* model, vec3* clipPts, vec2* uvPts, float* zbuffer, TGAImage& image, float intensity) { if (clipPts[0].y == clipPts[1].y && clipPts[0].y == clipPts[2].y) return; vec2 bboxmin(width - 1, height - 1); vec2 bboxmax(0, 0); for (int i = 0; i < 3; i++) { bboxmin.x = std::max(x, std::min(bboxmin.x, clipPts[i][0])); bboxmin.y = std::max(y, std::min(bboxmin.y, clipPts[i][1])); bboxmax.x = std::min(width, std::max(bboxmax.x, clipPts[i][0])); bboxmax.y = std::min(height, std::max(bboxmax.y, clipPts[i][1])); } vec3 P; for (P.x = bboxmin.x; P.x <= bboxmax.x; P.x++) { for (P.y = bboxmin.y; P.y <= bboxmax.y; P.y++) { vec3 bc_screen = baryCentric(clipPts, P); if (bc_screen.x < 0 || bc_screen.y < 0 || bc_screen.z < 0) continue; P.z = 0; for (int i = 0; i < 3; i++) P.z += clipPts[i][2] * bc_screen[i]; vec2 sample(0, 0); for (int i = 0; i < 3; i++) { sample.x += (uvPts[i] * bc_screen[i]).x; sample.y += (uvPts[i] * bc_screen[i]).y; } if (zbuffer[int(P.x + P.y * width)] < P.z) { zbuffer[int(P.x + P.y * width)] = P.z; image.set(P.x, P.y, model->diffuse(sample) * intensity); } } } } void Rasterization::triangle(vec3* worldPts, vec4* clipPts, vec2* uvPts, vec3* normalPts, float *zbuffer, TGAImage& image) { if (clipPts[0].y == clipPts[1].y && clipPts[0].y == clipPts[2].y) return; vec3 clipCoord[3]; for (int i = 0; i < 3; i++) { clipCoord[i] = proj<3>(viewport * (clipPts[i] / clipPts[i][3])); } vec3 P; TGAColor fragColor; mat<1, 3> zMat; mat<3, 3> worldMat; mat<2, 3> uvMat; mat<3, 3> normalMat; vec3 worldCoord; vec2 uvCoord; vec3 bnCoord; for (int i = 0; i < 3; i++) { zMat[0][i] = clipCoord[i][2]; worldMat.set_col(i, worldPts[i]); uvMat.set_col(i, uvPts[i]); normalMat.set_col(i, normalPts[i]); } mat<2, 2> deltaUV = mat<2, 2>{ uvPts[1] - uvPts[0], uvPts[2] - uvPts[0] }.invert(); mat<2, 3> deltaPos = mat<2, 3>{ worldPts[1] - worldPts[0], worldPts[2] - worldPts[0] }; mat<2, 3> TB = deltaUV * deltaPos; TB[0].normalize(); TB[1].normalize(); vec2 bboxmin(width - 1, height - 1); vec2 bboxmax(0, 0); for (int i = 0; i < 3; i++) { bboxmin.x = std::max(x, std::min(bboxmin.x, clipCoord[i][0])); bboxmin.y = std::max(y, std::min(bboxmin.y, clipCoord[i][1])); bboxmax.x = std::min(width, std::max(bboxmax.x, clipCoord[i][0])); bboxmax.y = std::min(height, std::max(bboxmax.y, clipCoord[i][1])); } for (P.x = (int)bboxmin.x; P.x <= (int)bboxmax.x; P.x++) { for (P.y = (int)bboxmin.y; P.y <= (int)bboxmax.y; P.y++) { vec3 bc_screen = baryCentric(clipCoord, P); vec3 bc_clip = vec3(bc_screen.x / clipPts[0][3], bc_screen.y / clipPts[1][3], bc_screen.z / clipPts[2][3]); bc_clip = bc_clip / (bc_clip.x + bc_clip.y + bc_clip.z); P.z = (zMat * bc_clip)[0]; if (bc_screen.x < 0 || bc_screen.y < 0 || bc_screen.z < 0 || zbuffer[int(P.x + P.y * width)] < P.z) continue; worldCoord = worldMat * bc_clip; uvCoord = uvMat * bc_clip; bnCoord = normalMat * bc_clip; bnCoord.normalize(); mat<3, 3> TBN; TBN.set_col(0, (TB[0] - bnCoord * (bnCoord * TB[0])).normalize()); TBN.set_col(1, vec3::cross(bnCoord, TB[0]).normalize()); TBN.set_col(2, bnCoord); //vec3 fragCoord = vec3(P.x, P.y, P.z * clipPts[2][3]); bool discard = modelShader->fragment(worldCoord, uvCoord, TBN, fragColor); if(discard) continue; zbuffer[int(P.x + P.y * width)] = P.z; image.set(P.x, P.y, fragColor); } } } void Rasterization::triangle(vec4* clipPts, float* shadowBuffer, TGAImage& depthTga) { if (clipPts[0].y == clipPts[1].y && clipPts[0].y == clipPts[2].y) return; vec3 clipCoord[3]; for (int i = 0; i < 3; i++) { clipCoord[i] = proj<3>(viewport * (clipPts[i] / clipPts[i][3])); } vec3 P; mat<1, 3> zMat; for (int i = 0; i < 3; i++) { zMat[0][i] = clipCoord[i][2]; } vec2 bboxmin(width - 1, height - 1); vec2 bboxmax(0, 0); for (int i = 0; i < 3; i++) { bboxmin.x = std::max(x, std::min(bboxmin.x, clipCoord[i][0])); bboxmin.y = std::max(y, std::min(bboxmin.y, clipCoord[i][1])); bboxmax.x = std::min(width, std::max(bboxmax.x, clipCoord[i][0])); bboxmax.y = std::min(height, std::max(bboxmax.y, clipCoord[i][1])); } for (P.x = (int)bboxmin.x; P.x <= (int)bboxmax.x; P.x++) { for (P.y = (int)bboxmin.y; P.y <= (int)bboxmax.y; P.y++) { vec3 bc_screen = baryCentric(clipCoord, P); vec3 bc_clip = vec3(bc_screen.x / clipPts[0][3], bc_screen.y / clipPts[1][3], bc_screen.z / clipPts[2][3]); bc_clip = bc_clip / (bc_clip.x + bc_clip.y + bc_clip.z); P.z = (zMat * bc_clip)[0]; //if (P.z <= 0.0f || P.z >= 1.0f) // std::cerr << "P.z = " << P.z << "\n"; int index = int(P.x + P.y * width); if (bc_screen.x < 0 || bc_screen.y < 0 || bc_screen.z < 0 || shadowBuffer[index] < P.z) continue; bool discard = depthShader->fragment(); if (discard) continue; //std::cerr << P.x <<" "<< P.y <<" " << P.z << "\n"; shadowBuffer[int(P.x + P.y * width)] = P.z; int depth = (P.z + 1.0) * 0.5 * 255; depthTga.set(P.x, P.y, TGAColor(depth, depth, depth, depth)); } } }<file_sep>#include "renderer_controller.h" RendererController::RendererController(int width, int height, std::string path, TGAImage& outFrame) : _outFrame(outFrame), _width(width), _height(height), _depth(255), _direction_light(-1, -1, 0), _camera(1, 1, 4), _center(0, 0, 0) { _model = new Model(path); _modelShader = new ModelShader(); _depthShader = new DepthShader(); _rasterize = new Rasterization(_modelShader, _depthShader); _zbuffer = new float[width * height]; _shadowBuffer = new float[width * height]; for (int i = width * height; i--; _zbuffer[i] = std::numeric_limits<float>::max()); for (int i = width * height; i--; _shadowBuffer[i] = std::numeric_limits<float>::max()); } RendererController::~RendererController() { if (_model) { delete _model; } if (_modelShader) { delete _modelShader; } if (_depthShader) { delete _depthShader; } if (_rasterize) { delete _rasterize; } if (_zbuffer) { delete[] _zbuffer; } if (_shadowBuffer) { delete[] _shadowBuffer; } } void RendererController::run() { UniformBlock modelBlock; modelBlock.model = mat<4,4>::identity(); //modelBlock.model[0][3] = 1.5; //modelBlock.model[1][3] = 1.6; //modelBlock.model[2][3] = 1.0; modelBlock.view = RendererUtil::lookat(_camera, _center, vec3(0.0, 1.0, 0.0)); modelBlock.projection = RendererUtil::projection((_camera - _center).length());; modelBlock.diffuseTexture = _model->getDiffuseTexture(); modelBlock.normalTexture = _model->getTangentNormalTexture(); modelBlock.specTexture = _model->getSpecularTexture(); modelBlock.glowTexture = _model->getGlowTexture(); modelBlock.lightDir = _direction_light; modelBlock.viewPos = _camera; UniformBlock depthBlock; depthBlock.model = modelBlock.model; depthBlock.view = RendererUtil::lookat(_direction_light * (-1.0f), _center, vec3(0.0, 1.0, 0.0)); depthBlock.projection = RendererUtil::projection(0); mat<4, 4> viewport = mat<4, 4>::identity(); viewport[0][3] = _width / 2.f; viewport[1][3] = _height / 2.f; viewport[0][0] = _width / 2.f; viewport[1][1] = _height / 2.f; modelBlock.lightSpace = viewport * depthBlock.projection * depthBlock.view; modelBlock.shadowBuffer = _shadowBuffer; modelBlock.shadowW = _width; modelBlock.shadowH = _height; _modelShader->setUniform(modelBlock); _depthShader->setUniform(depthBlock); _rasterize->viewPort(0, 0, _width, _height); TGAImage depthTga(_width, _height, TGAImage::RGB); for (int i = 0; i < _model->nfaces(); i++) { std::vector<int> vertFace = _model->vertFace(i); vec4 light_clip_coords[3]; for (int j = 0; j < 3; j++) { light_clip_coords[j] = _depthShader->vertex(_model->vert(vertFace[j])); } _rasterize->triangle(light_clip_coords, _shadowBuffer, depthTga); } depthTga.flip_vertically(); // to place the origin in the bottom left corner of the image depthTga.write_tga_file("depth.tga"); _rasterize->viewPort(0, 0, _width, _height); for (int i = 0; i < _model->nfaces(); i++) { std::vector<int> vertFace = _model->vertFace(i); std::vector<int> uvFace = _model->uvFace(i); std::vector<int> normalFace = _model->normalFace(i); vec3 world_coords[3]; vec4 clip_coords[3]; vec2 uv_coords[3]; vec3 normal_coords[3]; for (int j = 0; j < 3; j++) { //world_coords[j] = proj<3>(block.model * embed<4>(_model->vert(vertFace[j]), 1.0)); world_coords[j] = _model->vert(vertFace[j]); clip_coords[j] = _modelShader->vertex(_model->vert(vertFace[j])); uv_coords[j] = _model->uvert(uvFace[j]); normal_coords[j] = _model->normalvert(normalFace[j]); } _rasterize->triangle(world_coords, clip_coords, uv_coords, normal_coords, _zbuffer, _outFrame); } } <file_sep>#pragma once #include "tgaimage.h" #include "geometry.h" #define uniform #define vary typedef TGAImage* sample2D; struct UniformBlock { mat<4,4> model; mat<4,4> view; mat<4, 4> projection; vec3 lightDir; vec3 viewPos; sample2D diffuseTexture; sample2D normalTexture; sample2D specTexture; sample2D glowTexture; float* shadowBuffer; mat<4, 4> lightSpace; int shadowW; int shadowH; }; class RendererUtil { public: static mat<4,4> lookat(vec3 eye, vec3 center, vec3 up) { vec3 z = (eye - center).normalize(); vec3 x = vec3::cross(up, z).normalize(); vec3 y = vec3::cross(z, x).normalize(); mat<4,4> res = mat<4,4>::identity(); for (int i = 0; i < 3; i++) { res[0][i] = x[i]; res[1][i] = y[i]; res[2][i] = z[i]; //res[i][3] = -eye[i]; res[i][3] = -center[i]; } std::cerr << res << "\n"; return res; } static mat<4,4> projection(float coeff) { mat<4,4> projection = mat<4,4>::identity(); projection[2][2] = -1.f; if(coeff > 1e-6f) projection[3][2] = -1.f / coeff; std::cerr << projection << "\n"; return projection; } }; class IShader { public: virtual ~IShader() = 0; virtual void setUniform(UniformBlock& block) = 0; virtual vec4 vertex(vec3 position) = 0; virtual bool fragment() = 0; virtual bool fragment(vec2 uvCoord, vec3 normal, TGAColor& fragColor) = 0; virtual bool fragment(vec3 worldCoord, vec2 uvCoord, mat<3, 3> TBN, TGAColor& fragColor) = 0; }; class ModelShader:public IShader { public: virtual ~ModelShader() override; virtual void setUniform(UniformBlock& block) override; virtual vec4 vertex(vec3 position) override; virtual bool fragment() override { return false; } virtual bool fragment(vec2 uvCoord, vec3 normal, TGAColor& fragColor) override; virtual bool fragment(vec3 worldCoord, vec2 uvCoord, mat<3, 3> TBN, TGAColor& fragColor) override; protected: float calculateShadow(vec4 fragPosLightSpace); private: uniform mat<4,4> model; uniform mat<4,4> view; uniform mat<4,4> projection; uniform sample2D diffuseTexture; uniform sample2D normalTexture; uniform sample2D specTexture; uniform sample2D glowTexture; uniform vec3 lightDir; uniform vec3 viewPos; uniform mat<4, 4> lightSpace; uniform float * shadowBuffer; int shadowW; int shadowH; }; class DepthShader :public IShader { public: virtual ~DepthShader() override; virtual void setUniform(UniformBlock& block) override; virtual vec4 vertex(vec3 position) override; virtual bool fragment() override { return false; } virtual bool fragment(vec2 uvCoord, vec3 normal, TGAColor& fragColor) override { return false; } virtual bool fragment(vec3 worldCoord, vec2 uvCoord, mat<3, 3> TBN, TGAColor& fragColor) override { return false; } private: uniform mat<4, 4> model; uniform mat<4, 4> view; uniform mat<4, 4> projection; };<file_sep>#include <cmath> #include <algorithm> #include "renderer_controller.h" const int WIDTH = 800; const int HEIGHT = 800; int main(int argc, char** argv) { TGAImage _outFrame(WIDTH, HEIGHT, TGAImage::RGB); RendererController* controller[3] = {NULL}; if (2 == argc) { controller[0] = new RendererController(WIDTH, HEIGHT, argv[1], _outFrame); controller[0]->run(); } else { //controller[0] = new RendererController(WIDTH, HEIGHT, "obj/african_head/african_head", _outFrame); controller[0] = new RendererController(WIDTH, HEIGHT, "obj/diablo3_pose/diablo3_pose", _outFrame); controller[0]->run(); //controller[1] = new RendererController(WIDTH, HEIGHT, "obj/african_head/african_head_eye_inner", _outFrame); //controller[2] = new RendererController(WIDTH, HEIGHT, "obj/african_head/african_head_eye_outer", _outFrame); //controller[1]->run(); //controller[2]->run(); } for (int i = 0; i < 3; i++) { if (controller[i]) delete controller[i]; } _outFrame.flip_vertically(); // to place the origin in the bottom left corner of the image _outFrame.write_tga_file("framebuffer.tga"); //getchar(); return 0; }<file_sep>#pragma once #include "model.h" #include "shader.h" class Rasterization { public: Rasterization(IShader* modelShader, IShader* depthShader); ~Rasterization(); void viewPort(int x, int y, int w, int h); void line(int x0, int y0, int x1, int y1, TGAImage& image, TGAColor color); //fisrt of all, implement triangle rasterization with simple color void triangle(vec2 t0, vec2 t1, vec2 t2, TGAImage& image, TGAColor color); //1. add z-buffer to implement depth test //2. add diffuse texture void triangle(vec3* clipPts, float* zbuffer, TGAImage& image, TGAColor color); // add same light intensity used in single triangle void triangle(Model* model, vec3* clipPts, vec2* uvPts, float* zbuffer, TGAImage& image, float intensity); // add normalPts to calculate different light intensity void triangle(vec3* worldPts, vec4* clipPts, vec2* uvPts, vec3* normalPts, float* zbuffer, TGAImage& image); // calculate shadow Buffer void triangle(vec4* clipPts, float* shadowBuffer, TGAImage& depth); protected: vec3 baryCentric(vec3* clipPts, vec3 P); private: IShader * modelShader; IShader * depthShader; double x; double y; double width; double height; mat<4, 4> viewport; }; <file_sep>#pragma once #include <vector> #include "geometry.h" #include "tgaimage.h" class Model { public: Model(std::string filename); ~Model(); int nverts(); int nfaces(); std::vector<int> vertFace(int idx); vec3 vert(int i); std::vector<int> uvFace(int idx); vec2 uvert(int i); std::vector<int> normalFace(int idx); vec3 normalvert(int i); TGAColor diffuse(vec2 uv); TGAImage* getDiffuseTexture(); TGAImage* getNormalTexture(); TGAImage* getTangentNormalTexture(); TGAImage* getSpecularTexture(); TGAImage* getGlowTexture(); private: std::vector<vec3> verts; std::vector<std::vector<int> > vertFaces; std::vector<vec2> uverts; std::vector<std::vector<int> > uvFaces; std::vector<vec3> normalverts; std::vector<std::vector<int> > normalFaces; TGAImage diffuseTexture; TGAImage normalTexture; TGAImage tNormalTexture; TGAImage specTexture; bool glow; TGAImage glowTexture; };
ad43ac729cbc5c0623af2c34d8b7013f4777d93e
[ "C++" ]
9
C++
beholdShadow/SoftRenderer
f118b4f9e2dc6e8a97db0c96fd1e6556f329ac6e
00bcfa96053f9228b33fcc39ac4ae50f63920db1
refs/heads/master
<repo_name>kawaken/http2test<file_sep>/main.go package main import ( "crypto/tls" "fmt" "io/ioutil" "log" "net/http" "os" "path/filepath" "golang.org/x/net/http2" ) func server() { certFile, _ := filepath.Abs("cert/server.crt") keyFile, _ := filepath.Abs("cert/server.key") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Protocol: %s\n", r.Proto) }) err := http.ListenAndServeTLS(":3000", certFile, keyFile, nil) if err != nil { log.Printf("Error: %s", err) } } func client() { /* // If TLSClientConfig is not nil. Then http.Client does not work with HTTP/2. t := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } */ t := &http2.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } client := &http.Client{Transport: t} res, err := client.Get("https://localhost:3000") if err != nil { log.Print("Error:", err) } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { log.Print("Error:", err) return } log.Print("Res:", string(body)) } func main() { if len(os.Args) == 1 { return } cmd := os.Args[1] switch cmd { case "server": server() case "client": client() } }
1887676804f881f2d425c0343e1bef338298e022
[ "Go" ]
1
Go
kawaken/http2test
134938b92bf90d9d5b7362904dd18b9177240334
b0664f168675702dd10eced5452cfb0300cecc34
refs/heads/master
<file_sep>// // ViewController.swift // Map Testing // // Created by <NAME> on 10/05/2017. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import GoogleMaps class ViewController: UIViewController { var mapView: GMSMapView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.mapView.delegate = self } override func loadView() { // Create a GMSCameraPosition that tells the map to display the // coordinate -33.86,151.20 at zoom level 6. let camera = GMSCameraPosition.camera(withLatitude: -33.86, longitude: 151.20, zoom: 6.0) mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera) view = mapView // Creates a marker in the center of the map. let marker = GMSMarker() marker.position = CLLocationCoordinate2D(latitude: -33.86, longitude: 151.20) marker.title = "Sydney" marker.snippet = "Australia" marker.map = mapView } } extension ViewController: GMSMapViewDelegate { func mapView(_ mapView: GMSMapView, didLongPressAt coordinate: CLLocationCoordinate2D) { // Custom logic here let marker = GMSMarker() marker.position = coordinate marker.title = "I added this with a long tap" marker.snippet = "" marker.map = mapView } } <file_sep># Uncomment this line to define a global platform for your project source 'https://github.com/CocoaPods/Specs.git' target 'Map Testing' do pod 'GoogleMaps' end
29b73914febfee0c0b7c4d8b799142ed908ce71e
[ "Swift", "Ruby" ]
2
Swift
martinjkelly/gmaps-ios-long-tap-sample
c2a86782bde34ee735b47ca27abbd291193a5186
4be740799aba2f0b25ebae99a182b2a2e8d6f401
refs/heads/master
<repo_name>whyman/v00d00.github.io-src<file_sep>/content/pulseaudio-and-kmix-4-4-in-sabayon-5.rst Pulseaudio and Kmix 4.4 in Sabayon 5 #################################### :date: 2010-03-23 22:33 :author: v00d00 :category: Linux, News, Uncategorized :tags: alsa, kde4, pulseaudio, sabayon, sound, upmixing :slug: pulseaudio-and-kmix-4-4-in-sabayon-5 :status: published Recently there have been a number of issues reported in the forums and other places of people having issues with pulseaudio and KMix after updating to KDE 4.4.0.  I am glad to announce that most of those issues should now be resolved with the latest round of updates being pushed out by hard-working entropy maintainer Joost! Woot! I identified the root of most of the problems which  seemed to be that we were shipping a quite broken pulseaudio configuration based on hard-wiring an ALSA module but also using the out dated HAL detection module, this has now been corrected to using the shiny new udev detection module by default. Other improvements to the new setup are up mixing by default to 5.1 and LFE remixing. I have also bumped the pulseaudio patch for KMix so that is working nicely also, with multiple stream control working, global hotkey support fixed and should fix most pulse + kde issues. As usual a “equo update && equo upgrade  –ask” will grab you the latest updates. If you have any issues please please please report a bug with logs on the `Bugzilla <http://bugs.sabayon.org>`__. <file_sep>/content/not-really-the-best-approach.rst Not Really The Best Approach ############################ :date: 2010-07-25 15:18 :author: v00d00 :category: Linux, Opinion :slug: not-really-the-best-approach :status: published Today I stumbled across `Netrunner GNU/Linux Community Distro <http://www.netrunner-os.com/>`__ and it made me wonder about a few things. Originally, it was Ubuntu with out the "evil Mono(tm)", now of course mainline Ubuntu has no mono either, so their USP was gone! So they changed their main idea. The latest release is based on Kubuntu (which makes it a 4th generation distro) and aims to improve the KDE that is provided by Kubuntu by, this is what really got me, integrating more of Gnome into KDE. Yes, really. Dolphin for instance is replaced by Nautilus, because Nautilus is more "Feature complete".  I'm not sure how they came to that conclusion at all and especially within KDE Dolphin really shines, its integration with tech like Nepomuk and friends is a big plus. In fact, which missing features of Dolphin? You mean the integrated terminal? No forced breadcrumb navigation? On wait, they are things Dolphin can do and Nautilus can't. If anything, nautilus is getting worse, espesially with Gnome's ongoing war against features that could confuse anyone with less mental power than a domesticated turkey. (Domesticated Turkey fact: Young Turkeys don't know how to eat. Turkey farmers make use of the chick's natural attraction to bright colours: marbles or strips of foil are placed into their food, or their food is sprayed with green food colouring. In pecking at the colours, the turkeys learn to eat. ) One idea on their suggestions forum was to ship Windows apps pre-installed, uTorrent in fact. Native applications aren't feature complete either?. I suppose this is the strength of Linux - if you are looking for a Linux flavour for any particular purpose there will be one available -  even if what you want is a KDE/Gnome/Windows cross-breed Mongrel. <file_sep>/pelicanconf.py #!/usr/bin/env python # -*- coding: utf-8 -*- # from __future__ import unicode_literals AUTHOR = '<NAME>' SITENAME = 'v00d00.net' SITEURL = '' THEME = 'themes/pelican-alchemy/alchemy' STATIC_PATHS = ['images', 'static'] ARTICLE_URL = '{date:%Y}/{date:%m}/{date:%d}/{slug}/' ARTICLE_SAVE_AS = '{date:%Y}/{date:%m}/{date:%d}/{slug}/index.html' PATH = 'content' TIMEZONE = 'Europe/London' DEFAULT_LANG = 'en' # Feed generation is usually not desired when developing FEED_ALL_ATOM = None CATEGORY_FEED_ATOM = None TRANSLATION_FEED_ATOM = None AUTHOR_FEED_ATOM = None AUTHOR_FEED_RSS = None SOCIAL = (('You can add links in your config file', '#'), ('Another social link', '#'),) DEFAULT_PAGINATION = 10 # Uncomment following line if you want document-relative URLs when developing #RELATIVE_URLS = True # http://docs.getpelican.com/en/stable/plugins.html#how-to-use-plugins PLUGIN_PATHS = ['plugins'] PLUGINS = ['pelican-bootstrapify'] BOOTSTRAPIFY = { 'table': ['table', 'table-striped', 'table-hover'], 'img': ['img-fluid'], 'blockquote': ['blockquote'], } SITESUBTITLE = "/dev/random" SITEIMAGE = "/images/terminal-solid.svg width=150 height=150" LINKS = ( ) ICONS = ( ('github', 'https://github.com/v00d00'), ('twitter', 'https://twitter.com/thevoodoo'), ) HIDE_AUTHORS = True <file_sep>/content/sabayon-linux-format-141.rst Sabayon in Linux Format #141 ############################ :date: 2011-01-11 19:35 :author: v00d00 :category: Linux, News, Sabayon :tags: 141, 5.4 G, format, linux :slug: sabayon-linux-format-141 :status: published I have been waiting for this day for so long! Great to see it finally happen! Thank you to everyone who has donated and may our path to world domination continue. Apologies for the crappy phone images, blame HTC. [gallery link="file"] Shame the logo was rendered wrong. <file_sep>/content/sabayon-linux-daily-iso-images.rst Press Release: Sabayon Linux x86/x86-64 daily ISO images ######################################################## :date: 2010-05-11 12:38 :author: v00d00 :category: News, Sabayon :tags: sabayon, sabayon 5 daily, sabayon beta, sabayon daily :slug: sabayon-linux-daily-iso-images :status: published After several weeks of testing and ironing, we are happy to announce the public availability of daily (or nightly if you prefer) Sabayon Linux (Standard and CoreCD editions) ISO images. The aim is to improve packages and general system functionality testing during releases lifecycle by providing always up-to-date installable LiveDVDs/LiveCDs. Our stable releases are just "snapshots" of these ISO images, so you will be able to know (and report) about possible hardware, software issue before a new version is published. Features of Sabayon DAILY ISO images: - Up-to-date packages (ISO images are built every night) - Featuring the new `Anaconda Installer <http://planet.sabayon.org/?s=anaconda>`__ port - Speed improvements over 5.2 ISO images - Fully compliant with our rolling-distro philosophy, keep looking ahead Minimum Requirements ~~~~~~~~~~~~~~~~~~~~ See respective Press Releases. Got a PC, keyboard and monitor? That's enough! Warning, this is the bleeding edge of bleeding edge, do not use them on production systems. ISO file names do not expose a timestamp directly, but RELEASE\_DATE\_DAILY does, as well as ISO boot menu and BUILD\_INFO inside the ISO image filesystem. Download sources ~~~~~~~~~~~~~~~~ Our Mirrors Page: - NOTE 1: files are inside iso/daily directory - NOTE 2: these ISO images are moving targets, make sure to check them against respective .md5 files. http://www.sabayon.org/download (Seems this never made it to planet so posting it here for reference, very cool imo) <file_sep>/content/gerbera-1.3-released.md Title: Gerbera Media Server 1.3 Now Available Date: 2018-04-29 10:20 Category: Gerbera Tags: gerbera, mediaserver, upnp Slug: gerbera-1-3-now-available Authors: <NAME> I am happy to announce that Gerbera Media Server 1.3.0 is now available. We have had contributions from 12 different contributors, putting together 161 changes since 1.2\. Thank you so much to everyone involved! A special thank you to [Eamonn](https://github.com/elmodaddyb) for all of his ongoing hard work! ## Changes - C++17 is now required to build (clang, gcc-7, gcc-8) - Improved Samsung DTV Support (Still not entirely complete, but some more models may work) - Added FLAC, Wavpack, DSD to default configuration - Fixed Transcoding bugs with HTTP Protocol - Properly handle upnp:date for Album sorting on UPNP devices - Exposed resource options to import scripts (audio channels etc) - Added support for Classical music tags: Composer, Conductor, Orchestra - Fix UI update bug for macOS - Add online-content examples - Improve scripted installation - Add configurable title for UI Home - Fix SQL bugs - Create Gerbera Homebrew Tap (for macOS High Sierra & Mojave) - Various bug fixes and ongoing refactoring - Add CentOS install instructions ## Get it Find out how to [install Gerbera](http://docs.gerbera.io/en/latest/install.html). Download the source from [Github](https://github.com/gerbera/gerbera/releases/tag/v1.3.0).<file_sep>/content/gnome-shell-e2-80-a6-meh.rst Gnome Shell… Meh ################ :date: 2010-03-24 00:19 :author: v00d00 :category: Linux, Opinion, Sabayon :tags: gnome ftl, Gnome shell, kwin, libdvdcss, ubuntu :slug: gnome-shell%e2%80%a6-meh :status: published Now with any major new release of GNOME you are going to get a lot of “OMG totally awesome new stuff in gnome!” posts. When there are blogs out there with names like “omgubuntu” you have to expect this. Gnome 3.0 at its core seems to be gnome shell bolted onto a standard gnome 2.2x, with the primary purpose it seems of hyping gnome using a bigger version number. Maybe its because KDE is now solid and gnome think they need something closer to KDE’s Plasma? However, I will watch with interest at what happens in regards to gnome shell, Its nice to see that if needed Gnome can do something new. Great. The real question is do you want it to do something new? For me its a No, I don’t. Gnome is generally preferred by businesses building a working desktop out of Linux, why? Because its solid, predictable, a tried a tested desktop, why mess with it….that’s KDEs job! That’s why it wont be included in Ubuntu until late 2010 I suppose. Looking like Empathy all over again. And breaking Compiz compatibility is not cricket. Its only really ever worked properly on Gnome, I’ve moved on to Kwin now but that is beside the point. In other news, I’m very happy that you have all voted “HELL YEAH” to keeping libdvdcss for many of the reasons I originally gave to keep it, I have 0 clue why Fabio wanted it removed anyway. It does mean however that we cant be included on cover disks of magazines, which is a shame, would love to see Sabayon on the cover of Linux Format, but playing DVDs out of the box is always a winner with me! <file_sep>/content/107.rst LXDM Theme ########## :date: 2010-07-29 23:07 :author: v00d00 :category: Uncategorized :slug: 107 :status: draft <file_sep>/content/gerbera-1.2-released.md Title: Gerbera Media Server 1.2 Now Available Date: 2018-04-29 10:20 Category: Gerbera Tags: gerbera, mediaserver, upnp Slug: gerbera-1-2-now-available Authors: <NAME> I am happy to announce that Gerbera Media Server 1.2.0 is now available. We have had contributions from 15 different contributors, putting together 172 changes since 1.1\. Thank you so much to everyone involved! ## New Web UI The most noticeable change since v1.1 will be new awesome new Web UI. We shipped a beta of this in the previous version, but now it it is ready for prime time, and enabled by default. ![filesystem-view](/images/filesystem-view.png) Thank you to [Eamonn](https://github.com/elmodaddyb) for all of his ongoing hard work! ![gerbera-import-webui](/images/gerbera-import-webui.gif) ## UPnP Search Gerbera now supports searching! This allows clients to offload the hard work of finding your media to the server, this is both faster an more reliable than clients doing it themselves. If you are a BubbleUPnP user on android, this means the "Random Tracks" feature now works. Thank you to [astylos](https://github.com/astylos) for this great feature! ## Improved Docs Some of you have mentioned that Gerbera's documentation, as with many other free software projects, has not been as good as it could or should have been. We are happy to point you to [docs.gerbera.io](http://docs.gerbera.io/), kindly hosted by [Read the Docs](https://readthedocs.org/). If you wish to help, it is very easy to get started, simply open a pull request against Sphinx files in the `doc` folder. ## Bye, Youtube Youtube support has not worked for a long time so it has been removed from the code base entirely. Similar functionality may return in a future release. ## Bugfixes * Fixed AUXDATA truncation with UTF-8 characters. * Improved message when libupnp fails to bind correctly. * Allow use of FFMpeg to extract AUXDATA * Duktape JS scripting errors are now visible in log file * Fixed a crash in EXIV2 image handler. * Fixed "root path" sometimes missing for scripted layouts. ## Get it Find out how to [install Gerbera](http://docs.gerbera.io/en/latest/install.html). Download the source from [Github](https://github.com/gerbera/gerbera/releases/tag/v1.2.0).<file_sep>/content/holiday-sabayon-5-kde-4-3.rst Holiday & Sabayon 5 KDE 4.3 ########################### :date: 2010-03-24 00:19 :author: v00d00 :category: Uncategorized :slug: holiday-sabayon-5-kde-4-3 :status: published Im back! woot. After a week of holiday its good to get involved again with some Sabayon stuff. Holiday was nice got to see the Folks and have a bit of a computer detox! Im surprised I survived so long with no linuxiness to be honest. So I come back and the branch 5 situation has changed a bit, (which 100+ testers/devel mailing list messages attest too) the 5.0 Beta1 iso has been pushed out to the testers and then lxnay decides its a good time for a holiday (good timing perhaps?). There seems to be the usual mixed issues with the first ISO spin, most issues now seem to be handled by improved entropy and migration scripts, branch 5 is shaping up nicely. Ive switched to KDE4.3 from Gnome, So expect to see a much more polished and enhanced KDE (as you did with gnome when I switched to that) in the next release, things on KDE todo list are: #. New QT theme (10% Done) #. Getting sysinfo:// working (100% Done) #. Getting sysinfo:// customised (15% Done) #. Kicker Customisation (SL Logos etc) #. Skel Cleanup #. Sabayon XDG Menus Improve KDE Compat #. Etc etc… Feel free to add anything you want done to KDE in the comments and Ill incorporate them if appropriate. Next post has 5.0\_beta2 theme previews! <file_sep>/content/new-firefoxes.rst New Firefoxes ############# :date: 2010-03-24 00:21 :author: v00d00 :category: Uncategorized :slug: new-firefoxes :status: published Yesterday I pushed `3 new firefox versions <http://gitweb.sabayonlinux.org/?p=overlay.git;a=tree;f=www-client/mozilla-firefox;hb=HEAD>`__ into the sabayon overlay, “whats so great about these firefoxes?” I hear you ask, well there are a few things. Firstly they branded correctly as “Sabayon” which means sites that pick up on what OS your using will show you as usiong Sabayon and not Gentoo. For example on my `blog <http://main.v00d00.net/>`__, when you post a comment you will get a little Sabayon logo by your comment! (had to patch the wordpress plugin, but it has been accepted upstream now) Secondly they now use the Sabayon homepage as default, not gentoo.org, which means in theory we could remove the firefox profile from skel (and have one less thing to worry about). However skel also has some setting to make sure Flash and Java work OOTB so maybe not a good idea to that just yet, but we will see. Finally, there are newer versions! woop! By default everyone will get an upgrade to firefox 3.5\_rc2 (-r10). However there is still an older (stabler) version of 3.0.11(-r10) available for those who dont want to run a RC browser. For the brave there is also a bleeding edge 9999(-r1) ebuild which pulls the very latest code directly from the mozilla repository. I use the 9999 build with 0 problems. Please report any issues you encounter with these new builds to the `sabayon bugzilla <http://bugs.sabayonlinux.org/>`__. 4.2 is chugging along with testing nicley and the testers have just got a pre-alpha of the CoreCD version too.  As always keep an eye on planet for the latest updates <file_sep>/content/sabayon-5-2-status-update.rst Sabayon 5.2 Status Update ######################### :date: 2010-03-24 10:22 :author: v00d00 :category: Uncategorized :slug: sabayon-5-2-status-update :status: published So its been a while since I’ve blogged so I thought I would take some time to let you know whats happening in Sabyon-dev-land. Limbo users will have noticed lots of cool stuff has been added including the Phoronix Test Suite, KDE4.4RC, Emesene 1.6 as well as the usual swathes of updates. These updates  will ofcourse mature into Sabayon 5.2, so what can you expect? Highlights are: - Sabayon 2.6.32 kernel - Xorg 1.7 - KDE 4.4 - GRUB2 - Smaller ISOs due to dependency clean-ups - Sexy new theme - And More! A 5.2 beta is due to be created soon and given out to our testers team,  the the main hold up is due to ATI not releasing a driver compatible with Xorg 1.7, we are undecided whether we are going to drop the binary ati-drivers in favour of the more reliable as nearly as complete open source ati driver, your opinion is needed here :). So many things to look forward to there. We are looking for suggestions on ways to improve the disks so post a comment if you have a wishlist! <file_sep>/content/blogroll-o-development-blog-o-documentation-o-plugins-o-suggest-ideas-o-support-forum-o-themes-o-wordpress-plane.rst Sysinfo Kioslave on Sabayon 5 ############################# :date: 2010-03-24 00:14 :author: v00d00 :category: Uncategorized :slug: blogroll-o-development-blog-o-documentation-o-plugins-o-suggest-ideas-o-support-forum-o-themes-o-wordpress-plane :status: published The sysinfo:/ kioslave (aka “My Computer”) in konqueror is one of my favourite KDE3.5 features, I saw that SuSE and Fedora had this working so decided to “port” it over to sabayon, so after a few hours of playing around (my term for Sabayon work lol) there is one more thing off `my list <http://main.v00d00.net/holiday-sabayon-5-kde-4-3>`__, w00t.  Got that sorted yesterday, after a little patch to get it to compile and some custom artwork the result is shown at the bottom of this page: Got a list of more stuff to-do however, =D. If you are wondering about the network status, it picks it up from network manager, I use wicd, so thats not showing up. Its on the overlay now so if you want to try it, or if joost\_op is awake you could use equo, this will be added to branch 5 only. :: equo install kio-sysinfo or :: emerge  -av kio-sysinfo On an unrelated note if anyone has an ATI (r600+) which they would like to donate, that would be great. I'm a Nvidia user personally but have been wanting to test ATi stuff. <file_sep>/content/path-to-sabayon-5-4.rst The Path to Sabayon 5.4 ####################### :date: 2010-07-08 14:53 :author: v00d00 :category: Linux, News, Sabayon :tags: bugzilla, KDE 4.5, sabayon 5.4, sabayon kde, theme :slug: path-to-sabayon-5-4 :status: published Recently I seem to have been neglecting my blog a bit, I will try to keep it more regularly updated from now on. The next Sabayon Linux release will be 5.4 as usual it will have the usual skew of package updates and bug fixes. We are tracking the bugs earmarked for fixing before 5.4 using the `Sabayon 5.4 Tracking Bug <http://bugs.sabayon.org/show_bug.cgi?id=1575>`__. This means that you can see which bugs will be fixed for 5.4 and the status of each issue individually; it also means you can report bugs and we can easily target those before each release. This is a new public approach for to nailing down issues before release and is due in part to structural changes within the Sabayon testers group. Previously the Sabayon testers team (who are one of Sabayon’s most valuable assets) had a closed mailing list and IRC channel, as of this week both of these are being closed and all activity will be moved over to the existing public infrastructure of the `Sabayon-dev <http://lists.sabayon.org/cgi-bin/mailman/listinfo/devel>`__ mailing list and #Sabayon-dev IRC channel on freenode. The ‘opening up’ of the process was done to improve communication with the wider community, ideally it will  get some more testers involved in testing and encourage more widespread input on the varying aspects of the the distribution. If you want to get involved, just grab one of the Sabayon daily images and hop on the `devel mailing list <http://lists.sabayon.org/cgi-bin/mailman/listinfo/devel>`__ with any issues. I have decided to pick my artwork duties back up for 5.4 (as no else has volunteered to do art!) which means I can also reveal some things regarding the theme for 5.4. Firstly there will be a new theme which shares a colour scheme with the current 5.x theme, hooray! Secondly, the Sabayon “hens foot” logo will be brought back as the official Sabayon logo! Woot! There will also be a brand new KDM theme and wider KDE will be getting some theming love too. In conclusion then, there is a lot to look forward to in Sabayon Linux 5.4, stay tuned for more information. <file_sep>/content/sabayon-5-2-artwork-alphadraft-1.rst Sabayon 5.2 Artwork Alpha/Draft 1 ################################# :date: 2010-03-24 00:16 :author: v00d00 :category: Linux, News, Sabayon :tags: 5.2, artwork, KDE, preview :slug: sabayon-5-2-artwork-alphadraft-1 :status: published Even though 5.1 isn’t out yet (with many goodies I may add), work on the 5.2 artwork has started, plan for Sabayon 5.2 currently is a polished and reworked 5.0 style design. As always comments are welcome. Click the Image to enlarge to full size! |Sabayon 5.2 Preview Image is a HD image, sorry for the wait lol| .. |Sabayon 5.2 Preview Image is a HD image, sorry for the wait lol| image:: http://gitweb.sabayon.org/?p=artwork.git;a=blob_plain;f=5.2/sabayon-artwork-core/background/sabayonlinux.jpg;h=258381a067ee589cf5dd26506930493dcfa88728;hb=2dbecfb78ef34874073c6b8519508033fb1ed2f5 :class: alignnone :width: 100.0% :target: http://gitweb.sabayon.org/?p=artwork.git;a=blob_plain;f=5.2/sabayon-artwork-core/background/sabayonlinux.jpg;h=258381a067ee589cf5dd26506930493dcfa88728;hb=2dbecfb78ef34874073c6b8519508033fb1ed2f5 <file_sep>/content/sabayon-nightly-builds-installer-recruitment.rst Sabayon - Nightly Builds, Installer & Recruitment ################################################# :date: 2010-04-26 09:47 :author: v00d00 :category: Gentoo, News, Sabayon, Uncategorized :tags: 5.3, artwork, entropy, molecule, nightly builds, sabayon, sabayon 5.3, sabayon beta :slug: sabayon-nightly-builds-installer-recruitment :status: published |image0| Well, it’s been a while since I’ve blogged, so I think its time I started doing it more regularly again. So what is going down in Sabayon HQ? Well there have been many interesting developments recently which I want to talk about. Firstly we have the brand spanking new shiny Anaconda installer, this has been well publicised by `wolfden <http://wgo.wolf911.us/?p=357>`__ and `Lxnay <http://planet.sabayon.org/?p=1487>`__ and is really shaping up nicely, its about time the installer got an update and it is looking awesome, everyone has been testing (and breaking) the new installer and progress looks excellent. This is of course mainline Anaconda that is used in Fedora and RHEL et al and has inherited all the great features from it with some new sabayon specific stuff too, this version is more closely based on vanilla upstream git and as such we should inherit all the work that is being done upstream a lot faster. Next up is nightly builds of sabayon, yes you read that correctly. The idea is that you will have one ISO on your hard disk which you will keep updated using rsync’s binary diff capabilities and the Sabayon rsync servers to only update the parts of the ISO that have changed, this is how we have been distributing ISOs to testers for a while now and is much quicker and easier than the old version using Xdelta. What has been done is that we have a scripted molecule install which creates a new ISO at 0200 UTC every night using the latest packages from the mainline repository, from these images the rysnc is updated and you can download the changes, simple but clever if you ask me. Finally – recruitment. Getting people to work on an open source project is never easy, its not easy to find volunteers for anything in reality as time is such an expensive commodity. I have decided to step down from my position as artwork guy and as such Sabayon is looking for a replacement, if you have some design and theming skills, or even if you don’t why not get in `contact <mailto:<EMAIL>?subject=Artwork%20Replacement>`__ with me and I’ll get you started. You will need a good eye, ability to work in a team an interest in Sabayon and ability to use SVG, it would be preferred if you had some knowledge of bash scripts, ebuilds and linux theming, but we can train you if your designs are great. Once again, please do get in contact, either mail me, start a thread in the forums and show us your stuff or leave a comment even. …and that’s all I can think of for now. .. |image0| image:: http://upload.wikimedia.org/wikipedia/commons/b/be/Sabayon4foot.png :width: 131px :height: 131px <file_sep>/content/press-release-sabayon-linux-5_2-gnome-kde.rst Press Release: Sabayon Linux x86/x86-64 5.2 GNOME and KDE ######################################################### :date: 2010-03-26 13:47 :author: v00d00 :category: Linux, News, Sabayon :tags: GNOME, KDE, press release, sabayon 5.2 :slug: press-release-sabayon-linux-5_2-gnome-kde :status: published | The best, refined blend of GNU/Linux, coming with bleeding edge edges is eventually here! Say hello to Sabayon Five-point-Twoh, available in both GNOME and KDE editions! | Dedicated to those who like cutting edge stability, out of the box experience, outstanding Desktop performance, clean and beauty. Sabayon 5.2 will catch you, anything that could have been compiled, has been compiled, anything cool that could have been implemented or updated, it's there: you will find outstanding amount of new applications and features, like XBMC 9.11, KDE 4.4.1, GNOME 2.28, Linux Kernel 2.6.33, and so forth. | So, come on, go catch it, it's half a DVD away from you! Visual Tours: ------------- - `Take a Tour - Booting (GNOME) <http://wiki.sabayon.org/index.php?title=Visual_Tour:_Booting_Sabayon_Linux_Gnome>`__ - `Take a Tour - Installer (GNOME) <http://wiki.sabayon.org/index.php?title=Visual_Tour:_Installing_Sabayon_Linux_Gnome>`__ - `Take a Tour - Booting (KDE) <http://wiki.sabayon.org/index.php?title=Visual_Tour:_Booting_Sabayon_Linux_KDE4>`__ - `Take a Tour - Installer (KDE) <http://wiki.sabayon.org/index.php?title=Visual_Tour:_Installing_Sabayon_Linux_KDE4>`__ Features of Sabayon 5.2: ------------------------ - Based on new GCC 4.4.1 and Glibc 2.10 - Shipped with Desktop-optimized Linux kernel 2.6.33 - Providing extra Server-optimized and OpenVZ-enabled kernels in repositories - Installable in 10 minutes - Faster boot time and lightweight default system - Ext4 filesystem as default - Encrypted filesystem support - Featuring X.Org 7.5 and up-to-date Open Source, NVIDIA, AMD video drivers - Containing GNOME 2.28 (with GNOME Shell!) and KDE 4.4.1 - Outstanding 3D Desktop applications (Compiz, Compiz Fusion and KWin) working out of the box - Bringing Entropy Framework (Package Manager) 0.99.38.7 - Shipped with OpenOffice 3.2 productivity suite, Multimedia applications - Transform Sabayon into an full-featured HTPC Operating System (Media Center) using XBMC - Shipped with World of Goo Demo - best 2D game ever! - Sexiest Skin ever! (Light blueeee!) - Try it out from Windows, just kick the DVD in and use Sabayon via QEMU virtualization! - Ready for Sabayon 6 (someday!) Updates since Sabayon 5.2: -------------------------- - New Linux Kernel 2.6.33 with enhanced wireless and power management support - Switched to GRUB2, improved Mac support - Improved VirtualBox Input drivers support - KDE updated to 4.4.1 and now more integrated than ever (featuring new KNetworkManager)! - Entropy Framework updated to 0.99.38.7, featuring outstanding performance improvements, tons of bugfixes and features (see `our Git repos <http://gitweb.sabayon.org/>`__). Working towards 1.0! - More than 2000 new updated packages available (since Sabayon 5.1) - Greatly improved boot time - Improved Pulseaudio/ALSA support - Reduced ISO images footprint by 100Mb - Improved NVIDIA legacy drivers support - Improved XBMC, Media Center installation profile support and reliability Requirements ------------ | Minimum requirements: | - an i686-compatible Processor (Intel Pentium II/III, Celeron, AMD Athlon) | - 512Mb RAM | - 6 GB of free space | - A X.Org supported 2D GPU | - a DVD reader | Optimal requirements: | - a Dual Core Processor (Intel Core 2 Duo or better, AMD Athlon 64 X2 or better) | - 1024Mb RAM | - 15 GB of free space | - A X.Org supported 3D GPU (Intel, AMD, NVIDIA) (esp. for XBMC) | - a DVD reader Resources for Sabayon Linux 5.2 GNOME and KDE: ---------------------------------------------- | Kernel Configuration: | - `Sabayon 5.2 x86 kernel config <http://gitweb.sabayon.org/?p=overlay.git;a=blob;f=sys-kernel/linux-sabayon/files/linux-sabayon-2.6.33-x86.config;hb=HEAD>`__ | - `Sabayon 5.2 amd64 kernel config <http://gitweb.sabayon.org/?p=overlay.git;a=blob;f=sys-kernel/linux-sabayon/files/linux-sabayon-2.6.33-amd64.config;hb=HEAD>`__ | Packages list: | - `Sabayon Linux x86 5.2 KDE Packages <http://www.sabayonlinux.org/sabayon/pkglist/Sabayon-5.2-x86K.txt>`__ | - `Sabayon Linux x86-64 5.2 KDE Packages <http://www.sabayonlinux.org/sabayon/pkglist/Sabayon-5.2-amd64K.txt>`__ | - `Sabayon Linux x86 5.2 GNOME Packages <http://www.sabayonlinux.org/sabayon/pkglist/Sabayon-5.2-x86G.txt>`__ | - `Sabayon Linux x86-64 5.2 GNOME Packages <http://www.sabayonlinux.org/sabayon/pkglist/Sabayon-5.2-amd64G.txt>`__ Download sources ---------------- | Our Mirrors Page: | - http://www.sabayon.org/download | Bittorrent: | - http://tracker.sabayon.org/ <file_sep>/content/amazing-artwork.rst Amazing Artwork ############### :date: 2010-07-26 22:33 :author: v00d00 :category: Linux, Sabayon :tags: artwork, cartoon, sabayon, sabayon 2010, wolfden :slug: amazing-artwork :status: published We are well known for our beautiful artwork here at Sabayon, and I would like to share this amazing cartoon, produced by wolfden. |Sabayon 2010| If you are the devel mailing list you will have seen this already in the ongoing debate over "What is Sabayon" with regards to user group focus and the website. If you have any opinion on what Sabayon is, please leave it in the comments. .. |Sabayon 2010| image:: http://v00d00.net/wp/wp-content/uploads/2010/07/Sabayon.jpg :class: alignleft size-full wp-image-97 :width: 100.0% :target: http://v00d00.net/wp/wp-content/uploads/2010/07/Sabayon.jpg <file_sep>/content/looking-for-derivatives.rst Looking for Derivatives ####################### :date: 2011-04-28 21:55 :author: v00d00 :category: Linux, News, Sabayon :tags: Derivatives, sabayon 5.6, sabayon spin :slug: looking-for-derivatives :status: published A quick call for anyone who has created a Sabayon derivative or spin that is publicly available. I am currently adding a derivatives section on the new site and it looking a bit bare, so if you would like the possibility of some more hits for your Sabayon based distro, please `contact me <mailto:<EMAIL>>`__ with details. Please include a project name, homepage and short description. Thanks! <file_sep>/content/life-new-sabayon-site-design-sabayon-5-5-teaser.rst Life, New Sabayon Site Design & Sabayon 5.5 Teaser ################################################## :date: 2010-10-27 20:06 :author: v00d00 :category: Linux, News, Sabayon :tags: artwork, bugzilla, job, ParkerBeta, sabayon 5.5, Sabayon Design :slug: life-new-sabayon-site-design-sabayon-5-5-teaser :status: published So what have I been up to lately? Well, I have recently got a nice new job with a local ex-ISP turned "cloud services" provider so I'm looking forward to jumping into the new role which, I hope, will be far more interesting as it will unleash my passion for Linux in a commercial environment. I've been a bit less active on the Sabayon front because of the job hunting and such but should increase again soon. One of the things I've been working on is the Sabayon website design, the plan is to provide the whole portal and services with a uniform clean look that is more accessible and easy to use. I've attached a screenshot of the homepage draft design, feedback as always is encouraged. |Sabayon Website Redesign Beta| I have moved `bugs.sabayon.org <http://bugs.sabayon.org>`__ to the `Bugzilla.git repository <http://gitweb.sabayon.org/?p=bugzilla.git;a=summary>`__ but have not been able to work on the new styling for a while which is a shame however its high on my todo list. I've also been improving some of my various other projects, for instance the IRC bot ParkerBeta on the #Sabayon IRC channels on Freenode, the facts database module recently got an update to enable to the deletion of particular numbered entries on entries with multiple output. The not so functional Entropy module is getting a major update to use another of my recently started projects a `JSON <http://en.wikipedia.org/wiki/JSON>`__ API for entropy, its currently in the very early stages, but when finished should allow lots of cool stuff to built on top of it, think nice AJAX web interfaces etc. So finally: Sabayon 5.5 may or may not be planned for around Christmas. .. |Sabayon Website Redesign Beta| image:: http://v00d00.net/wp/wp-content/uploads/2010/10/sabayon-website-new.jpg :class: alignleft size-full wp-image-110 :width: 100.0% :target: http://v00d00.net/wp/wp-content/uploads/2010/10/sabayon-website-new.jpg <file_sep>/content/gerbera-1.1-released.md Title: Gerbera 1.1 Released Date: 2017-09-29 10:20 Category: Gerbera Tags: gerbera, mediaserver, upnp Slug: gerbera-1-1-released Authors: <NAME> [![Gerbera Logo](/images/gerbera-logo-horiz.png)](https://gerbera.io/) I am proud to announce the second release of the Gerbera media server. There have been over 110 commits since 1.0 from 13 awesome contributors. ## So whats new? ### Modern UI Preview @elmodaddyb has been hard at work on the next generation UI for Gerbera. Built using Boostrap4 with TDD methodologies; this will be the default Web UI in a future version. This release includes a read only preview of the interface. Access it by visiting `gerbera.html` on your v1.1 install e.g. `http://localhost:49152/gerbera.html` You can keep track of the progress [on the New UI github issue](https://github.com/gerbera/gerbera/issues/84). ![](https://user-images.githubusercontent.com/8599799/28802450-7605ea34-7624-11e7-8185-3425a6000d32.png) ### Raspberry Pi / 32bit fixes Post 1.0 we had a number of issues reported by Raspberry Pi users. Investigation found that we were not properly supporting large files in the build system for 32 bit hosts. We have added LFS support and Gerbera now runs great on Raspberry Pi! Unfortunately this issue highlighted a bug in libupnp - client apps should fail to build when their LFS state did not match libupnp. This has been [fixed](https://github.com/ukleinek/pupnp/commit/74c98de50a03f603d6fedf3d4f0377b274d54d75) upstream. ### Video thumbnail support Support for video thumbnails using FFMpegThumbnailer is back. You can enable video thumbnail support by passing `-DWITH_FFMPEGTHUMBNAILER=1` at build time and set `<ffmpegthumbnailer enabled="yes">` in your config file to get pretty thumbnails for your video files. ### Protocol Extensions You can now enable incomplete DLNA protocol extensions in Gerbera. With this option Gerbera makes changes to the data sent to devices to enable support for less picky DLNA renderers. It also enables AlbumArt/Thumbnails on some devices (e.g. various LG TVs). Full DLNA support is high on the ToDo list, however we are still waiting for custom HTTP header support in libupnp before we can implement it. If you want to help (or know somebody who can), [please check out libupnp's github]https://github.com/mrjimenez/pupnp/pull/49). ### BSD Fixes We have had some great feedback and patches from BSD users since 1.0 and we have merged user patches to add support for INotify via libinotify and to add support for native UUID generation functions. ### Album Artists AlbumArtist metadata is now extracted from media files (where supported) and is used to populate the "creator" field for albums. It is also available for use with custom JavaScript powered layouts. ### OSX improvements @elmodaddyb spent some time getting Gerbera running on OSX and [produced some build instructions](https://github.com/gerbera/gerbera#on-macos), we now ship an [OSX Launchd script](https://github.com/gerbera/gerbera/tree/master/scripts/launchd) in the repo. ### Other notable changes * MySQL is no longer enabled by default in CMake, you will need to pass `-DWITH_MYSQL=1` at build time if you want support. We recommend using SQLite. * The `--pidfile` option has been removed, as we removed the `--daemon` option in the previous release retaining `--pidfile` option did not make sense. Please update your scripts if you were using this flag. * We have moved to a new github organisation, check us out at [github.com/gerbera](https://github.com/gerbera) 👍 And more! As always a huge thanks to everyone who has contributed to this release. See [how to install Gerbera](https://github.com/gerbera/gerbera#installing) on your OS/Distro or [download the source](https://github.com/gerbera/gerbera/releases/tag/v1.1.0) from Github. ### Note on LibUPnP support This release supports <=libupnp 1.8.2 due to breaking changes in libupnp master branch, 1.2 will most likely require >=1.8.3.<file_sep>/content/gerbera-1.0-released.md Title: Gerbera v1.0 Released Date: 2017-05-29 10:20 Category: Gerbera Tags: gerbera Slug: gerbera-v1-0-released Authors: <NAME> ![Gerbera Logo](/images/gerbera-logo-horiz.png) I am proud to announce the first release of the Gerbera media server! There have been over 340 commits since the last commit on the MediaTomb git. These including porting the build system to cmake, removing lots of bundled code (including libupnp itself), replacing spidermonkey with duktape, code housekeeping, album artwork support, bugfixes and more. A a lot of work done, but much much more is still to do! This release is so we can get the code into the hands of more people for wider testing, hopefully to get packages built for a range of distributions and get even more testing and (hopefully) pull requests as a result 👍 Huge thanks to everyone who has contributed to this release, including the original MediaTomb authors for creating such a great project. [Download from Github](https://github.com/v00d00/gerbera/releases/tag/v1.0.0)<file_sep>/content/sabayon-6-released.rst Sabayon 6 Released! ################### :date: 2011-06-23 09:13 :author: v00d00 :category: Linux, Sabayon :slug: sabayon-6-released :status: published |Image| We're once again here to announce the immediate availability of Sabayon 6, one of the biggest milestone in our project. Letting bleeding edge and reliability to coexist is the most outstanding challenge our users, our team, is faced every day. There you have it, shining at full bright, for your home computer, your laptop and your home servers. Because we do care about our community, we do listen to our users, we consider them part of the game, we decided to leave GNOME3 out for another, last, release cycle, in order let things to settle down: providing a broken user experience has never been in our plans. Besides, what do we have under the hood this round? Let's go ahead and see. | Please don't forget to `donate here <http://www.sabayon.org/donate>`__, we still need your support. | Thanks to your donations, we were able to buy a new development server, but we need more I/O speed now! Features -------- - Linux Kernel 192.168.127.12 and blazing fast, yet reliable, boot - Providing extra Server-optimized, OpenVZ-enabled, Vserver-enabled kernels in repositories - Natively supporting btrfs filesystem - Completely reworked artwork and boot music intro, thanks to our little Van Gogh (<NAME>) - Improved theming for 16:9 and 16:10 widescreen monitors - Transform Sabayon into an full-featured HTPC Operating System (Media Center) using XBMC - Entropy 1.0\_rc10, bringing outstanding speed and reliability. Entropy Store (Sulfur) went through a massive speed rework. Entropy Web Services foundation library has been introduced in order to support User Generated Content contributions in a `more powerful way <http://packages.sabayon.org/>`__, bringing our Package Manager in the Social Internet age. Added support to delta packages downloads, parallel packages download, differential repository update through simple HTTPS protocol - Several Sabayon Installer improvements, especially with dealing with crypt, LVM and swRAID environments - Added a non-intrusive firewall tool called "ufw" and its frontends for GNOME and KDE - X.Org Server updated to 1.10 - Sane Desktop Compositing now enabled by default - Switched to IcedTea6 as bundled Java VM - Switched to jpeg-turbo library, boosting JPEG images rendering speed - Switched to LibreOffice 3.3.3 - Switched to Chromium/WebKit as bundled Web Browser - Split nvidia-drivers and ati-drivers into userspace and kernel modules, improving reliability over kernel migrations - Updated to GNOME 2.32.2 and KDE 4.6.4 - Updated to GRUB 1.99 - Introduced the "kernel-switcher" tool, to easily switch between available Sabayon Linux kernels - Python toolchain updated to version 2.7 - Updated to GCC 4.5.2 - Dracut and Plymouth ready (expect them in Sabayon 7) - Thousands of updates and bug fixes that flew in, during these last 4 months - We're still here! (it's a feature), only thanks to your donations, please keep donating, `donate now <http://www.sabayon.org/donate>`__! Minimum requirements (aka, we don't underestimate them, like everybody else does): ---------------------------------------------------------------------------------- - An i686-compatible Processor (Intel Pentium II/III, Celeron, AMD Athlon) - 512Mb RAM (GNOME) - 768Mb RAM (KDE) - 8 GB of free space - A X.Org supported 2D GPU - A DVD reader Optimal requirements ~~~~~~~~~~~~~~~~~~~~ - A Dual Core Processor (Intel Core 2 Duo or better, AMD Athlon 64 X2 or better) - 1024Mb RAM - 15 GB of free space - A X.Org supported 3D GPU (Intel, AMD, NVIDIA) (esp. for XBMC) Download sources ---------------- ISO images (those little .iso files that you have download and burn) are available on our mirrors: - Sabayon Linux 6 amd64 (x86\_64, x64) GNOME: 06b51b1b0210a636c40a0eba1822539c Sabayon\_Linux\_6\_amd64\_G.iso - Sabayon Linux 6 x86 (i686, x32) GNOME: 76ce8f9871940573a5841123348def29 Sabayon\_Linux\_6\_x86\_G.iso - Sabayon Linux 6 amd64 (x86\_64, x64) KDE: ce2d774270bb8c020aedf76f5f57e5bb Sabayon\_Linux\_6\_amd64\_K.iso - Sabayon Linux 6 x86 (i686, x32) KDE: 68ece268e181967b8200382b019e3c0b Sabayon\_Linux\_6\_x86\_K.iso - `Sabayon Mirrors Page <http://www.sabayon.org/download>`__ - `Sabayon Bittorrent Tracker <http://tracker.sabayon.org/>`__ Thanks everybody involved! ~~~~~~~~~~~~~~~~~~~~~~~~~~ To comment, see the forum `Here <http://forum.sabayon.org/viewtopic.php?f=60&t=24397>`__. .. |Image| image:: http://static.sabayon.org/site/content/marketing/sl6-now-available.png <file_sep>/content/sshfs-is-awesome.rst SSHFS is Awesome ################ :date: 2010-03-24 00:18 :author: v00d00 :category: Opinion, Sabayon :tags: Awesome!, sshfs :slug: sshfs-is-awesome :status: published Now sometimes you find a bit of Linux goodness that makes your geeky bits tingle, I found one recently, its called SSHFS, and its part of the awesome fuse framework. As you may have guessed it allows you to mount a file system through a SSH connection, this means it can be read from and saved to as any other part of your local file-system! This leads to some cool possibilities, mounting a remote server over a secure connection for easy file uploads and downloads, the ability to run local scripts on remote files (WIN) and more. Its ultra easy to use: :: emerge -av1 sys-fs/sshfs-fuse or :: equo install sshfs-fuse then :: sshfs username@server:/path/to/mountpoint I have it set up to run when I login and I use RSA key based auth so no passwords for ultraconvience at the price of a little bit of security. Just thought I’d spread the word a bit. <file_sep>/content/kde4-theming-aurorae.rst KDE4 Theming & Aurorae ####################### :date: 2010-03-24 00:20 :author: v00d00 :category: Uncategorized :slug: kde4-theming-aurorae :status: published When KDE4 was first released I was shocked at the lack of conguration options themewise compared to 3.5 and its wealth of options, I had best note plasma however is a notable exception,  a triumph of customisation and SVG goodness! Kwin has needed a decent engine for theming for a while, while its almost on par in terms of effects with compiz, it has always lacked the extensive customisation features provided by emerald and its various engines. Then there is the default QT theme in KDE4.3 (oxygen). This has many fans and it is nice to see some technoloigical progress being made in terms of themeing. Personally im not a fan of the whole oxygen look as it wastes to many pixels and is mostly plain grey. In my opinion its only used by alot of people as they lack an alternative. Currently I’m `working on <http://main.v00d00.net/holiday-sabayon-5-kde-4-3>`__ improving KDE4.3 experience in Sabayon, we have always shipped the excellent QtCurve Qt widgetset as a alternative to Oxygen as it very flexable, fast and can be made to look as you like, it also integrates perfectly with a GTK theme provided (no winNT style firefox!). We have, for all the KDE4 releases, shipped with the default Kwin theme due to the lack of a suitable replacement. Yesterday however, while browsing through KDE-look.org looking for a new wallpaper for my machine, I noted the \ `Aurorae Theme Engine <http://kde-look.org/content/show.php/Aurorae+Theme+Engine?content=107158>`__. This engine is designed to KDE4.3+ and uses SVGs to decorate the windows. “Yay!” was my inital thought and I immedietly installed it from the provided ebuild ( a bumped version with some cleanup is `on the sabayon overlay <http://gitweb.sabayonlinux.org/?p=overlay.git;a=commit;h=c3efbeaa1923f902fd8fb2854ac85319b21ce979>`__\ now). Work is now in progress on a theme for 5.0 for keep an eye out for 50.\_beta3 artwork. <file_sep>/content/virtualbox-3-0-0-now-available-on-sabayon-overlay.rst VirtualBox 3.0.0 Now available on Sabayon Overlay ################################################# :date: 2010-03-24 00:22 :author: v00d00 :category: Uncategorized :slug: virtualbox-3-0-0-now-available-on-sabayon-overlay :status: published ust committed the three ebuilds, the first is app-emulation/virtualbox-bin-3.0.0 and the second is app-emulation/vitualbox-modules-3.0.0 and finally app-emulation/virtualbox-guest-additions. I may add the  OSE but I haven’t seen anyone using that recently, so it got left out this time. This are in the overlay right now and support lots of cool stuff such as SMP (Multiple Virtual CPUs) to guest operating systems, plus guests are now able to access OpenGL 2.0 with hardware acceleration on supported hardware / drivers. These will hopefully be in mainline entropy after the normal testing process, if you want then now you can simply emerge them. <file_sep>/content/official-linux-licence.rst Official Linux(R) Licence ######################### :date: 2011-04-12 19:25 :author: v00d00 :category: News, Sabayon :tags: global, linux license, Linux(R), maddog :slug: official-linux-licence :status: published |Registered Trademark|\ The Sabayon Foundation has just had an official sub-license granted for our use of Linux(R) as part of "Sabayon Linux" & "SabayonLinux", covering goods and services on every corner of the planet (including Antarctica!). Linux is of course a trademark of <NAME> and the Linux Foundation can provide everyone who uses the trademark as part of their product with a license to use it in countries where it is trademarked. This is a good deal for everyone involved as it means that Company X can no go using the Linux name for crappy products and services. And so Linux(R) License No. **20110410-0332** is for Sabayon. I feel that I should mention a video by Jon "maddog" Hall, of his keynote at CeBIT earlier this year called "The Hidden Costs of Closed Source Software", the inital part of which originally raised to fact that we had not in fact registered our use of Linux! Its a very interesting video and Maddog puts his points across fairly without going to GNUCrazy... `The Hidden Costs of Closed Source Software - Jon "maddog" Hall <http://www.techcast.com/events/cebit11/mi03/>`__ .. |Registered Trademark| image:: http://v00d00.net/wp/wp-content/uploads/2011/04/reg.png :class: size-full wp-image-134 :width: 250px :height: 229px <file_sep>/content/contributing-upstream-it-will-make-or-break-linux.rst Contributing upstream, it will make or break Linux ################################################## :date: 2010-03-24 00:12 :author: v00d00 :category: Uncategorized :slug: contributing-upstream-it-will-make-or-break-linux :status: published Many fully fledges distros have drawn praise for bringing something new to the linux arena, while relying on the solid foundation of a mother distro, Mint, for example, is based on Ubuntu which is based on Debian. Sabayon is based on Gentoo; PCLinuxOS on Mandrivia so on and so forth. There has been much comment in the community about these new distros taking the mother distros work, adding to it and pushing out releases without passing those additions back to the mother distro. In many ways  this is still happening, new distros come out each and every day which is a serious misallocation of reasources, I mean seriously how many different variants do you need? Devleopers will add a few packages change the wallpaper and claim it’s a new distro, which its not, sorry, Yes im talking to you Ubuntu scientology edition et al. What I see is a worrying trend, that rather than becoming package maintainers for upstream packages developers often create small personal repos, helped in part by PPAs / overlay overuse, which means that effort gets divided and there are often duplicate packages, an older version in the main tree with its own maintainer and the newer version with more features and bug fixes in some obscure repository somewhere with a different maintainer. There were claims earlier in its history that Ubuntu was doing similar, adding custom patches and only maintaining a small subset of the overall tree, while not offering those changes upstream. Nowadays the communication is better and the Debian developers seem relatively positive about Ubuntu. Obviously we will never see the kinds of contributions that Redhat or Novell bring to linux and opensource from Ubuntu / Canocal as they have said they are not interested in doing it publically, but do the hundreds of small fixes as in their “papecuts” marketing gimmick make their way upstream? A similar thing with Sabayon was claimed in the early days there seemed to be a bit of hostility from certain members of the Gentoo community about what Sabayon was doing.  This situation has improved dramatically in recent months, communication with upstream has improved, both reporting bugs and providing patches, Gentoo devs are often seen hanging around on sabayon channels and vice versa. Lxnay, the lead developer for Sabayon is now an official Gentoo developer. Joost the Entropy maintainer is working closely with both the KDE and Gnome herds to iron out issues with the latest release of both desktop environments. The Sabayon team always desired to be working closer to upstream with the belief that together we are stronger, and that by having a more desktop and user focused Gentoo it would improve the Gentoo experience for a lot of users, and I think that extends to all of open source in general, if we all worked together in a harmonious way we could do anything, but its open source, so it will never happen, the status quo of its greatest strength and greatest weakness. <file_sep>/content/projects.rst Projects ######## :date: 2010-07-10 21:40 :author: v00d00 :slug: projects :status: published <file_sep>/content/the-joys-of-irc.rst The Joys of IRC ############### :date: 2010-03-24 00:10 :author: v00d00 :category: Uncategorized :slug: the-joys-of-irc :status: published hought I would share a little IRC session that me laugh. Oh, and if you want useful information on Sabayon 5, please see `Wolfden’s very useful planet post, inc pretty screenshots <http://wgo.wolf911.us/?p=226>`__ This is the kind of thing that you see and dont expect it to happen to you! Ahh IRC. Please join us on #sabayon on irc.freenode.net for sabayon help and to hang out with cool people like rakuen, lxnay, joost\_op, DHalens, Azerthoth, tangent, wolfden and ofcourse Thev00d00. Without further ado: :: <rakuen--> /etc/init.d/net.eth0 restart gives me error-msg: "net.eth0 has started, but is inactive" <Thev00d00> rakuen--: /etc/init.d/net.eth0 stop <Thev00d00> rakuen--: /etc/init.d/net.eth0 zap <Thev00d00> rakuen--: /etc/init.d/net.eth0 start <darthlukan> what was the live root pass again? <Thev00d00> darthlukan: on livecd "root" <dave_64> darthlukan: root <rakuen--> Thev00d00 same problem still <darthlukan> thanks <Thev00d00> rakuen--: lan or gfx? <rakuen--> "Starting ifplugd on eth0...OK, Bakcgrounding... , *WARNING: net.eth0 has started, but is inactive" <rakuen--> Thev00d00 I don't understand the question <Thev00d00> rakuen--: what lan chip have you got? <Thev00d00> rakuen--: /etc/init.d/eth0 stop <rakuen--> Thev00d00 I am not quite sure, ethernet something <Thev00d00> rakuen--: ifconfig eth0 down <Thev00d00> rakuen--: ifconfig eth0 up <Thev00d00> rakuen--: dhclient eth0 <rakuen--> ended with: NO DHCP0FERS recieved. No working leases in persistent database - sleeping. <Thev00d00> rakuen--: is it plugged in? <rakuen--> no, I am using it to this computer (...) wait a moment <Thev00d00> OMG <Thev00d00> =0 Also I love people who say “pacific” instead of “specific”. Makes me fuzzy inside. I wonder if they realise. <file_sep>/content/sabayon-5-2-to-ship-with-2-6-33-kernel-and-bfs.rst Sabayon 5.2 To Ship With 2.6.33 Kernel.. and BFS! ################################################# :date: 2010-03-24 00:11 :author: v00d00 :category: Uncategorized :slug: sabayon-5-2-to-ship-with-2-6-33-kernel-and-bfs :status: published With Sabayon fever reaching boiling point I have some cool news to break to you all, which, as you have guessed from the title is that Sabayon 5.2 will ship with 2.6.33 Kernel with\ `Con Kolivas 1 (ck1) 2.6.33 desktop performance patches <http://www.phoronix.com/scan.php?page=news_item&px=ODAxOQ>`__\ (including BFS). Sabayon has a reputation for pushing new desktop technologies into the forefront of Linux and this move will continue on that path, the announcement (`commit <http://gitweb.sabayon.org/?p=overlay.git;a=commit;h=b01340a34740f09a2f4a2ea49cda848aaa713c3c>`__) was made by our Great Leader(tm) Lxnay on the Sabayon development mailing list, as `discussed previously <http://wgo.wolf911.us/?p=317>`__ Sabayon 5.2 is in closed beta testing and scheduled for release at the end of March. <file_sep>/README.md # v00d00.github.io-src Pelican <file_sep>/content/bugs-wonderful-bugs.rst Bugs! Wonderful Bugs! ##################### :date: 2010-03-24 00:08 :author: v00d00 :category: Uncategorized :slug: bugs-wonderful-bugs :status: published The Sabayon `bugzilla <http://bugs.sabayonlinux.org/>`__ recently reached the 1000 bug milestone, note this reported bugs, currently we are running at 75 open bugs which includes bugs for every one of the thousands of entropy packages and new entropy package requests, which isn’t too bad, in my opinion at least. We have to remember that there are 3 core developers, 2 entropy maintainers and about 1o or so core staff, which is the entire Sabayon team and such our resources are not usually freely available. Anyway, when browsing the bugzilla there are a few trends I would like to comment on, firstly and the bane of Azerthoth’s existence it seems, is that every single bug needs some basic information on a selection of things that are relevant to the bug. - Hardware Issue – Dmesg, lspci or lsusb as appropriate, kernel version, entropy version. - Entropy Package Issue – Exact version number of the package, Full install log, Any error messages produced by the application when run from a command line, entropy version, branch number and Arch. - Live Disk Issues – Did you check the MD5, Did you burn slow? - Overlay/Ebuild Issue – emerge –info output, full build log, portage version. Just adding these simple bits of information makes the developers lives easier and allows the issue to get fixed quicker, so its best for everyone. Secondly then is the issue of bug naming. For example the below is very bad and well, annoying: :: mail crashed What does this tell the developers scanning through a buglist or seeing a notification email? Nothing at all about the actual issue, on the other hand a name like: :: mail-client/evolution-2.8.3-r2: crash if I close the mail window while checking for new POP mail Will definitely speed up the process and mean that it canbe put into the hands of the right people to deal with it straight away. Yay! Finally then, is the issue of user persistence. Our bugzilla has a number of open bugs that are waiting on users to come back to the developers with feedback from possible fixes, version bumps, backports, recompiles etc. The users who went to the time and effort to report the bug now seem to have disappeared completely and the bug is just left hanging  open for a while until it gets closed as invalid due to lack of user input and the issue is therefore never really resolved 100%. It is important that users stay with their issues and check it occasionally, by default bugzilla should mail you on activity on your bug so please keep an eye out for any updates. So, that was enough moaning for me for today, but please try to remember the above information, its quite simple and helps to make the process nice and simple. <file_sep>/content/sabayon-and-o2.rst Sabayon and -O2 ############### :date: 2010-03-24 00:22 :author: v00d00 :category: Uncategorized :slug: sabayon-and-o2 :status: published Well during my usual perusal of Linux based sites one particular article took my eye, it was `Linux Magazines Gentoo Optimizations Benchmarked <http://www.linux-mag.com/id/7574/1/>`__. It shows, in my opinion quite comprehensively, the advantage of a Gentoo base system with the latest kernel and I reccomend you check out the figures for yourself. The article states that big gains can be made but is it worth the time? I say no, use entropy and get the best of both worlds! Oh, you can find the entropy make.conf `on any entropy mirror <http://pkg.sabayonlinux.org/standard/sabayonlinux.org/database/x86/5/make.conf>`__, if you want to take a look at the setup we use to build entropy packages. P.S. Kororaa Linux was not the first LiveCD w/ 3D desktop effects, that would be Sabayon (ofcourse!), Chris knows this, we have emails to prove it also, so he should really change his little bio on that site. <file_sep>/content/qdbusviewer-and-integer-arrays.rst QDbusViewer and Integer Arrays ############################## :date: 2011-07-20 14:24 :author: v00d00 :category: Linux, Sabayon :tags: array, Dbus, Development, integer, qdbusviewer :slug: qdbusviewer-and-integer-arrays :status: published This post is a "things that should be easily googleable but aren't" type post. When an application is returning a dbus array of integers (Dbus type 'ai'), qdbusviewer will give you a message similar to: :: unable to find method <MethodName> on path <DbusPath> in interface <Interface> This message is sign of a failing in qdbusviewer and not in the application (as I discovered to today after a couple of hours of confusion!) The solution is to use another dbus client, for example: :: $ dbus-send --session --type=method_call --print-reply --dest=<Interface> <DbusPath> <MethodName> method return sender=:1.165 -> dest=:1.171 reply_serial=2 array [       int32 0       int32 1    ] Hopefully that will save someone some pain. <file_sep>/content/sometimes-phoronix-grinds-my-gears.rst Ubuntu 11.04 alpha 43% slower than 10.10 ######################################## :date: 2010-11-03 15:54 :author: v00d00 :category: Linux, Opinion, Sabayon :tags: KDE, kernel, opinion, phoronix :slug: sometimes-phoronix-grinds-my-gears :status: published or - Sometimes Phoronix Grinds My Gears. I don't have anything against `Phoronix <http://www.phoronix.com>`__, its a valued resource to the Linux graphics community no doubt and I'm thankful for the service it provides, sometimes - like today for example - it just makes me a little sad. The main thing that irritates me is the endless cross referencing of other posts, for example today - `KDE 4.5.3 is released <http://www.phoronix.com/scan.php?page=news_item&px=ODc1MA>`__! Yay, I heard about it from Phoronix, good job. However, the entire first paragraph is just cramming as many links to other articles that are related to KDE as possible, in this case an example is QtSceneGraph, an experimental implementation thats not even in upstream Qt yet and not at all related to KDE, also included where articles about the next major release(4.6), and the next super major release (KDE5). We know more page views means more ad revenue for Phoronix, not sure the entire back catalog of links has to be weaved into every story, why not just have "related posts" section like 90% of blogs do? Its a similar story with the kernel releases, they will link to every other story they have run about that kernel revision, often with it just linking to an index page of stories possibly related to that release, this is always early on, so you will have to read through that before the actual news, but again, they will link relating to stuff that's not even going to be in this kernel, but the next one, or the next one. And then after that we get onto the actual news item with a link to source, no problems there, very nice, good job. The second issue I have with them is the benchmarking of alpha and beta versions, its just my opinion that this is a bad practice... its not done yet! I'm sure it will be argued that it could help the project improve, but this isn't why Phoronix does it, it does it to get a nice tabloid headline eg "Ubuntu 11.04 alpha 43% slower than 10.10"  that will bring it more ad revenue. Oh and don't forget to have plug for their Phoronix Global service as often as possible. <file_sep>/content/hello-world.rst Hello world! ############ :date: 2010-03-23 21:26 :author: v00d00 :category: Uncategorized :slug: hello-world :status: published Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!
de1a75babb06a7694e254fa78b156977c01aaddc
[ "Markdown", "Python", "reStructuredText" ]
37
reStructuredText
whyman/v00d00.github.io-src
52d988542becd3a4cd3112a9830e66dc301c0abe
119478de04b544a77516a29de632e8351bd5cff3
refs/heads/master
<file_sep>from django.apps import AppConfig class RegistCenterConfig(AppConfig): name = 'regist_center' <file_sep>from django.db import models # Create your models here. class Authentic(models.Model): user_id = models.IntegerField(default=1) user_fake_id = models.IntegerField(default=1) pair_key = models.TextField() class Authentic2(models.Model): user_id = models.IntegerField(default=1) user_fake_id = models.IntegerField(default=1) pair_key = models.TextField() class Meta: app_label = 'service_02' class BaseInformation(models.Model): service_id = models.IntegerField(default=1) service_key = models.TextField(max_length=20001) tpk = models.TextField() mk = models.TextField() class Meta: app_label = 'service_01' class BaseInformation2(models.Model): service_id = models.IntegerField(default=1) service_key = models.TextField(max_length=20000) tpk = models.TextField() mk = models.TextField() class Meta: app_label = 'service_02' <file_sep># Generated by Django 2.2.6 on 2019-10-11 01:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0002_auto_20191011_0154'), ] operations = [ migrations.AlterField( model_name='authentic', name='pair_key', field=models.TextField(), ), ] <file_sep># Generated by Django 2.2.6 on 2019-10-11 01:41 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Authentic2', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('user_id', models.IntegerField(default=1)), ('user_fake_id', models.IntegerField(default=1)), ('pair_key', models.IntegerField(default=1)), ], ), migrations.CreateModel( name='BaseInformation2', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('service_id', models.IntegerField(default=1)), ('service_key', models.TextField(max_length=20000)), ('tpk', models.TextField()), ('mk', models.TextField()), ], ), ] <file_sep># CryptoBaseWeb This is the truely coding project of CryptoWeb Project link:https://github.com/Reagan1947/CryptoProject <br> Changing will first show on this rep, and I will make the well virsion on link project. <file_sep>from django.apps import AppConfig class Service02Config(AppConfig): name = 'service_02' <file_sep>from django.shortcuts import render from CryptoBaseWeb.registration_center import * from CryptoBaseWeb.mobile_user_register import * from CryptoBaseWeb.mobile_user_login import * from CryptoBaseWeb.cloud_service_provider import * import pickle # change the object register to register_init # Create your views here. def register(request): return render(request, 'register.html') def login(request): return render(request, 'login.html') def do_login(request): user_id = '' password = '' if request.method == "POST": user_id = request.POST.get('user_id') password = request.POST.get('password') mobile_login = MobileUserLogin(int(user_id), password) data_name_str = 'data' + user_id + '.pkl' with open(data_name_str, 'rb') as f: smart_car = pickle.load(f) log_in_result = mobile_login.log_in(smart_car, 1) cloudProvider = CloudServiceProvider() PK = smart_car[9] au_result = cloudProvider.authentication(log_in_result, 1, register, PK) mobile_login.monile_authentiation(au_result, smart_car, 1) return None def init(request): global register_init register_init = RegistrationCenter() register_init.initation() return render(request, 'register.html') def do_register(request): user_id = '' password = '' if request.method == "POST": user_id = request.POST.get('user_id') password = request.POST.get('password') mobile_register = MobileUserRegister(user_id, str(password)) NBPW_result = mobile_register.NBPW_gen() user_id = NBPW_result[0] NBPW = NBPW_result[1] smart_car_result = register_init.smart_car(user_id, NBPW) smart_car = mobile_register.smart_car_save(smart_car_result) data_name_str = 'data' + user_id + '.pkl' output = open(data_name_str, 'wb') pickle.dump(smart_car, output) return render(request, 'smart_car.html') <file_sep># -*-coding:utf8-*- import random class MobileUserRegister: def __init__(self, user_id, user_pw): self.user_id = user_id self.user_pw = user_pw self.rho = random.getrandbits(128) self.m = random.getrandbits(128) self.bi = 'bio' def NBPW_gen(self): NBPW = hash(str(hash(self.bi + str(self.user_id) + self.user_pw)) + str(self.rho)) NBPW_result = [self.user_id, self.m ^ NBPW] return NBPW_result def smart_car_save(self, smart_car_result): P_1 = hash(self.bi + self.user_pw) ^ self.rho P_2 = hash(str(self.rho) + self.bi + self.user_pw + str(self.user_id)) N_01 = smart_car_result[1][0][1] N_02 = smart_car_result[1][1][1] # N_01 = M_01 ^ NBPW N_dot_01 = N_01 ^ self.m N_dot_02 = N_02 ^ self.m AID_01 = smart_car_result[0] ^ hash(str(N_dot_01) + str(self.user_id)) AID_02 = smart_car_result[0] ^ hash(str(N_dot_02) + str(self.user_id)) NId_cs_01 = smart_car_result[1][0][2] NId_cs_02 = smart_car_result[1][1][2] NId_cs_01_dot = NId_cs_01 ^ hash(str(self.rho) + self.bi) NId_cs_02_dot = NId_cs_02 ^ hash(str(self.rho) + self.bi) ID_s = [1, 2] attrs_01 = smart_car_result[1][0][3] attrs_02 = smart_car_result[1][1][3] sk_01 = smart_car_result[1][0][4] sk_02 = smart_car_result[1][1][4] attrs = [attrs_01, attrs_02] sk = [sk_01, sk_02] N_dot = [N_dot_01, N_dot_02] AID = [AID_01, AID_02] NId_cs_dot = [NId_cs_01_dot, NId_cs_02_dot] pk = smart_car_result[2] smart_car = [self.bi, P_1, P_2, N_dot, AID, NId_cs_dot, ID_s, attrs, sk, pk] return smart_car <file_sep>import random from charm.toolbox.pairinggroup import PairingGroup, GT from base.models import * class CloudServiceProvider: def authentication(self, log_in_result, service_index, register, PK): service_key = '' pair_key = '' user_id = '' abe_pk = '' # data_base = 'service_0' + str(service_index) + '.db' # conn = sqlite3.connect(data_base) # c = conn.cursor() # cursor = c.execute("SELECT service_key FROM main.base_information") # for row_1 in cursor: # service_key = row_1[0] if service_index == 1: database = BaseInformation else: database = BaseInformation2 sql_result = database.objects.get(service_id=service_index) service_key = sql_result['service_key'] NId_cs = hash(str(service_index) + service_key) # XId_U_star = XId_U ^ hash(str(Tm) + str(NId_cs)) XId_U_star = log_in_result[1] Tm = log_in_result[2] XId_U = XId_U_star ^ hash(str(Tm) + str(NId_cs)) # print('XId_U is tag {}'.format(XId_U)) if service_index == 1: database_au = Authentic else: database_au = Authentic2 sql_result_2 = database_au.objects.get(user_fake_id=XId_U) user_id = sql_result_2['user_id'] pair_key = sql_result_2['pair_key'] # record = c.execute('SELECT * FROM authentica_information') for row_2 in record: user_id = row_2[0] user_fake_id = row_2[1] pair_key = row_2[2] """ here should add a select get the id and other by fake_id """ Q_ij = hash(str(hash(int(pair_key) ^ int(user_id))) + str(service_key)) Z_1 = log_in_result[0] print('user_fake_id is {}'.format(user_fake_id)) # service_index 是否str X_1 = Z_1 ^ hash(service_index) ^ Tm ^ Q_ij H_2 = hash(str(Z_1) + str(user_id) + str(Tm) + str(X_1)) H_1 = log_in_result[3] if H_1 == H_2: print('H is fine') else: print('H is bad') rand_msg = register.groupObj.random(GT) access_policy_01 = '((four or three) and (three or one))' access_policy_02 = '((four or three) and (three or one))' access_policy = [access_policy_01, access_policy_02] get_access_policy = access_policy[service_index] cpabe = register.cpabe pk = c.execute('SELECT pk FROM main.base_information') for p in pk: abe_pk = p[0] dict = eval(abe_pk) print(dict) g = dict['g'] print(g) g2 = dict['g2'] h = dict['h'] f = dict['f'] e_gg_alpha = dict['e_gg_alpha'] g = register.groupObj.deserialize(g) g2 = register.groupObj.deserialize(g2) h = register.groupObj.deserialize(h) f = register.groupObj.deserialize(f) e_gg_alpha = register.groupObj.deserialize(e_gg_alpha) abe_pk = {'g': g, 'g2': g2, 'h': h, 'f': f, 'e_gg_alpha': e_gg_alpha} # print('PK g type is {}'.format(type(PK['g']))) # print(eval(abe_pk)) # pp = eval(abe_pk) # print(type(pp.g)) # ppk = pickle.dumps(PK) # pickle.load(ppk) # print('ppk type is {}'.format(type(ppk))) ct = cpabe.encrypt(abe_pk, rand_msg, get_access_policy) RDN_j = random.getrandbits(128) Z_2 = Q_ij ^ Tm ^ RDN_j ^ user_id SKY_s_j_U_i = hash( str(user_id) + str(service_index) + str(rand_msg) + str(Q_ij) + str(X_1) + str(RDN_j) + str(Tm) + str(Tm)) print('Q_ij is {}'.format(Q_ij)) print('SKY_s_j_U_i is {}'.format(SKY_s_j_U_i)) H_3 = hash( str(user_id) + get_access_policy + str(ct) + str(Tm) + str(X_1) + str(SKY_s_j_U_i) + str(Tm) + str(RDN_j)) au_result = [Z_2, get_access_policy, ct, H_3, Tm] return au_result <file_sep># Generated by Django 2.2.6 on 2019-10-11 01:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('service_02', '0001_initial'), ] operations = [ migrations.AlterField( model_name='authentic2', name='pair_key', field=models.IntegerField(default=20000), ), ] <file_sep># -*-coding:utf8-*- import random from CryptoBaseWeb.abenc_bsw07 import * from base.models import * class RegistrationCenter: def __init__(self): self.groupObj = PairingGroup('SS512') self.cpabe = CPabe_BSW07(self.groupObj) (self.pk, self.mk) = self.cpabe.setup() def initation(self): cs_secret_key = [random.getrandbits(1024), random.getrandbits(1024)] MK = str(self.mk) service_key_01 = str(cs_secret_key[0]) service_key_02 = str(cs_secret_key[1]) g = self.groupObj.serialize(self.pk['g']) g2 = self.groupObj.serialize(self.pk['g2']) h = self.groupObj.serialize(self.pk['h']) f = self.groupObj.serialize(self.pk['f']) e_gg_alpha = self.groupObj.serialize(self.pk['e_gg_alpha']) self.PPK = {'g': g, 'g2': g2, 'h': h, 'f': f, 'e_gg_alpha': e_gg_alpha} BaseInformation.objects.create(service_id=1, service_key=service_key_01, tpk=str(self.PPK), mk=MK) BaseInformation2.objects.create(service_id=2, service_key=service_key_02, tpk=str(self.PPK), mk=MK) def smart_car(self, user_id, mNBPW): global service_key_01, service_key_02 pair_key_01 = random.getrandbits(1024) pair_key_02 = random.getrandbits(1024) # conn_01 = sqlite3.connect('service_01.db') # conn_02 = sqlite3.connect('service_02.db') # c_01 = conn_01.cursor() # c_02 = conn_02.cursor() # cursor_01 = c_01.execute("SELECT service_key from main.base_information") # for row_01 in cursor_01: # service_key_01 = row_01[0] # cursor_02 = c_02.execute("SELECT service_key from main.base_information") # for row_02 in cursor_02: # service_key_02 = row_02[0] # c_01.execute("insert into main.authentica_information(user_id, user_fake_id, pair_key) " # "values (\"{}\", \"{}\", \"{}\")".format(user_id, user_id + 200, str(pair_key_01))) # c_02.execute("insert into main.authentica_information(user_id, user_fake_id, pair_key) " # "values (\"{}\", \"{}\", \"{}\")".format(user_id, user_id + 200, str(pair_key_02))) # # conn_01.commit() # conn_02.commit() # conn_01.close() # conn_02.close() service_key_01 = BaseInformation.objects.get(service_id=1) service_key_01 = service_key_01.service_key service_key_02 = BaseInformation2.objects.get(service_id=2) service_key_02 = service_key_02.service_key user_fake_id = int(user_id) + 200 Authentic.objects.create(user_id=int(user_id), user_fake_id=user_fake_id, pair_key=str(pair_key_01)) Authentic2.objects.create(user_id=int(user_id), user_fake_id=user_fake_id, pair_key=str(pair_key_02)) M_01 = hash(str(hash(int(pair_key_01) ^ int(user_id))) + str(service_key_01)) M_02 = hash(str(hash(int(pair_key_02) ^ int(user_id))) + str(service_key_02)) N_01 = M_01 ^ mNBPW N_02 = M_02 ^ mNBPW NId_cs_01 = hash(str(1) + service_key_01) NId_cs_02 = hash(str(2) + service_key_02) # user temple_id ############################################## temple_user_id = int(user_id) + 200 # attrs_01 = ['ONE', 'TWO', 'THREE'] attrs_02 = ['ONE', 'TWO', 'THREE'] sk_01 = self.cpabe.keygen(self.pk, self.mk, attrs_01) sk_02 = self.cpabe.keygen(self.pk, self.mk, attrs_02) sk_01 = RegistrationCenter.serialization(self, sk_01) sk_02 = RegistrationCenter.serialization(self, sk_02) service_result_01 = [1, N_01, NId_cs_01, attrs_01, sk_01] service_result_02 = [2, N_02, NId_cs_02, attrs_02, sk_02] sr = [service_result_01, service_result_02] smart_car_result = [temple_user_id, sr, self.PPK] return smart_car_result # base information # service id, service_key , master_key, master_public_key # def sezerlize(self, aim_dict): # for index in aim_dict: # temple = aim_dict[index] # print(type(temple)) # aim_dict[index] = self.groupObj.serialize(temple) # print(aim_dict) # return aim_dict def serialization(self, original_sk): # groupObj = PairingGroup('SS512') # temple D = original_sk['D'] Dj = original_sk['Dj'] Djp = original_sk['Djp'] S = original_sk['S'] # serialization D D = self.groupObj.serialize(D) # serialization Dj Dj_ONE = Dj['ONE'] Dj_TWO = Dj['TWO'] Dj_THREE = Dj['THREE'] Dj_ONE = self.groupObj.serialize(Dj_ONE) Dj_TWO = self.groupObj.serialize(Dj_TWO) Dj_THREE = self.groupObj.serialize(Dj_THREE) Dj = {'ONE': Dj_ONE, 'TWO': Dj_TWO, 'THREE': Dj_THREE} # serialization Djp Djp_ONE = Djp['ONE'] Djp_TWO = Djp['TWO'] Djp_THREE = Djp['THREE'] Djp_ONE = self.groupObj.serialize(Djp_ONE) Djp_TWO = self.groupObj.serialize(Djp_TWO) Djp_THREE = self.groupObj.serialize(Djp_THREE) Djp = {'ONE': Djp_ONE, 'TWO': Djp_TWO, 'THREE': Djp_THREE} # s is list return {'D': D, 'Dj': Dj, 'Djp': Djp, 'S': S}
a84ee547ad30c8ba9b8bb651eb98b332f71e58b7
[ "Markdown", "Python" ]
11
Python
Reagan1947/CryptoBaseWeb
fd070110eb682c98d76a2900e080bd9725075127
e54756f666d4530d288ca2c389b0b1e410329292
refs/heads/master
<file_sep>def method_name(params1) params1 end puts method_name(1) # NB : la factorielle de 8, notée 8 !, vaut # 1 x 2 x 3 x 4 x 5 x 6 x 7 x 8 # factorielle_number = 8 # i = 0 # array = [] # while i < factorielle_number # i += 1 # array << i # end # p array[0]*array[1]*array[2]*array[3]*array[4]*array[5]*array[6]*array[7] # -------------------------- # Ecrire un algorithme qui demande un nombre de départ, # et qui calcule la somme des entiers jusqu’à ce nombre. # Par exemple, si l’on entre 5, le programme doit calculer : # 1 + 2 + 3 + 4 + 5 = 15 # NB : on souhaite afficher uniquement le résultat, pas la décomposition du calcul. # number_start = 5 # init = 0 # array = [] # while init != number_start # array << init # init += 1 # end # p array.sum # number_start = 5 # i = 0 # array = [] # while i < number_start # i += 1 # array << i # end # puts array.sum # -------------------------- # Ecrire un algorithme qui demande un nombre de départ, # et qui ensuite écrit la table de multiplication de ce nombre, présentée comme suit (cas où l'utilisateur entre le nombre 7) : # i = 1 # while i <= 10 # puts "> Entrez un nombre :" # user_number = gets.chomp.to_i # puts " #{user_number} x #{i} = #{user_number * i}" # i += 1 # end # Table de 7 : # 7 x 1 = 7 # 7 x 2 = 14 # 7 x 3 = 21 # … # 7 x 10 = 70 # -------------------------- <file_sep># Ecrire un programme qui renvoie "Je n'ai pas faim" tant qu'il n'est pas = 12 # Afficher de 8h à 12h hungry = 8 hour_start = 12 while hungry <= hour_start if hungry != hour_start puts "> A #{hungry} H: Je n'ai pas faim" else hour_start puts "> A #{hungry} H: j'ai faim" end hungry += 1 end <file_sep># => Tous les exos avec des boucles + conditions si besoin # Exo 1 # Afficher la liste des élèves # Exo 1.1 # On a un certain nombre d'élèves. # On veut afficher si un élève à eu l'année ou pas. # Exo 1.2 # On veut afficher la somme des notes des élèves. # On veut afficher la moyenne # Exo 2 # Ecrire un programme qui demande à l'utilisisateur un nombre compirs entre 1 et 10. # On va demander au uqser de tirer un chiffre. # Si le chiffre correspond au chiffre du croupier, on affiche le message : "You win!" <file_sep>class Controller require_relative "task" def initialize(repository, view) @repository = repository # INJECTION DE DEPENDANCE @view = view end # ACTIONS UTILISATEURS def display_all_tasks # 1 - Demander eu repo la liste des taches tasks = @repository.all # 2 - Donner a view liste des taches pour afficher @view.display_tasks(tasks) end def add_task # 1 - Vue : Demande au user Description description = @view.ask_for_user_description # 2 - Creer une nouvelle tache task = Task.new(description) # 3 - Ajouter tache dans repo @repository.add(task) end def mark_task_as_done # 1 - Vue: demander au user l'index de la tahce à marquer task_id = @view.ask_user_for_task_id # 2 - Demander au repo la tache en question task = @repository.find(task_id) # 3 - marquer les tache comme faite task.mark_task_as_done end # def destroy_task # end end <file_sep>words = %w(dog data ask my win two beer as) size = 3 def size_splitter(array, size) # TODO: Return an array of two arrays, the first containing # words of length `size`, the second containing all the other words # In addition to this split, each array should be *sorted*. array_one = array.select do |word| word.length == size end array_two = array.reject do |word| word.length == size end return array_one, array_two end p size_splitter(words, size) # def block_splitter(array) # # TODO: Return an array of two arrays, the first containing # # elements for which the given block yields true, # # the second containing all the other elements. # # No sort needed this time. # end <file_sep>team_members = ['Chomp', 'Omar', 'Romain'] def team_count(team_members) # TODO: Return the number of elements in the `team_members` array team_members.count end puts team_count(team_members) <file_sep>class Restaurant attr_accessor :name, :city def initialize(name, city) @name, @city = name, city end end class FastFood < Restaurant attr_accessor :preparation_time def initialize(name, city, preparation_time) super(name, city) @preparation_time = preparation_time end def name return "FastFood: #{@name.capitalize}" end end class Gastronomic < Restaurant def initialize(name, city, stars) @name, @city, @stars = name, city, stars end end mcdonald = FastFood.new("McDo", "Paris", 10) puts "#{mcdonald.name} => #{mcdonald.preparation_time}" <file_sep>require_relative "vending_machine" def display(vending_machine) return "---> Amount: #{vending_machine.user_balance_cents / 100.0}€" \ " - 1 Snack = #{vending_machine.snack_price_cents / 100.0}€" \ " - Stock: #{vending_machine.snack_count}" end # We instantiate a new vending machine selling 2.5 euros snacks. In the beginning # this machine has a stock of 10 snacks. vending_machine = VendingMachine.new(250, 10) puts "Vending machine ready!" puts display(vending_machine) # A client comes and inserts some coins puts "Inserting 2€" vending_machine.insert_coin(200) puts display(vending_machine) 3.times do puts "Inserting 0.2€" vending_machine.insert_coin(20) puts display(vending_machine) end # Then the client pushes the Buy snack button puts "Pushing 'Buy Snack' button" vending_machine.buy_snack puts display(vending_machine) # Then the client pushes the Buy snack button again (but forgot to insert some more coins!) puts "Pushing 'Buy Snack' button" vending_machine.buy_snack puts display(vending_machine) <file_sep># Ecrire un algorithme qui demande un nombre compris entre 10 et 20, jusqu’à ce que la # réponse convienne. En cas de réponse supérieure à 20, on fera apparaître un message : « Plus # petit ! », et inversement, « Plus grand ! » si le nombre est inférieur à 10. machine = rand(10..20) user = 0 puts "Choisissez un chiffre :" while user != machine user = gets.chomp.to_i if user == machine puts "Bien joué !" elsif user < machine puts "Plus grand !" elsif user > machine puts "Plus petit !" end end <file_sep>def burger(patty, sauce, topping) # returns the burger as an array of strings cooked = block_given? ? yield(patty) : patty ["bread", "#{cooked}", "#{sauce}", "#{topping}", "bread"] end <file_sep>require_relative "car" white_car = Car.new p white_car red_car = Car.new("red") p red_car green_car = Car.new("green" ) p green_car <file_sep>class Router def initialize(controller) @controller = controller end def start loop do print_menu action = gets.chomp.to_i case action when 1 then @controller.display_all_tasks when 2 then @controller.add_task when 3 then @controller.mark_task_as_done else puts "Wrong number" end end end private def print_menu puts "What next?" puts "1. Liste tasks" puts "2. Add task" puts "3. Mark task as done" end end <file_sep>def horse_racing_format!(race_array) # TODO: modify the given array so that it is horse racing consistent. This method should return nil. horse_count = 0 array =[] while horse_count < race_array.size array << "#{horse_count + 1}-#{race_array[horse_count]}!" horse_count += 1 end puts array.reverse! end horse_racing_format!(["Abricot du Laudot", "Black Caviar", "<NAME>", "Coup de Folie"]) <file_sep># You are about to leave Singapore and have some money left # over. # The exchange rate is 100 SIDs = 37 GBP. sids = 100.00 pounds = 37 sids_dizaine = 10 teapot = 75 # a) Produce a table for 10, 20, 30 ... 100 sids showing # what you would get back in pounds while sids_dizaine <= sids puts "Conversion" puts "#{sids_dizaine} sids = #{(sids_dizaine * pounds)/sids} pounds" if sids_dizaine <= teapot puts "=> you can't afford it" else # puts "=> you can afford it and that would leave you with #{(sids_dizaine * (sids_dizaine - teapot)) / pounds} pounds after the conversion back" result_sids = sids_dizaine - teapot puts "=> you can afford it and that would leave you with #{(result_sids * pounds)/sids} pounds after the conversion back" end puts "---------" p "---------" sids_dizaine += 10 end # -------------- # b) You see a teapot for sale at the airport shop for 75 SIDS. # Add extra info to each line of your earlier answer - "you # can't afford it" or "you can afford it and that would leave # you with xxxxxxxx pounds after the conversion back" # Constant Erate (so WILL be available in method ;-) <file_sep># rubocop:disable Metrics/LineLength require_relative 'orange_tree' require_relative 'helpers' orange_tree = OrangeTree.new is_dead = orange_tree.dead? until is_dead orange_tree.one_year_passes! print "One year passes!" sleep(0.1) print "." sleep(0.05) print "." sleep(0.05) puts "." sleep(0.05) is_dead = orange_tree.dead? if is_dead puts "Your orange tree is dead :(" else puts "Your orange tree is #{pluralize(orange_tree.age, 'year')} old, measures #{pluralize(orange_tree.height, 'meter')}, gives #{pluralize(orange_tree.fruits, 'fruit')}, and is still alive :)" end sleep(0.1) puts "" end # rubocop:enable Metrics/LineLength <file_sep>class Restaurant attr_accessor :name def initialize(country, price, name) @country = country @price = price @name = name end def opening? @opening = true end end <file_sep>require_relative "object_exemples" lewagon_lyon = Lewagon.new('lewagon', "20 rue des Capucins", 3) loop do puts "What is the name of the student?" print "> " student = gets.chomp lewagon_lyon.new_students(student) puts "--------------------------------" p lewagon_lyon puts "--------------------------------" end <file_sep>require_relative "vending_machine" p vending_machine = VendingMachine.new(100, 10) p vending_machine.insert_coin(20) p vending_machine.insert_coin(30) p vending_machine.buy_snack p vending_machine <file_sep> # Encapsulation class SportsCar def start start_engine_pump init_spark_plug end private def start_engine_pump puts "Starting engine pump" end def init_spark_plug puts "Initialize spark plug" end end <file_sep># DECLARATION DE VARIABLES................................................................................ groups = [ ['Romain', 'Loic', 'Adelaid', 'David'], ['Jeanro', 'Caroline', 'Jules', 'Mathieu'], ['Eduina', 'Alexander', 'Anton'], ['Funny', 'Hugo', 'Nour', 'Emma'], ['Nelson', 'Jerimy', 'Yoann', 'Omar'] ] project_name = ['Ride On Time', 'Ibreath', 'My Level Language Learning', 'The good wayste', 'EasyCheck'] # FIN de declaration de variables......................................................................... # INITIALISER LA VARIABLE i = 0 i = 0 # INITIALISER LA VARIABLE y = 0 y = 0 # FIN initialisation de variables......................................................................... # DEBUT DE LA BOUCLE WHILE PARENTE........................................................................ # TANT QUE i EST INFERIEUR A array.size ALORS............................................................ while i < groups.size # DEBUT DE CONDITION.......................... # SI i EXISTE ALORS if i # AFFICHER LE NOM DU PROJET EN MAJUSCULE QUI CORRESPOND AU GROUPE EN UTILISATION L'INTERPOLATION e.g puts "#{projet_name[i].upcase}" p "#{project_name[i].upcase}" # FIN DE CONDITION............................ end # AFFICHER array de [i] p groups[i] # AFFICHER "------------------------------" p "------------------------------" # DEBUT DE LA BOUCLE ENFANT............................................................................. # TANT QUE y EST INFERIEUR A array[i].size ALORS while y < groups[i].size # AFFICHER array[i][y] p groups[i][y] # INCREMENTER LA VALEUR DE y par 1 y += 1 # FIND DE LA BOUCLE ENFANT.............................................................................. end # REINITIALISER LA VALEUR DE y a 0 y = 0 # INCREMENTER LA VALEUR DE i par 1 i += 1 # FIN DE LA BOUCLE WHILE PARENTE........................................................................ end <file_sep>def array_to_hash(array) # TODO: implement the method :) hash = {} array.each_with_index do |name, index| key = if block_given? yield(index) else index.to_s end hash[key] = name end hash end hash_bis = array_to_hash(["Omar", "Loic", "Gitanos"]) do |index| "key#{index}" end p hash_bis <file_sep># Ecrire un algorithme qui demande un nombre de départ, # et qui ensuite affiche les dix nombres suivants. # Par exemple, si l'utilisateur entre le nombre 17, # le programme affichera les nombres de 18 à 27. puts "Entrez un nombre de départ : " user_number = gets.chomp.to_i max_number = user_number + 10 while user_number < max_number p user_number += 1 end <file_sep># Bootstrap require_relative "repository" require_relative "view" require_relative "controller" require_relative "router" repository = Repository.new view = View.new controller = Controller.new(repository, view) router = Router.new(controller) router.start <file_sep>class Restaurant attr_reader :city, :clients attr_accessor :capacity def initialize(name, city, capacity, category) @name = name @city = city @capacity = capacity @category = category @clients = [] end def add_reservation(name) @clients << name end def print_reservations @clients.each_with_index do|client, index| puts "Client ##{index + 1} => #{client}" end end end cerises = Restaurant.new("Temps des Cerises", "Paris", 30, "francais") p cerises.city cerises.capacity += 10 p cerises.capacity cerises.add_reservation("Mathilde") cerises.add_reservation("Claire") cerises.print_reservations <file_sep>require_relative "vending_machine" def display(vending_machine) return "---> Amount: #{vending_machine.user_balance_cents / 100.0}€" \ " - 1 Snack = #{vending_machine.snack_price_cents / 100.0}€" \ " - Stock: #{vending_machine.snack_count}" end # We instantiate an **empty** vending machine selling 2.5 euros snacks. vending_machine = VendingMachine.new(250, 0) puts "Vending machine ready!" puts display(vending_machine) # A technician comes and refill the vending machine with 20 snacks. puts "Technician filling machine with 20 snacks" vending_machine.snack_count = vending_machine.snack_count + 20 puts display(vending_machine) <file_sep>DISHES_CALORIES = { "Hamburger" => 250, "Cheese Burger" => 300, "Big Mac" => 540, "McChicken" => 350, "French Fries" => 230, "Salad" => 15, "Coca Cola" => 150, "Sprite" => 150 } MEALS = { "Happy Meal" => ["Cheese Burger", "French Fries", "Coca Cola"], "Best Of Big Mac" => ["Big Mac", "French Fries", "Coca Cola"], "Best Of McChicken" => ["McChicken", "Salad", "Sprite"] } def poor_calories_counter(burger, side, beverage) DISHES_CALORIES[burger] + DISHES_CALORIES[side] + DISHES_CALORIES[beverage] end def calories_counter(orders) # TODO: return number of calories for a less constrained order total = 0 orders.each do |order| if DISHES_CALORIES.key?(order) total += DISHES_CALORIES[order] else total += poor_calories_counter(MEALS[order][0], MEALS[order][1], MEALS[order][2]) end end return total end orders = ["Happy Meal", "French Fries", "Coca Cola"] puts calories_counter(orders) <file_sep>def sum_odd_indexed(array) # TODO: computes the sum of elements at odd indexes (1, 3, 5, 7, etc.) # You should use Enumerable#each_with_index numbers_2 = [] array.each_with_index do |number, index| numbers_2 << number if index.odd? end numbers_2.sum end def even_numbers(array) # TODO: Return the even numbers from a list of integers. # You should use Enumerable#select array.select do |number| array.even? end end def short_words(array, max_length) # TODO: Take an array of words, return the array of words not exceeding max_length characters # You should use Enumerable#reject array.reject do |word| word.length > max_length end end def first_under(array, limit) # TODO: Return the first number from an array that is less than limit. # You should use Enumerable#find array.find do |number| number < limit end end def add_bang(array) # TODO: Take an array of strings and return a new array with "!" appended to each string. # You should use Enumerable#map array.map do |word| "#{word}!" end end def concatenate(array) # TODO: Concatenate all strings given in the array. # You should use of Enumerable#reduce array.reduce do |word, index| word + ", " +index end end words = ["titi", "toto", "tata", "tutu", "tete", "tjtj"] def sorted_pairs(array) array_words = [] # TODO: Reorganize an array into slices of 2 elements, and sort each slice alphabetically. # You should use of Enumerable#each_slice array.each_slice(2) do |word| array_words << word.sort end array_words end p sorted_pairs(words) <file_sep># On a une liste de 4 élèves et on veut affciher si l'élève à + 10 = année validé # si - 10 = Tu refaits ton année notes = [11, 12, 13, 4] students_name = ["romain", "loic", "omar", "gitanos"] validation = 10 students = 0 while students <= 3 if notes[students] >= validation puts "#{students_name[students]}, tu as eu #{notes[students]} => T'es un bon!" else puts "#{students_name[students]}, tu as eu #{notes[students]} => Je veux savoir comment m'améliorer en tant qu'homme" end students += 1 end # On a 10 pommes et on veut afficher à chaque -2 on affiche la phrase il me reste # pommes = 10 while pommes >= 1 if pommes.odd? puts pommes else puts "Il me reste #{pommes} pommes" end pommes -= 1 end # boucle à l'infine while true puts "Hello" end # Arreter la boucle en la passant à false while true puts "Hello" return false end # # Afficher une boucel 9 fois compteur = 1 while compteur <= 9 puts "Hello" compteur += 1 end # Afficher les chiffres de 8 à 1 compteur = 8 while compteur >= 1 puts compteur compteur -= 1 end <file_sep>values = [ ["I", 1], ["V", 5], ["X", 10], ["L", 50], ["C", 100], ["D", 500], ["M", 1000] ] def old_roman_numeral(an_integer) # TODO: translate integer in roman number - old-style way roman = "" numeral = 0 while numeral > 0 end end if end # def new_roman_numeral(an_integer) # # TODO: translate integer in roman number - modern-style way # end <file_sep>require 'csv' file_path = 'movies.csv' def most_successful(number, max_year, file_path) movies = [] CSV.foreach(file_path) do |row| puts row if row[1].to_i <= max_year p movies << row[1] end end end most_successful(6, 1999, file_path) <file_sep>class Car # attr_reader + attr_writer attr_accessor :color # Car.new => appelle initialize # Contructor def initialize(color = "white") # Definir les variables d'instances @engine_started = false @color = color end # def color # return @color # end def paint(color) @color = color end def start_engine @start_engine = true end def stop_engine @stop_engine = false end end <file_sep>#Ecrire un algorithme qui demande à l’utilisateur un nombre compris entre 1 et 3 jusqu’à ce #que la réponse convienne. # Variable N en Entier machine = rand(1..3) user = 0 puts "Entrez un nombre ente 1 et 3" while user != machine user = gets.chomp.to_i if user != machine puts "Désolé, recommencez" else puts "Bien joué !" end end <file_sep>class View def display_tasks(tasks) puts "-------------------------------" tasks.each_with_index do |task, index| status = task.done? ? "[x]" : "[ ]" puts "#{index + 1}. #{status} #{task.description}" end puts "-------------------------------" end def ask_for_user_description puts "What do you want to do?" print "> " return gets.chomp end def ask_user_for_task_id puts "Which task do you want to mark as done?" print "> " gets.chomp.to_i - 1 end end <file_sep>class OrangeTree # TODO: Implement all the specs defined in the README.md :) attr_accessor :age, :height, :fruits, :dead def initializer @age = 0 @height = 0 @fruits = 0 @dead = false end def one_year_passes! @age += 1 if @age < 101 @height += 1 end if @age < 11 update_fruits end end def dead? age_rand = rand(@age..100) if @age > 50 && @age == age_rand return @dead = true end end def pick_a_fruit! @fruits -= 1 if @fruits.positive? end def update_fruits if @age < 5 @fruits = 0 elsif @age >= 6 && @age < 10 @fruits = 100 elsif @age >= 10 && @age < 15 @fruits = 200 else @fruits = 0 end end end <file_sep>require_relative "burger_restaurant" puts "💬 I'd like a burger with a bigger portion of fish, plus mayo and salad please." # TODO: to upgrade a portion to a bigger one, transform the fish to uppercase bigger_burger = burger("fish", "mayo", "salad") do |cooked| "#{cooked.upcase!}" end p bigger_burger puts "💬 I'd like a juicy steak with barbecue sauce and cheddar please." # TODO: to make a juicy steak, replace any vowel by the sign "~" juicy_burger = burger("steak", "barbecue", "cheddar") do |replace| "#{replace.gsub(/[aeiou]/, '~')}" end p juicy_burger puts "💬 I'd like a spicy chicken with ketchup and cheddar please." # TODO: to make a spicy portion, add the sign "*" before and after the string spicy_burger = burger("chicken", "ketchup", "cheddar") do |cooked| "*#{cooked}*" end p spicy_burger # DO NOT remove this line, written for testing purpose @variables = Hash[local_variables.collect { |v| [v, binding.local_variable_get(v)] }] <file_sep>def tag(name, content, attributes = ) return "<#{name}>#{content}</#{name}>" end puts tag("h1", "Hello") # => <h1>Hello</h1> tag("h1", "Hello world") # => <h1>Hello world</h1> tag("h1", "Hello world", { class: "bold" }) # => <h1 class='bold'>Hello world</h1> tag("a", "Le Wagon", { href: "http://lewagon.org", class: "btn" }) # => <a href='http://lewagon.org' class='btn'>Le Wagon</a> <file_sep>class Repository def initialize @tasks = [] end def add(task) @tasks << task end def find(id) @task[id] end def delete(task) @task.delete(task) end def all @tasks end end <file_sep>def tag(tag_name, attributes = nil) # TODO: Build HTML tags around content given in the block # The method can be called with an optional HTML attribute inputted as [attr_name, attr_value] attr_name = if attributes.nil? nil else attributes.first end attr_value = if attributes.nil? nil else attributes.last end title = if block_given? yield(tag_name) else "<h1>Google it</h1>" end html_content = "<#{tag_name} #{attr_name}='#{attr_value}'>#{title}</#{tag_name}>" end # => '<a href="www.google.com"><h1>Google it</h1></a>' html = tag("h1") do |title, second| "<#{title}>Some Title</#{title}>" end p html www = tag("a", ["href", "www.google.com"]) p www <file_sep>def refrain(lyrics, number_of_times = 10, vibrato = 0, strong = false) song_refrain = [] lyrics += lyrics[lyrics.size - 1] * vibrato lyrics.upcase! if strong number_of_times.times do song_refrain << lyrics end song_refrain.join(" ") end puts refrain("hey ya") def better_refrain(lyrics, options = { vibrato: 0, number_of_times: 10, strong: false }) # TODO: implement this better version which breaks argument order dependency song_refrain =[] lyrics += lyrics[lyrics.size - 1] * options[:vibrato] lyrics.upcase! if options[:strong] options[:number_of_times].times do song_refrain << lyrics end song_refrain.join(" ") end puts better_refrain("hey ya") <file_sep>class VendingMachine # TODO: add relevant getter/setter to this class to make the scenarios work properly. attr_reader :user_balance_cents, :snack_price_cents attr_accessor :snack_count def initialize(snack_price_cents, snack_count) @user_balance_cents = 0 @snack_count = snack_count @snack_price_cents = snack_price_cents end def insert_coin(input_cents) # TODO: what happens to @snack_count, @user_balance_cents and @snack_price_cents # when the user inserts a coin? @user_balance_cents += input_cents end def buy_snack # TODO: what happens to @snack_count, @user_balance_cents and @snack_price_cents # when the user pushes a button to buy a Snack? if @user_balance_cents >= @snack_price_cents && snack_count > 0 @user_balance_cents -= @snack_price_cents @snack_count -= 1 else puts "Not enough money or no snack in V.M" end @snack_count @user_balance_cents end end <file_sep>class Lewagon def initialize(name, address, capacity = 30) @name = name @address = address @capacity = capacity @students = [] end def full @capacity end def new_students(student) if @students.size + 1 > full puts "Vous avez dépassé la capacité" raise ExceptionError, " " else @students << student end end end <file_sep>CALORIES = { "Hamburger" => 250, "Cheese Burger" => 300, "Big Mac" => 540, "McChicken" => 350, "French Fries" => 230, "Salad" => 15, "Coca Cola" => 150, "Sprite" => 150 } def poor_calories_counter(burger, side, beverage) # TODO: return number of calories for this mcDonald order CALORIES[burger]+CALORIES[side]+CALORIES[beverage] # burger + side + beverage end puts poor_calories_counter("Big Mac", "Salad", "Coca Cola") <file_sep>require 'open-uri' require 'json' def generate_grid(grid_size) # TODO: generate random grid of letters ('A'..'Z').to_a.sample(grid_size) end grid = generate_grid(9) p grid puts "What's you word?" print "> " word = gets.chomp def parsing(word) url = "https://wagon-dictionary.herokuapp.com/#{word}" user_word = open(url).read user = JSON.parse(user_word) # {"found"=>true, "word"=>" ", "length"=>5} user["found"] end parsing(word) def include?(word, grid) word.chars.all? { |letter| word.count(letter) <= grid.count(letter)} end include?(word, grid) def game_rule(word, grid) if include?(word, grid) == true && parsing(word) == true p "You Win!" elsif include?(word, grid) == false && parsing(word) == true p "You word doesn't match with the grid" elsif parsing(word) == false && include?(word, grid) == true p "Word doesn't exist" else p "You loose" end end game_rule(word, grid) <file_sep>class Chief attr_accessor :name, :years def intialize(name, years, restaurant) @name, @years = name, years @restaurant = restaurant end end class Restaurant attr_accessor :name, :city, :clients, :chief def intialize(name, city, chief_name, chief_years) @name, @city = name, city @clients = [] @chief = Chief.new(chief_name, chief_years, self) end def print_clients @clients.each_with_index do |client, index| puts "Client ##{index + 1} => #{client}" end end end bristol = Restaurant.new("Le Bristol", "Paris", "Frechont", 20) frechont = bristol.chief puts "Le chef du #{frechont.restaurant.name} est #{frechont.name}" puts "Il a #{frechont.years} ans de métier." <file_sep>require nokogiri require json puts Time.now puts Nokogiri::html::document.parse("<h1>Hello guys</h1>") # JSON.parse('{"key": "value", "other_key": "other_value"}') <file_sep>require_relative "restaurant" italian_restaurant = Restaurant.new("Italian", "cheap", "Italofood") french_restaurant = Restaurant.new("French", "expensive", "Bouchon") greek_restaurant = Restaurant.new("Spain", "cheap", "Tortilla") italian_restaurant.opening? p italian_restaurant p french_restaurant p greek_restaurant p french_restaurant.name p italian_restaurant.name = "Foufoune" <file_sep>def pluralize(integer, string) if integer == 1 "#{integer} #{string}" else "#{integer} #{string}s" end end <file_sep>require_relative "task" require_relative "repository" require_relative "controller" require_relative "view" repo = Repository.new task1 = Task.new("course") task2 = Task.new("menage") # SCENARIO UTILISATEUR # 1.afficher les taches controller = Controller.new(repo, View.new) controller.display_all_tasks # 2.ajouter une tache controller.add_task # 3.afficher à nouveau les atches controller.display_all_tasks # 4.marquer une tache comme faite controller.mark_task_as_done # 5.afficher à nouveau les taches controller.display_all_tasks
096371f5b17dc2d9509047483fb4afda5b75e9c9
[ "Ruby" ]
48
Ruby
Romai558/reboot
806fba9f2c375046beb886ed385c7684d9b13cac
175148bf1afb0ae7090ac5617a2057894b6979c8
refs/heads/master
<file_sep><?php include '../view/header.php'; require __DIR__ . '/../users/users.php'; if (!isset($_GET['id'])) { include "../view/not_found.php"; exit; } $userId = $_GET['id']; $user = getUserById($userId); if (!$user) { include "../view/not_found.php"; exit; } ?> <div class="container"> <div class="card"> <div class="card-body"> <form style="display: inline-block" method="POST" action="submit.php"> <input name="name" value="<?php echo $user['name'] ?>"> <input type="<PASSWORD>" name="password" value="<?php echo $user['<PASSWORD>'] ?>"> <a href="submit.php?id=<?php echo $user['id'] ?>" class="btn btn-secondary">Login</a> </form> </div> </div> </div><file_sep><?php include '../view/header.php'; require __DIR__ . '/../users/users.php'; if (!isset($_GET['id'])) { include "../view/not_found.php"; exit; } $userId = $_GET['id']; $user = getUserById($userId); if (!$user) { include "../view/not_found.php"; exit; } $errors = [ 'name' => "", 'username' => "", 'password' => "", 'email' => "", 'phone' => "", 'website' => "", ]; if ($_SERVER['REQUEST_METHOD'] === 'POST') { $user = array_merge($user, $_POST); $isValid = validateUser($user, $errors); if ($isValid) { $user = updateUser($_POST, $userId); header("Location: ../index.php"); } } ?> <div class="container"> <div class="card"> <div class="card-header"> <h3> <?php if ($user['id']): ?> Update user <b><?php echo $user['name'] ?></b> <?php else: ?> Create new User <?php endif ?> </h3> </div> <div class="card-body"> <form method="POST" enctype="multipart/form-data" action=""> <div class="form-group"> <label>Name</label> <input name="name" value="<?php echo $user['name'] ?>" class="form-control <?php echo $errors['name'] ? 'is-invalid' : '' ?>"> <div class="invalid-feedback"> <?php echo $errors['name'] ?> </div> </div> <div class="form-group"> <label>Username</label> <input name="username" value="<?php echo $user['username'] ?>" class="form-control <?php echo $errors['username'] ? 'is-invalid' : '' ?>"> <div class="invalid-feedback"> <?php echo $errors['username'] ?> </div> </div> <div class="form-group"> <label>Phone</label> <input name="phone" value="<?php echo $user['phone'] ?>" class="form-control <?php echo $errors['phone'] ? 'is-invalid' : '' ?>"> <div class="invalid-feedback"> <?php echo $errors['phone'] ?> </div> </div> <div class="form-group"> <label>Website</label> <input name="website" value="<?php echo $user['website'] ?>" class="form-control <?php echo $errors['website'] ? 'is-invalid' : '' ?>"> <div class="invalid-feedback"> <?php echo $errors['website'] ?> </div> </div> <button class="btn btn-success">Submit</button> </form> </div> </div> </div> <file_sep><?php use source\H1\Request; use source\H1\Response; use source\H2\Router; require 'users/users.php'; spl_autoload_register(function($class) { $path = str_replace('\\', '/', $class.'.php'); if (file_exists($path)) { require $path; } }); $users = getUsers(); $router = new Router(new Request); $router->get('/new', 'main'); ?> <div class="container"> <table class="table"> <tbody> <?php foreach ($users as $user): ?> <tr> <td><?php echo $user['name'] ?></td> <td><?php echo $user['email'] ?></td> <td> <a href="operators/login.php?id=<?php echo $user['id'] ?>" class="btn btn-sm btn-outline-info">Login</a> </td> </tr> <?php endforeach;; ?> </tbody> </table> </div><file_sep><?php require_once __DIR__ . '/users/users.php'; $users = getUsers(); ?> {header} <div class="container"> <p> <a class="btn btn-success" href="operators/create.php">Create new User</a> </p> <table class="table"> <thead> <tr> <th>Name</th> <th>Email</th> </tr> </thead> </table> </div>
9c8ee2b87c89fbb48cc72be8bc2b0c254743659c
[ "PHP" ]
4
PHP
Tamta99/Homework-5
36833b35641728a418aaab3675764872c26dde71
cd274eafa0e806e1899b818e1d722e7bb2ce3f2e
refs/heads/master
<file_sep># get-reddit-saveds This is a very simple script type application that gets a user's latest saved posts from Reddit. By default, it tries to save 1,000 posts to output.json in the same directory as the executable. This is an okay example of how to start messing around with the Reddit api using Go! ## How to Use This depends on Reddit's API. As such, you need to create a Reddit app. You can find the instructions on how to do that [here](https://github.com/reddit-archive/reddit/wiki/OAuth2-Quick-Start-Example). Once you have all that information, you really only have to build the executable and run it. You can accomplish that by running `go run .` in the same directory as the main.go file. ## Options You can change the constants in the source code to accomplish different behaviors. `limit` controls how many posts are requested, and `settings` and `output` can change where those respective files are looked for/created. You can put a settings.json file in your directory so that you don't have to specify your credentials every time you want to use this script. I created this part of the script mainly to make my own development easier. I really don't recommend that you store your passwords/secrets in plain text on your computer; it's just a convenience feature. <file_sep>package main import ( "encoding/json" "fmt" "io" "io/ioutil" "log" "net/http" "net/url" "os" "strings" "time" ) const ( tokenAPIURL = "https://www.reddit.com/api/v1/access_token" savedsAPIURL = "https://oauth.reddit.com/user/%s/saved" userAgentTemplate = "desktop:saveds-downloader:v0.0.1 (by /u/%s)" settings = "settings.json" output = "output.json" limit = "1000" ) var ( client = &http.Client{Timeout: time.Second * 10} userAgent = "" ) type apiLogin struct { Username string Password string ClientID string ClientSecret string } func must(err error) { if err != nil { log.Panic(err) } } func requestToken(config apiLogin) string { form := url.Values{} form.Set("grant_type", "password") form.Set("username", config.Username) form.Set("password", config.Password) formStr := form.Encode() // ? how are these errors handled in prod? request, err := http.NewRequest("POST", tokenAPIURL, strings.NewReader(formStr)) must(err) request.SetBasicAuth(config.ClientID, config.ClientSecret) request.Header.Set("User-Agent", userAgent) request.Header.Add("Content-Type", "application/x-www-form-urlencoded") request.Header.Add("Content-Length", fmt.Sprintf("%d", len(formStr))) response, err := client.Do(request) must(err) defer response.Body.Close() if response.StatusCode != 200 { log.Panicf(`Error "%s" received from Reddit`, response.Status) } body, err := ioutil.ReadAll(response.Body) must(err) result := struct { Error string AccessToken string `json:"access_token"` }{} err = json.Unmarshal(body, &result) must(err) if result.Error != "" { serverErr := fmt.Errorf(`Server returned error: "%s"`, result.Error) log.Print(serverErr) log.Print("Please check your login details.") panic(serverErr) } return result.AccessToken } func main() { data, err := ioutil.ReadFile(settings) login := apiLogin{} if err == nil { jsonErr := json.Unmarshal(data, &login) if jsonErr != nil { log.Print(jsonErr) log.Fatal("Your settings.json file may be malformatted") } } else if !os.IsNotExist(err) { log.Printf(`Was unable to read configuration at "%s", proceeding to manual entry.`, settings) } setFieldIfEmpty := func(field *string, name string) { if *field == "" { fmt.Printf("%s: ", name) fmt.Scanln(field) } } setFieldIfEmpty(&login.Username, "Username") setFieldIfEmpty(&login.Password, "<PASSWORD>") setFieldIfEmpty(&login.ClientID, "Client ID") setFieldIfEmpty(&login.ClientSecret, "Client Secret") userAgent = fmt.Sprintf(userAgentTemplate, login.Username) token := requestToken(login) fmt.Printf("Token: %s\n", token) savedsGet, err := url.Parse(fmt.Sprintf(savedsAPIURL, login.Username)) must(err) params := savedsGet.Query() params.Set("limit", limit) savedsGet.RawQuery = params.Encode() request, err := http.NewRequest( "GET", savedsGet.String(), nil, ) must(err) request.Header.Set("Authorization", fmt.Sprintf("bearer %s", token)) request.Header.Set("User-Agent", userAgent) response, err := client.Do(request) must(err) defer response.Body.Close() outFile, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0744) must(err) _, err = io.Copy(outFile, response.Body) must(err) fmt.Printf("Done. Check %s to find (at most) %s of your most recent saved posts.\n", output, limit) }
13a05dc3496974f09562081dbda28fd09d962476
[ "Markdown", "Go" ]
2
Markdown
Anthony-Fiddes/get-reddit-saveds
ac07ec3c33d991bc75bc7ef13d14b1f37063a17c
84b63314d794c4f4a89cf1c7fd66136bc2d145f3
refs/heads/master
<file_sep>package com.praddy; import opennlp.tools.cmdline.postag.POSModelLoader; import opennlp.tools.postag.POSModel; import opennlp.tools.postag.POSSample; import opennlp.tools.postag.POSTaggerME; import opennlp.tools.tokenize.WhitespaceTokenizer; import opennlp.tools.util.ObjectStream; import opennlp.tools.util.PlainTextByLineStream; import org.apache.commons.lang3.StringUtils; import java.io.*; import java.util.HashMap; import java.util.Map; /** * Hello world! */ public class App { static int TRAIN_FROM_SAMPLE = 30000; static int TRAIN_SAMPLE_EVALUATION_FROM = 10000; static int TRAIN_SAMPLE_EVALUATION_TO = 30000; static int ngram = 3; static POSModel model = new POSModelLoader() .load(new File("/Users/pradeepmishra/Downloads/en-pos-maxent.bin")); static POSTaggerME tagger = new POSTaggerME(model); //Data Containers // Great =4 Poor=0 Range is 0-4 static HashMap<String, Integer> wordWeight = new HashMap<String, Integer>(); static HashMap<String, Frequency> wordWeightFrequency = new HashMap<String, Frequency>(); // Noun[0],Adj[4] = 3, Adj[4]Adv[3] = 5 . what do 2 phrases generally contribute static HashMap<String, Integer> wordTypeNGramContribution = new HashMap<String, Integer>(); static HashMap<String, Frequency> wordTypeNGramContributionFrequency = new HashMap<String, Frequency>(); public static void main(String[] args) { loadData(); testReviews(); } public static void testReviews() { String csvFile = "/Users/pradeepmishra/datascience/kaggle/train.tsv"; BufferedReader br = null; String line = ""; String tabSplitBy = "\t"; int successCount = 0; int failureCount = 0; int errorCount = 0; int relativeSuccessCount = 0; try { int count = 0; int PhraseId = 0, SentenceId = 1, Phrase = 2, Sentiment = 3; br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null && count++ < TRAIN_SAMPLE_EVALUATION_TO) { if (count < TRAIN_SAMPLE_EVALUATION_FROM) { //Ignore heading line continue; } // use comma as separator String[] row = line.split(tabSplitBy); String phrase = row[Phrase]; String[] words = phrase.split("\\s+"); if (null == words || words.length == 0 || !StringUtils.isNumeric(row[Sentiment])) { errorCount++; continue; } Integer sentiment = Integer.parseInt(row[Sentiment]); Integer wordbasedweightage = 0; Integer wordNgrambasedweightage = 0; //word based weighatge // String prevWord = null; // String prevWordType = null; int index = -1; for (String word : words) { index++; Integer wordWeightage = wordWeight.get(word); if (null != wordWeightage) { wordbasedweightage += wordWeightage; } else { wordbasedweightage += 2; } // if (null == prevWordType) { // prevWord = word; // prevWordType = getWordType(word); // continue; // } String currWord = word; String currWordType = getWordType(word); // String KEY = prevWord + "[" + prevWordType + "]" + currWord + "[" + currWordType + "]"; String KEY = ""; int currGram = 0; boolean notPossible = false; while (currGram++ < ngram) { if (index - currGram < 0) { notPossible = true; break; } KEY = getWordType(words[index - currGram]) + "[" + wordWeight.get(words[index - currGram]) + "]" + KEY; } if (notPossible) { continue; } Integer wordTypeNGramContributionWeightage = wordTypeNGramContribution.get(KEY); if (null != wordTypeNGramContributionWeightage) { wordNgrambasedweightage += wordTypeNGramContributionWeightage; } else { wordNgrambasedweightage += 2; } // prevWord = currWord; // prevWordType = currWordType; } Integer wordBasedWeightage = Math.round(wordbasedweightage / words.length); Integer finalWeightage = wordBasedWeightage; Integer word2GramBasedWeightage = 2; if (words.length - ngram + 1 > 0) { word2GramBasedWeightage = Math.round(wordNgrambasedweightage / (words.length - ngram + 1)); finalWeightage = Math.round((wordBasedWeightage + word2GramBasedWeightage) / 2); } if (finalWeightage == sentiment) { successCount++; } else { failureCount++; } if (Math.abs(finalWeightage - sentiment) <= 1.0) { relativeSuccessCount++; } } System.out.println("Total Successes : " + successCount); System.out.println("Total Failures : " + failureCount); System.out.println("Total Errors : " + errorCount); System.out.println("Relative Successes : " + relativeSuccessCount); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static void loadData() { String csvFile = "/Users/pradeepmishra/datascience/kaggle/train.tsv"; BufferedReader br = null; String line = ""; String tabSplitBy = "\t"; try { int count = 0; int PhraseId = 0, SentenceId = 1, Phrase = 2, Sentiment = 3; br = new BufferedReader(new FileReader(csvFile)); while ((line = br.readLine()) != null && count++ < TRAIN_FROM_SAMPLE) { if (count < 2) { //Ignore heading line continue; } // use comma as separator String[] row = line.split(tabSplitBy); String phrase = row[Phrase]; String[] words = phrase.split("\\s+"); Integer sentiment = Integer.parseInt(row[Sentiment]); //word based for (String word : words) { Frequency freq = wordWeightFrequency.get(word); if (null == freq) { freq = new Frequency(); } HashMap<Integer, Integer> keyValue = freq.getKeyValue(); if (null == keyValue) { keyValue = new HashMap<Integer, Integer>(); keyValue.put(sentiment, 0); } Integer value = keyValue.get(sentiment); if (null == value) { value = 0; } keyValue.put(sentiment, value + 1); freq.setKeyValue(keyValue); wordWeightFrequency.put(word, freq); } } // System.out.println("wordWeightFrequency:" + wordWeightFrequency); br.close(); for (Map.Entry<String, Frequency> entry : wordWeightFrequency.entrySet()) { wordWeight.put(entry.getKey(), 2); int maxFrequency = 0; for (Map.Entry<Integer, Integer> levelFrequency : entry.getValue().getKeyValue().entrySet()) { if (levelFrequency.getValue() > maxFrequency) { maxFrequency = levelFrequency.getValue(); wordWeight.put(entry.getKey(), levelFrequency.getKey()); } } } br = new BufferedReader(new FileReader(csvFile)); count = 0; //Go through the file once more to get phrases while ((line = br.readLine()) != null && count++ < TRAIN_FROM_SAMPLE) { if (count < 2) { continue; } // use comma as separator String[] row = line.split(tabSplitBy); String phrase = row[Phrase]; String[] words = phrase.split("\\s+"); Integer sentiment = Integer.parseInt(row[Sentiment]); //word phrase (2 gram) based // String prevWordType = null; // String prevWord = null; int index = -1; for (String word : words) { index++; // if (null == prevWordType) { // prevWordType = getWordType(word); // prevWord = word; // continue; // } String currentWordType = getWordType(word); String currentWord = word; //wordtype1[sentiment]wordtype2[sentiment] = 3 String KEY = ""; int currGram = 0; boolean notPossible = false; while (currGram++ < ngram) { if (index - currGram < 0) { notPossible = true; break; } KEY = getWordType(words[index - currGram]) + "[" + wordWeight.get(words[index - currGram]) + "]" + KEY; } if (notPossible) { continue; } // prevWordType + "[" + wordWeight.get(prevWord) + "]" + currentWordType + "[" + wordWeight.get(currentWord) + "]"; Frequency freq = wordTypeNGramContributionFrequency.get(KEY); if (null == freq) { freq = new Frequency(); } HashMap<Integer, Integer> keyValue = freq.getKeyValue(); if (null == keyValue) { keyValue = new HashMap<Integer, Integer>(); keyValue.put(sentiment, 0); } Integer value = keyValue.get(sentiment); if (null == value) { value = 0; } keyValue.put(sentiment, value + 1); freq.setKeyValue(keyValue); wordTypeNGramContributionFrequency.put(KEY, freq); // prevWordType = currentWordType; } } for (Map.Entry<String, Frequency> entry : wordTypeNGramContributionFrequency.entrySet()) { wordTypeNGramContribution.put(entry.getKey(), 2); int maxFrequency = 0; for (Map.Entry<Integer, Integer> levelFrequency : entry.getValue().getKeyValue().entrySet()) { if (levelFrequency.getValue() > maxFrequency) { maxFrequency = levelFrequency.getValue(); wordTypeNGramContribution.put(entry.getKey(), levelFrequency.getKey()); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (br != null) { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } } System.out.println("wordWeight:" + wordWeight); System.out.println("wordTypeNGramContribution:" + wordTypeNGramContribution); System.out.println("Done"); } public static String getWordType(String input) throws IOException { // String input = "Hi. How are you? This is Mike."; ObjectStream<String> lineStream = new PlainTextByLineStream( new StringReader(input)); String line; while ((line = lineStream.read()) != null) { String whitespaceTokenizerLine[] = WhitespaceTokenizer.INSTANCE .tokenize(line); String[] tags = tagger.tag(whitespaceTokenizerLine); POSSample sample = new POSSample(whitespaceTokenizerLine, tags); // System.out.println(sample.toString()); String removeWordFromType = sample.toString().replace(input, ""); return removeWordFromType; } return "NA"; } } <file_sep>research ======== Various researches conducted by Pradeep Mishra Solutions to various probems analyzed and solved by Pradeep Mishra
00d1828f240a4d59ec419f0106347394111a65db
[ "Markdown", "Java" ]
2
Java
pradeepgmishra/research
1b1a9fb237f359246e68796e766ac789246d6c97
6264e93e7f9e5c69a227bf54080b4f82fca4e56f
refs/heads/master
<repo_name>addictmud/utils<file_sep>/vnums_test.go package utils_test import ( "reflect" "testing" "github.com/addictmud/utils" ) func TestVnumHash(t *testing.T) { var expected_hash string = "29r0cvj793" // test if underlying hash methods are broken hash, err := utils.VnumToHash(12, 1265) expect(t, err, nil, "") expect(t, hash, expected_hash, "") var expected_vnum = []int{12, 1265} zone, vnum, err := utils.HashToVnum(expected_hash) expect(t, err, nil, "") expect(t, zone, expected_vnum[0], "zone") expect(t, vnum, expected_vnum[1], "vnum") } func expect(t *testing.T, a interface{}, b interface{}, body string) { if a != b { if body != "" { t.Errorf("Expected [%v] (type %v) - Got [%v] (type %v) : %s", b, reflect.TypeOf(b), a, reflect.TypeOf(a), body) } else { t.Errorf("Expected [%v] (type %v) - Got [%v] (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a)) } } } <file_sep>/vnums.go package utils import ( "fmt" "github.com/speps/go-hashids" ) // hard-coded values for now, this is not for security purposes // just major convenience var salt string = "addict" var min int = 10 var alphabet = "abcdefgh<KEY>" var hasher *hashids.HashID func Hasher() (*hashids.HashID, error) { if hasher == nil { hd := hashids.NewData() hd.Salt = salt hd.MinLength = min hd.Alphabet = alphabet var err error hasher, err = hashids.NewWithData(hd) return hasher, err } return hasher, nil } func VnumToHash(zone, vnum int) (string, error) { h, err := Hasher() if err != nil { return "", err } e, err := h.Encode([]int{zone, vnum}) return e, err } func HashToVnum(hash string) (zone, vnum int, err error) { h, err := Hasher() if err != nil { return } d, err := h.DecodeWithError(hash) if err != nil { return } if len(d) != 2 { err = fmt.Errorf("vnum hash did not return two values as expected") } else { zone = d[0] vnum = d[1] } return }
82d4d7465d19ce2147cf9fd84098151422af22a6
[ "Go" ]
2
Go
addictmud/utils
f3f811409142874a50333b81704e46b5d586adee
5626e27733f26d84fd9e8b6a7238e25772cbd74f
refs/heads/master
<repo_name>Borsapv/ak8ppo<file_sep>/zamestnanecForm.py from tkinter import * import zamestanecFunctions import sqlite3 #basic settings for form window root = Tk() root.title("Nový zaměstnanec") # Show all employees (ID, first name, last name) def show_employees(): # connection to database conn = sqlite3.connect("tajemnik.db") conn.execute("PRAGMA foreign_keys = 1") # create cursor c = conn.cursor() c.execute("SELECT * FROM zamestnanec") items = c.fetchall() employees = "" for item in items: employees += str(str(item[0]) + " " + str(item[1]) + " " + item[2] + '\n') item_lbl = Label(root, text=employees) item_lbl.grid_forget() item_lbl.grid(row=20, columnspan=2) # Commit commands conn.commit() # Close connection conn.close() # Function to save a new employee def send_form(): first = name_inpt.get() last = last_name_inpt.get() work = mail_work_inpt.get() private = mail_private_inpt.get() phone = phone_number_inpt.get() zamestanecFunctions.add_employee(first, last, work, private, phone) # Function to delete employee (by ID) def delete_employee(): # connection to database conn = sqlite3.connect("tajemnik.db") conn.execute("PRAGMA foreign_keys = 1") # create cursor c = conn.cursor() c.execute("DELETE from zamestnanec WHERE oid = " + chooser_inpt.get()) show_employees() # Commit commands conn.commit() # Close connection conn.close() # Function to show all subjects associated to employee def show_employees_subject(): # connection to database conn = sqlite3.connect("tajemnik.db") conn.execute("PRAGMA foreign_keys = 1") # create cursor c = conn.cursor() c.execute("SELECT * from predmet WHERE id_employee = " + chooser_inpt.get()) subjects = c.fetchall() all_subjects = "" for subject in subjects: all_subjects += str(subject[1] + " " + str(subject[2]) + " hodin" + '\n') item_lbl = Label(root, text=all_subjects) item_lbl.grid_forget() item_lbl.grid(row=21, columnspan=2, pady=5) # Commit commands conn.commit() # Close connection conn.close() # set fields and buttons name_lbl = Label(root, text="Jméno") name_inpt = Entry(root) last_name_lbl = Label(root, text="Příjmení") last_name_inpt = Entry(root) mail_work_lbl = Label(root, text="Pracovní email") mail_work_inpt = Entry(root) mail_private_lbl = Label(root, text="Soukromý email") mail_private_inpt = Entry(root) phone_number_lbl = Label(root, text="Telefon") phone_number_inpt = Entry(root) save_btn = Button(root, text="Uložit", command=send_form) save_btn.grid(row=5, column=0, columnspan=2, ipadx=100, pady=10) show_btn = Button(root, text="Zobrazit všechny zaměstnance", command=show_employees) show_btn.grid (row=6, column=0, columnspan=2, ipadx=34) chooser_lbl = Label(root, text="Volba zaměstnance (ID)") chooser_inpt = Entry(root) chooser_lbl.grid(row=7, column=0) chooser_inpt.grid(row=7, column=1) delete_btn = Button(root, text="Smazat zvoleného zaměstnance", command=delete_employee) delete_btn.grid (row=8, column=0, columnspan=2, ipadx=33, pady=5) show_subjects_btn = Button(root, text="Předměty zvoleného zaměstnance", command=show_employees_subject) show_subjects_btn.grid (row=9, column=0, columnspan=2, ipadx=27) # place created fields on the screen - using grid system name_lbl.grid(row=0, column=0) name_inpt.grid(row=0, column=1, padx=20) last_name_lbl.grid(row=1, column=0) last_name_inpt.grid(row=1, column=1, padx=20) mail_work_lbl.grid(row=2, column=0) mail_work_inpt.grid(row=2, column=1, padx=20) mail_private_lbl.grid(row=3, column=0) mail_private_inpt.grid(row=3, column=1, padx=20) phone_number_lbl.grid(row=4, column=0) phone_number_inpt.grid(row=4, column=1, padx=20) #main loop root.mainloop()<file_sep>/zamestanecFunctions.py import sqlite3 from tkinter import * # Save a new employee entry def add_employee(name,last_name,mail_work,mail_private,phone_number): # connection to database conn = sqlite3.connect("tajemnik.db") # create cursor c = conn.cursor() c.execute("INSERT INTO zamestnanec(name, last_name, mail_work, mail_private, phone_number) VALUES(?,?,?,?,?)", (name, last_name, mail_work, mail_private, phone_number)) # Commit commands conn.commit() # Close connection conn.close() # Save a new subject entry def add_subject(name, hours, id): # connection to database conn = sqlite3.connect("tajemnik.db") conn.execute("PRAGMA foreign_keys = 1") # create cursor c = conn.cursor() c.execute("INSERT INTO predmet(name, pocet_hodin, id_employee) VALUES(?,?,?)", (name, hours, id)) # Commit commands conn.commit() # Close connection conn.close() # Show all from zamestnanec table def show_all_employees(): # connection to database conn = sqlite3.connect("tajemnik.db") conn.execute("PRAGMA foreign_keys = 1") # create cursor c = conn.cursor() c.execute("SELECT * FROM zamestnanec") items = c.fetchall() for item in items: item_lbl = Label(root, text=item) item_lbl.pack() # Commit commands conn.commit() # Close connection conn.close() # Show all from zamestnanec table def show_all_subjects(): # connection to database conn = sqlite3.connect("tajemnik.db") conn.execute("PRAGMA foreign_keys = 1") # create cursor c = conn.cursor() c.execute("SELECT rowid, * FROM predmet") items = c.fetchall() for item in items: print(item) # Commit commands conn.commit() # Close connection conn.close()<file_sep>/test_vypisu.py import zamestanecFunctions zamestanecFunctions.show_all_employees() zamestanecFunctions.show_all_subjects()<file_sep>/database.py import sqlite3 # connection to database conn = sqlite3.connect("tajemnik.db") conn.execute("PRAGMA foreign_keys = 1") # create cursor c = conn.cursor() # create tables predmety, zamestnanci, obory, stitek, vahy pacovnich bodu c.execute(""" CREATE TABLE predmet ( id_subject INTEGER PRIMARY KEY NOT NULL, name STRING, pocet_hodin INTEGER, id_employee INTEGER NOT NULL, FOREIGN KEY (id_employee) REFERENCES zamestnanec(id_employee) ON UPDATE CASCADE ON DELETE RESTRICT ) """) c.execute(""" CREATE TABLE obor ( id INTEGER ) """) c.execute(""" CREATE TABLE predmet_obor ( id INTEGER ) """) c.execute(""" CREATE TABLE zamestnanec ( id_employee INTEGER PRIMARY KEY NOT NULL, name STRING, last_name STRING, mail_work STRING, mail_private STRING, phone_number STRING ) """) c.execute(""" CREATE TABLE stitek ( id INTEGER ) """) c.execute(""" CREATE TABLE vahy_pracovnich_bodu ( id INTEGER ) """) #Commit commands conn.commit() #Close connection conn.close()<file_sep>/predmetForm.py from tkinter import * import zamestanecFunctions #basic settings for form window root = Tk() root.title("Nový předmět") def send_form(): name = name_inpt.get() hours = hours_inpt.get() id = id_employee_inpt.get() zamestanecFunctions.add_subject(name, hours, id) # set fields and buttons name_lbl = Label(root, text="Jméno") name_inpt = Entry(root) hours_lbl = Label(root, text="Počet hodin") hours_inpt = Entry(root) id_employee_lbl = Label(root, text="ID_employee") id_employee_inpt = Entry(root) send_btn = Button(root, text="Uložit", command=send_form) # place created fields on the screen - using grid system name_lbl.grid(row=0, column=0) name_inpt.grid(row=0, column=1, padx=20) hours_lbl.grid(row=1, column=0) hours_inpt.grid(row=1, column=1, padx=20) id_employee_lbl.grid(row=2, column=0) id_employee_inpt.grid(row=2, column=1, padx=20) send_btn.grid(row=5, column=1) #main loop root.mainloop()
075ae7210d974e4b3d2059c7aacb73bc281a3210
[ "Python" ]
5
Python
Borsapv/ak8ppo
ea2ec55feafbdcbcb8ed2b14d2c206645863b6e8
9ff35f2ae82bdbfd59cf474b1ecbed5aa97d7593
refs/heads/master
<repo_name>urbitassociates-archive/drone-kubernetes-helm<file_sep>/.env.example KUBE_CONFIG=<KUBE_CONFIG_BASE64> KUBE_CA=<KUBE_CA_BASE64> KUBE_CLIENT_CERT=<KUBE_CLIENT_CERT_BASE64> KUBE_CLIENT_KEY=<KUBE_CLIENT_KEY_BASE64><file_sep>/commands/fetch.go package commands import ( "os" "os/exec" ) func (c *Command) Fetch() (interface{}, error) { cmd := exec.Command("helm", "fetch") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr for _, flag := range c.Flags { for k, v := range flag { switch k { case "d": fallthrough case "destination": cmd.Args = append(cmd.Args, "--destination", v.(string)) case "keyring": cmd.Args = append(cmd.Args, "--keyring", v.(string)) case "untar": cmd.Args = append(cmd.Args, "--untar") case "untardir": cmd.Args = append(cmd.Args, "--untardir", v.(string)) case "verify": cmd.Args = append(cmd.Args, "--verify") case "version": cmd.Args = append(cmd.Args, "--version", v.(string)) case "reverse": cmd.Args = append(cmd.Args, "--reverse") // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } if len(c.Args) > 0 { for _, arg := range c.Args { cmd.Args = append(cmd.Args, arg) } } else { cmd.Args = append(cmd.Args, c.Chart) } trace(cmd) return nil, cmd.Run() } <file_sep>/commands/rollback.go package commands import ( "os" "os/exec" // "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/proto/hapi/services" ) func (c *Command) Rollback() (*services.RollbackReleaseResponse, error) { cmd := exec.Command("helm", "rollback", c.Release) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr for _, flag := range c.Flags { for k, v := range flag { switch k { case "dry-run": cmd.Args = append(cmd.Args, "--dry-run") case "no-hooks": cmd.Args = append(cmd.Args, "--no-hooks") // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } if len(c.Args) > 0 { for _, arg := range c.Args { cmd.Args = append(cmd.Args, arg) } } trace(cmd) return nil, cmd.Run() } <file_sep>/README.md # drone-kubernetes-helm Drone plugin to deploy or update a project on Kubernetes using Helm. For the usage information and a listing of the available options please take a look at [the docs](DOCS.md). ## Build with Docker Build the container: ``` docker build . -t docker-kubernetes-helm:local-test ``` ## How to test Run the `test.sh` file<file_sep>/commands/repo.go package commands import ( "os" "os/exec" // "k8s.io/helm/pkg/helm" ) func (c *Command) Repo() (interface{}, error) { cmd := exec.Command("helm", "repo") cmd.Stderr = os.Stderr switch c.SubCommand { case "add": cmd.Args = append(cmd.Args, "add") case "index": cmd.Args = append(cmd.Args, "index") case "list": cmd.Args = append(cmd.Args, "list") case "remove": cmd.Args = append(cmd.Args, "remove") case "update": cmd.Args = append(cmd.Args, "update") } for _, flag := range c.Flags { for k, v := range flag { switch k { // Local: repo add case "no-update": cmd.Args = append(cmd.Args, "--no-update") // Local: repo index case "merge": cmd.Args = append(cmd.Args, "--merge", v.(string)) // Local: repo index case "url": cmd.Args = append(cmd.Args, "--url", v.(string)) // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } if len(c.Args) > 0 { for _, arg := range c.Args { cmd.Args = append(cmd.Args, arg) } } res, err := cmd.Output() if err != nil { return nil, err } trace(cmd) _, err = os.Stdout.Write(res) if err != nil { return nil, err } return res, nil } <file_sep>/commands/list.go package commands import ( "os" "os/exec" // "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/proto/hapi/services" ) func (c *Command) List() (*services.ListReleasesResponse, error) { cmd := exec.Command("helm", "list") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr for _, flag := range c.Flags { for k, v := range flag { switch k { case "all": cmd.Args = append(cmd.Args, "--all") case "d": fallthrough case "date": cmd.Args = append(cmd.Args, "--date") case "deleted": cmd.Args = append(cmd.Args, "--deleted") case "deployed": cmd.Args = append(cmd.Args, "--deployed") case "failed": cmd.Args = append(cmd.Args, "--failed") case "m": fallthrough case "max": cmd.Args = append(cmd.Args, "--max", v.(string)) case "o": fallthrough case "offset": cmd.Args = append(cmd.Args, "--offset", v.(string)) case "reverse": cmd.Args = append(cmd.Args, "--reverse") case "q": fallthrough case "short": cmd.Args = append(cmd.Args, "--short") // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } if c.Filter != "" { cmd.Args = append(cmd.Args, c.Filter) } else if len(c.Args) > 0 { for _, arg := range c.Args { cmd.Args = append(cmd.Args, arg) } } trace(cmd) return nil, cmd.Run() } <file_sep>/commands/commands.go package commands import ( "fmt" "os/exec" "strings" "github.com/pkg/errors" ) type ( Command struct { Release string `json:"release"` // "dev-store-api" Chart string `json:"chart"` // "store-api" Flags []map[string]interface{} `json:"flags"` // ["namespace"] = "kube-system" Filter string `json:"filter"` // "dev" SubCommand string `json:"command"` // "values" Args []string `json:"args"` // ["name", "url"] } ) // Invoke executes helm CLI commands, with their respective flags and values func (c *Command) Invoke(name string) (interface{}, error) { switch name { case "fetch": return c.Fetch() case "get": return c.Get() case "hist": fallthrough case "history": return c.History() case "ls": fallthrough case "list": return c.List() case "install": return c.Install() case "del": fallthrough case "delete": return c.Delete() case "upgrade": return c.Upgrade() case "repo": return c.Repo() case "rollback": return c.Rollback() case "status": return c.Status() case "version": return c.Version() default: return nil, errors.New(fmt.Sprintf("Command '%v' not available\n", name)) } } // Trace writes each command to standard error (preceded by a ‘$ ’) before it // is executed. Used for debugging your build. func trace(cmd *exec.Cmd) { fmt.Println("$", strings.Join(cmd.Args, " ")) } <file_sep>/commands/get.go package commands import ( "os" "os/exec" ) func (c *Command) Get() (interface{}, error) { cmd := exec.Command("helm", "get") cmd.Stderr = os.Stderr o := "" switch c.SubCommand { case "hooks": cmd.Args = append(cmd.Args, "hooks") case "manifest": cmd.Args = append(cmd.Args, "manifest") case "values": cmd.Args = append(cmd.Args, "values") } for _, flag := range c.Flags { for k, v := range flag { switch k { // Local case "all": cmd.Args = append(cmd.Args, "--all") case "revision": cmd.Args = append(cmd.Args, "--revision", v.(string)) case "output": o = v.(string) // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } if len(c.Args) > 0 { for _, arg := range c.Args { cmd.Args = append(cmd.Args, arg) } } else { cmd.Args = append(cmd.Args, c.Release) } res, err := cmd.Output() if err != nil { return nil, err } if o != "" { f, err := os.Create(o) if err != nil { return nil, err } _, err = f.Write(res) if err != nil { return nil, err } err = f.Close() if err != nil { return nil, err } } trace(cmd) _, err = os.Stdout.Write(res) if err != nil { return nil, err } return res, nil } <file_sep>/DOCS.md Use the Kubernetes Helm plugin to upgrade a service in [Kubernetes](http://kubernetes.io). The following parameters are used to configure this plugin: - `config` - kubectl config & credentials - `commands` - helm commands to run [Example drone configuration](./drone-example.yml)<file_sep>/commands/version.go package commands import ( "os" "os/exec" // "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/proto/hapi/services" ) func (c *Command) Version() (*services.GetVersionResponse, error) { cmd := exec.Command("helm", "version") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr for _, flag := range c.Flags { for k, v := range flag { switch k { case "c": fallthrough case "client": cmd.Args = append(cmd.Args, "--client") case "s": fallthrough case "server": cmd.Args = append(cmd.Args, "--server") // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } trace(cmd) return nil, cmd.Run() } <file_sep>/test.sh #!/bin/sh set -e source .env sed -e ' s/{{KUBE_CONFIG}}/'$KUBE_CONFIG'/g; s/{{KUBE_CA}}/'$KUBE_CA'/g; s/{{KUBE_CLIENT_CERT}}/'$KUBE_CLIENT_CERT'/g; s/{{KUBE_CLIENT_KEY}}/'$KUBE_CLIENT_KEY'/g; ' ./test-drone-config.json.tpl > ./test-drone-config.json docker build --no-cache . -t test docker run -i test < test-drone-config.json <file_sep>/commands/upgrade.go package commands import ( "os" "os/exec" // "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/proto/hapi/services" ) func (c *Command) Upgrade() (*services.UpdateReleaseResponse, error) { ns := "default" cmd := exec.Command("helm", "upgrade", c.Release, c.Chart) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr for _, flag := range c.Flags { for k, v := range flag { switch k { // Local case "disable-hooks": cmd.Args = append(cmd.Args, "--disable-hooks") case "dry-run": cmd.Args = append(cmd.Args, "--dry-run") case "i": fallthrough case "install": cmd.Args = append(cmd.Args, "--install") case "keyring": cmd.Args = append(cmd.Args, "--keyring", v.(string)) case "namespace": ns = v.(string) case "set": cmd.Args = append(cmd.Args, "--set", v.(string)) case "f": fallthrough case "values": cmd.Args = append(cmd.Args, "--values", v.(string)) case "verify": cmd.Args = append(cmd.Args, "--verify") case "version": cmd.Args = append(cmd.Args, "--version", v.(string)) // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } cmd.Args = append(cmd.Args, "--namespace", ns) trace(cmd) err := cmd.Run() if err != nil { c.Args = append([]string{}, "0") c.Rollback() } return nil, err } <file_sep>/commands/status.go package commands import ( "os" "os/exec" // "k8s.io/helm/pkg/helm" "k8s.io/helm/pkg/proto/hapi/services" ) func (c *Command) Status() (*services.GetReleaseStatusResponse, error) { cmd := exec.Command("helm", "status", c.Release) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr for _, flag := range c.Flags { for k, v := range flag { switch k { case "revision": cmd.Args = append(cmd.Args, "--revision", v.(string)) // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } trace(cmd) return nil, cmd.Run() } <file_sep>/commands/history.go package commands import ( "os" "os/exec" ) func (c *Command) History() (interface{}, error) { cmd := exec.Command("helm", "history") cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr for _, flag := range c.Flags { for k, v := range flag { switch k { // Local case "max": cmd.Args = append(cmd.Args, "--max", v.(string)) // Global case "debug": cmd.Args = append(cmd.Args, "--debug") case "home": cmd.Args = append(cmd.Args, "--home", v.(string)) case "host": cmd.Args = append(cmd.Args, "--host", v.(string)) case "kube-context": cmd.Args = append(cmd.Args, "--kube-context", v.(string)) } } } if len(c.Args) > 0 { for _, arg := range c.Args { cmd.Args = append(cmd.Args, arg) } } else { cmd.Args = append(cmd.Args, c.Release) } trace(cmd) return nil, cmd.Run() } <file_sep>/config/config.go package config import ( "encoding/base64" "io/ioutil" "fmt" ) type ( Credentials struct { CA string `json:"certificate-authority"` ClientCert string `json:"client-certificate"` ClientKey string `json:"client-key"` } Config struct { Kubeconfig string `json:"kubeconfig"` Credentials Credentials `json:"credentials"` } ) const ( ROOT_PATH = "/root/.kube/" KUBECONFIG = "kubeconfig" CONFIG = "config" CREDENTIALS_PATH = ROOT_PATH + "credentials/" CA_CERT = "ca.pem" CLIENT_CERT = "client.pem" CLIENT_KEY = "client-key.pem" ) // Setup writes the kubectl config and credentials to file func (cfg *Config) Init() error { // Decode and output CA cert ca, err := base64.StdEncoding.DecodeString(cfg.Credentials.CA) if err != nil { return err } err = ioutil.WriteFile(CREDENTIALS_PATH+CA_CERT, ca, 0644) if err != nil { return err } fmt.Println("Wrote CA cert") // Decode and output client cert crt, err := base64.StdEncoding.DecodeString(cfg.Credentials.ClientCert) if err != nil { return err } err = ioutil.WriteFile(CREDENTIALS_PATH+CLIENT_CERT, crt, 0644) if err != nil { return err } fmt.Println("Wrote client cert") // Decode and output client key key, err := base64.StdEncoding.DecodeString(cfg.Credentials.ClientKey) if err != nil { return err } err = ioutil.WriteFile(CREDENTIALS_PATH+CLIENT_KEY, key, 0644) if err != nil { return err } fmt.Println("Wrote client key") // Decode and output kubeconfig config, err := base64.StdEncoding.DecodeString(cfg.Kubeconfig) if err != nil { return err } err = ioutil.WriteFile(ROOT_PATH + CONFIG, config, 0644) if err != nil { return err } fmt.Println("Wrote kubeconfig") return nil } <file_sep>/Dockerfile # Docker image for the Drone build runner # # CGO_ENABLED=0 go build -a -tags netgo # docker build --rm=true -t urbit/drone-kubernetes-helm . FROM alpine:3.8 # Environment variables ARG K8S_VERSION=1.9.3 ARG HELM_VERSION=2.9.1 ARG KUBE_PATH="/root/.kube/" ADD . /root/go/src/github.com/urbitassociates/drone-kubernetes-helm # Install dependencies & Clean up RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/3.8/community/ add \ curl \ git \ musl-dev \ go \ glide \ && apk --no-cache del \ wget \ && rm -rf /var/cache/apk/* /tmp/* # Install Go dependencies WORKDIR /root/go/src/github.com/urbitassociates/drone-kubernetes-helm RUN glide install # Build ENV GOOS=linux ENV GOARCH=amd64 ENV CGO_ENABLED=0 RUN go build # Install kubectl & helm for the runtime RUN curl -#SL -o /usr/local/bin/kubectl https://storage.googleapis.com/kubernetes-release/release/v$K8S_VERSION/bin/linux/amd64/kubectl \ && chmod +x /usr/local/bin/kubectl \ && curl -#SL https://storage.googleapis.com/kubernetes-helm/helm-v$HELM_VERSION-linux-amd64.tar.gz | tar zxvf - \ && mv linux-amd64/helm /usr/local/bin/helm && rm -rf linux-amd64 \ && chmod +x /usr/local/bin/helm \ && mkdir -p ~/.kube/credentials && helm init -c ENTRYPOINT ["./drone-kubernetes-helm"] <file_sep>/main.go package main import ( "fmt" "log" "os" // "github.com/drone/drone-go/plugin" // https://github.com/drone/drone-go/tree/eaa41f7836a191224ec5702d2458db07882ec269 "github.com/drone/drone-plugin-go/plugin" "github.com/urbitassociates/drone-kubernetes-helm/commands" "github.com/urbitassociates/drone-kubernetes-helm/config" ) type ( Helm struct { Config config.Config `json:"config"` Commands []map[string]commands.Command `json:"commands"` } ) var ( buildCommit string ) func main() { fmt.Printf("Drone Kubernetes Helm Plugin built from %s\n", buildCommit) workspace := plugin.Workspace{} build := plugin.Build{} vargs := Helm{} plugin.Param("workspace", &workspace) plugin.Param("build", &build) plugin.Param("vargs", &vargs) plugin.MustParse() err := vargs.Config.Init() if err != nil { log.Fatalln(err) } // loop through commands for _, command := range vargs.Commands { for k, v := range command { r, e := v.Invoke(k) if e != nil { fmt.Fprintln(os.Stderr) fmt.Println(r) log.Fatalln(e) } fmt.Fprintln(os.Stdout) } } }
6f5d03c7491018e4d4d6aed4c49937c27e88ab53
[ "Markdown", "Go", "Dockerfile", "Shell" ]
17
Shell
urbitassociates-archive/drone-kubernetes-helm
e97b4325b045dab1c7d080b3500324b8c934f5c3
66a0d920e47991f61b990f4c8b5ed29deda2fb8b
refs/heads/master
<file_sep># Arduino YL-69_HL-69 Soil Moisture Read YL-69_HL-69 Soil Moisture with Arduino # Open file Schematics to build the project <file_sep># Arduino Arduino Sensor Modules # Profil * <NAME> * IG : @muskarab * Github : MustafaKamalRabbani * email : <EMAIL> <file_sep># Arduino DS-18B20 Temperature Read DS-18B20 with Arduino # Open file Schematics to build the project # Download and copy library into Arduino Library <file_sep># Arduino HC-SR04 Ultrasonic Read HC-SR04 Ultrasonic with Arduino # Open file Schematics to build the project # Download and copy library into Arduino Library <file_sep># Arduino PIR Motion gas/smoke Read PIR Motion with Arduino # Open file Schematics to build the project <file_sep>/* * Arduino BMP180 * <NAME> * IG : @muskarab * Github : MustafaKamalRabbani */ int smokeA0 = A0; // Your threshold value int sensorThres = 400; void setup() { pinMode(smokeA0, INPUT); Serial.begin(9600); } void loop() { int analogSensor = analogRead(smokeA0); Serial.print("Pin A0: "); Serial.println(analogSensor); // Checks if it has reached the threshold value delay(100); } <file_sep>/* * Arduino BMP180 * <NAME> * IG : @muskarab * Github : MustafaKamalRabbani */ int rainPin = A0; int greenLED = 6; int redLED = 7; // you can adjust the threshold value int thresholdValue = 800; void setup(){ pinMode(rainPin, INPUT); pinMode(greenLED, OUTPUT); pinMode(redLED, OUTPUT); digitalWrite(greenLED, LOW); digitalWrite(redLED, LOW); Serial.begin(9600); } void loop() { // read the input on analog pin 0: int sensorValue = analogRead(rainPin); Serial.print(sensorValue); if(sensorValue < thresholdValue){ Serial.println(" - Doesn't need watering"); digitalWrite(redLED, LOW); digitalWrite(greenLED, HIGH); } else { Serial.println(" - Time to water your plant"); digitalWrite(redLED, HIGH); digitalWrite(greenLED, LOW); } delay(500); } <file_sep># Arduino BMP180 Pressure Read BMP180 Pressure with Arduino # Open file Schematics to build the project # Download and copy library into Arduino Library <file_sep># Arduino DHT11 Read DHT11 with Arduino # Open file Schematics to build the project # Download and copy library into Arduino Library <file_sep># Arduino RTC Read RTC with Arduino # Open file Schematics to build the project <file_sep># Arduino MQ-2 gas/smoke Read MQ-2 with Arduino # Open file Schematics to build the project <file_sep># Arduino FC-47 Rain Sensor Read FC-47 Rain Sensor with Arduino # Open file Schematics to build the project
188309be68992b5a3d0eaa8a676c5b90d730d07e
[ "Markdown", "C++" ]
12
Markdown
MustafaKamalRabbani/Arduino
479dbe84e0f3742d131ac5b980d35e1838e6e38b
89a8eb9f8ad473fddda927ce16f18c18602fa748
refs/heads/master
<file_sep>import React, { Component } from 'react'; import Header from './Components/Theme/Header'; import Menu from './Components/Theme/Menu'; import {Router, Route, Switch} from 'react-router'; import indexRoutes from './routes' import {createBrowserHistory} from "history"; var hist = createBrowserHistory(); class App extends Component { render() { return ( <div className="App"> <div className="page-header"> <Header/> <Menu /> </div> <section className="content"> <Router history={hist}> <Switch> {indexRoutes.map((prop, key) => { return <Route exact path={prop.path} key={key} component={prop.component} /> })} </Switch> </Router> </section> </div> ); } } export default App; <file_sep>import React from 'react' import { Field, reduxForm } from 'redux-form' import validate from '../validate' import renderField from './Fields/renderField' import { Table, Modal, Form, Card, CardBody, CardHeader, Button, Row, Col, Container } from 'reactstrap' import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser'; import successIco from '../../../../../dist/img/success.svg' import loadging from '../../../../../dist/img/tourddLoading.svg' import _Collpase from './Collapse' const moment = require('moment'); require("moment/min/locales.min"); moment.locale('th'); function numberWithCommas (x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } const Thirdpage = props => { if(props.booking.isLoading){ return ( <Modal isOpen={true} fade={false} className="modal-loading"> <div style={{display:'flex', justifyContent:'center'}}><img src={loadging}></img></div> </Modal> ) } const {booking} = props return ( <div className="container"> <div> <Card> <Row> <Container style={{ paddingTop: '1rem', display: 'flex', justifyItems: 'center' }}> <img style={{ margin: '0 auto', height: '80px', width: '80pxs' }} src={successIco}></img> </Container> </Row> <Row style={{ display: 'flex', textAlign: 'center', justifyContent: 'center' }}> <h3 >เราได้รับการจองขอบคุณเรียบร้อยแล้ว</h3> </Row> <Row style={{ display: 'flex', textAlign: 'center', justifyContent: 'center' }}> <h5>ขอบคุณที่ไว้วางใจให้เราดูแลคุณ</h5> </Row> <Row style={{ paddingTop: '1rem', display: 'flex', textAlign: 'center', justifyContent: 'center' }}> <h5>กำลังตรวจสอบที่นั่ง...</h5> </Row> <Row style={{ display: 'flex', textAlign: 'center', justifyContent: 'center' }}> <h6>ทางทัวร์ดีดีจะติดต่อกลับไปยังข้อมูลติดต่อของท่าน</h6> </Row> </Card> <Card> <Container style={{ margin: '1rem' }}> <Row> <h5>ข้อมูลการจอง</h5> </Row> <Row> <Col xs="4"> <span>รหัสการจอง TDD-{booking && booking.reference}</span> </Col> <Col xs="8"> <span>คุณ {booking && booking.bookingCustomer}</span>{' '} </Col> </Row> <Row className="justify-content-md-center"> <Col xs="10"> <Table bordered> <thead > <tr> <th className="text-align-center">รายการ</th> <th className="text-align-right">จำนวน</th> <th className="text-align-right">ราคาต่อหน่วย</th> <th className="text-align-right">รวม</th> </tr> </thead> <tbody> {booking && booking.item && booking.item.map(e=>{ return <tr key={e.detail_id}> <td className="text-align-center">{e.detail_name}</td> <td className="text-align-right">{numberWithCommas(parseInt(e.detail_count))}</td> <td className="text-align-right">{numberWithCommas(parseInt(e.detail_price))} บาท</td> <td className="text-align-right">{numberWithCommas(parseInt(e.sum))} บาท</td> </tr> })} <tr> <td colSpan="3" className="text-align-left">รวม</td> <td className="text-align-right">{booking.amount} บาท</td> </tr> </tbody> </Table> </Col> </Row> </Container> </Card> </div> </div> ) } export default Thirdpage<file_sep> import axios from 'axios'; //lib import config from '../../config'; //config const BASE_URL = config.BASE_URL export const createBooking = (values) => { return (dispatch) => { dispatch({ type: 'CREATE_BOOKING_PENDING' }) return axios({ method: 'post', url: `${BASE_URL}/booking/`, data: values }).then(results => { return dispatch({ type: 'CREATE_BOOKING_SUCCESS', payload: results.data }) }).catch(err => { return dispatch({ type: 'CREATE_BOOKING_REJECTED', payload: err.message }) }) } } <file_sep> const validate = values => { const errors = {} if (!values.firstName) { errors.firstName = 'ต้องการฟิลด์นี้' } if (!values.lastName) { errors.lastName = 'ต้องการฟิลด์นี้' } if (!values.email) { errors.email = 'ต้องการฟิลด์นี้' } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) { errors.email = 'รูปแบบ E-mail ไม่ถูกต้อง ตัวอย่าง: <EMAIL>' } if(!values.telNumber){ errors.telNumber ="ต้องการฟิลด์นี้" }else if(!/\(?([0-9]{2})\)?([ .-]?)([0-9]{3})\2([0-9]{4})/.test(values.telNumber)){ errors.telNumber ="รูปแบบเบอร์โทรศัพท์ที่รองรับ 083-456-7899 และ 0834567899" } return errors } export default validate; <file_sep> import axios from 'axios'; //lib import config from '../../config'; //config const BASE_URL = config.BASE_URL export const loadPeriod = (id) => { return (dispatch) => { dispatch({ type: 'LOAD_PERIOD_PENDING' }) return axios.get(`${BASE_URL}/products/${id}`, { }).then(results => { dispatch({ type: 'LOAD_PERIOD_SUCCESS', payload: results.data }) }).catch(err => { dispatch({ type: 'LOAD_PERIOD_REJECTED', payload: err.message }) }) } } <file_sep>import React from 'react' import { Field, reduxForm } from 'redux-form' import validate from '../validate' import renderField from './Fields/renderField' import { Table, Form, Card, CardBody, CardHeader, Button, Row, Col, Container } from 'reactstrap' import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 } from 'react-html-parser'; import _Collpase from './Collapse' const moment = require('moment'); require("moment/min/locales.min"); moment.locale('th'); const FistPage = props => { const { initialize, handleSubmit, data } = props const forward = (params) => { initialize({ period: params }) handleSubmit(); } return ( <div> {data && data.map(e => { return ( <div key={e.item_id}> <Card> <CardHeader> ข้อมูลทัวร์ </CardHeader> <CardBody> <Row> <Col xs="12" md="6" > รหัสสินค้า: {e.item_code} </Col> </Row> <Row> <Col xs="12" md="6" > {e.item_name} </Col> </Row> <Row style={{ marginTop: '.5rem', borderTop: 'solid 1px', borderBottom: 'solid 1px' }} > <Col style={{ paddingTop: '.5rem' }}> <h2><i className="fas fa-globe-asia" /> รายละเอียดทัวร์</h2> <Container> {ReactHtmlParser(e.item_description)} {e.item_highlight} </Container> </Col> </Row> </CardBody> </Card> <Form onSubmit={handleSubmit} className="Wizard-form"> <Card > <CardHeader> แบบฟอร์มสำหรับจองทัวร์นี้ </CardHeader> <CardBody> <Row style={{ marginTop: '.5rem' }} > <Col style={{ paddingTop: '.5rem' }}> <h5><i className="far fa-calendar-alt" /> ปฏิทินการเดินทาง</h5> </Col> </Row> <Table> <thead> <tr> <th style={{ textAlign: 'center' }} colSpan="3">วันเดินทาง</th> <th>จำนวนวัน</th> <th>สายการบิน</th> <th></th> </tr> </thead> <tbody> {e.plans.map((_e, _i) => { if (_e.plan_id === props.cursor) { return [ <tr key={`0-${_e.plan_id}`}> <td className="text-align-center" width="180">{moment(_e.plan_start_date).add(543, 'years').format('ll')} </td> <td className="text-align-center" width="10"><i className="fas fa-arrow-right" /></td> <td className="text-align-center" width="180">{moment(_e.plan_end_date).add(543, 'years').format('ll')}</td> <td>{e.item_days} วัน {e.item_night} คืน</td> <td></td> <td><Button style={{ width: '4rem' }} color="danger" onClick={() => { props.collapse(_e.plan_id) }}>ปิด</Button></td> </tr>, <_Collpase plan_id={_e.plan_id} handleSelect={forward} data={_e.plans_condition} key={`1-${_e.plan_id}`} /> ] } return ( <tr key={`0-${_e.plan_id}`}> <td className="text-align-center" width="180">{moment(_e.plan_start_date).add(543, 'years').format('ll')} </td> <td className="text-align-center" width="10"><i className="fas fa-arrow-right" /></td> <td className="text-align-center" width="180">{moment(_e.plan_end_date).add(543, 'years').format('ll')}</td> <td>{e.item_days} วัน {e.item_night} คืน</td> <td></td> <td> <Button outline color="danger" style={{ width: '4rem' }} onClick={() => { props.collapse(_e.plan_id) }} >เลือก</Button> </td> </tr> ) })} </tbody> </Table> </CardBody> </Card> </Form> </div> ) })} </div> ) } export default reduxForm({ form: 'wizard', // <------ same form name destroyOnUnmount: false, // <------ preserve form data forceUnregisterOnUnmount: true, // <------ unregister fields on unmount validate })(FistPage)<file_sep>import React from 'react'; import { Collapse, Navbar, NavbarToggler, Button, Nav, NavItem, NavLink, UncontrolledDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; export default class Example extends React.Component { constructor(props) { super(props); this.toggle = this.toggle.bind(this); this.state = { isOpen: false }; } toggle() { this.setState({ isOpen: !this.state.isOpen }); } render() { return ( <header className="page-header-second container"> <Navbar light expand="md"> <NavbarToggler onClick={this.toggle} /> <Collapse isOpen={this.state.isOpen} navbar> <Nav className="mdle-auto" navbar> <NavItem> <NavLink href="/components/">หน้าแรก</NavLink> </NavItem> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret> โปรแกรมทัวร์แนะนำ </DropdownToggle> <DropdownMenu right> <DropdownItem> ทัวร์ยอดนิยม </DropdownItem> <DropdownItem> ทัวร์แนะนำ </DropdownItem> <DropdownItem> ทัวร์ถูก </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret> แพ็คเกจทัวร์ </DropdownToggle> <DropdownMenu right> <DropdownItem> ทัวร์ยุโรป </DropdownItem> <DropdownItem> ทัวร์เอเชีย </DropdownItem> <DropdownItem> ทัวร์อื่นๆ </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <NavItem> <NavLink href="/components/">กรุ๊ปส่วนตัว</NavLink> </NavItem> <NavItem> <NavLink href="/components/">แบคแพ็ค</NavLink> </NavItem> <UncontrolledDropdown nav inNavbar> <DropdownToggle nav caret> บทความ </DropdownToggle> <DropdownMenu right> <DropdownItem> ท่องเที่ยว </DropdownItem> <DropdownItem> โปรโมชั่น </DropdownItem> </DropdownMenu> </UncontrolledDropdown> <NavItem> <NavLink href="/components/">บริการ</NavLink> </NavItem> <NavItem> <NavLink href="/components/">สมัครสมาชิก</NavLink> </NavItem> {' '} <NavItem> <NavLink href="/components/">เข้าสู่ระบบ</NavLink> </NavItem> <NavItem> <Button color="link"> <i className="fas fa-search fa-lg"></i> </Button> </NavItem> </Nav> </Collapse> </Navbar> </header> ); } }<file_sep>const config = { // BASE_URL: 'http://localhost:3009', BASE_URL: 'http://api1.vm101.net', COMPANY_ID:1635 } export default config <file_sep>import React, { Component } from 'react' import { Container } from 'reactstrap' import brand from '../../dist/img/tourdd.jpg' import '../../dist/css/app.css'; class Header extends Component { render() { return ( <header className="page-header-top"> <Container> <div className="page-logo" > <a href="http://xn--l3cah2ct3d5ab7r.com/"> <img src={brand} className="is-brand" title="ทัวร์ดีดี" alt="ทัวร์ดีดี" /> </a> </div> <div className="social-contact"> <ul className="nav-social"> <li className="facebook-ico"> </li> <li className="instagram-ico"> </li> <li className="line-ico"> </li> </ul> <div className="header-license"> <a href="http://xn--l3cah2ct3d5ab7r.com/license"> เลขที่ใบอนุญาต 11/08551</a> </div> </div> </Container> </header> ) } } export default Header;<file_sep>import React, { Component } from 'react'; import { Button,} from 'reactstrap'; import PropTypes from 'prop-types'; class _Collapse extends Component { constructor(props) { super(props); this.state = { show: true, status: 'Closed' }; } static propTypes = { show: PropTypes.bool, //รับค่า true , false เพื่อกำหนดว่าจะแสดง Modal หรือไม่ onConfirm: PropTypes.func, }; handleSelect = (params_id)=>{ this.props.handleSelect(params_id) } //กำหนด Default Props static defaultProps = { show: true, }; render() { const {data} = this.props let PropertiesRender = []; {data && data.map(function(e){ if(e.condition_value){ PropertiesRender =[...PropertiesRender, <tr key={e.condition_id} className="no-border animated fadeInDown"> <td colSpan="3" className="text-align-left">{e.condition_name}</td> <td colSpan="3" className="text-align-right">{`${numberWithCommas(e.condition_value)}`}</td> </tr> ] }else{ PropertiesRender =[...PropertiesRender, <tr key={e.condition_id} className="no-border animated fadeInDown"> <td colSpan="3" className="text-align-left">{e.condition_name}</td> </tr> ]} })} if(this.state.show){ return [ <tr key={0} className="no-border animated fadeInDown" > <td colSpan="6"> ราคา </td> </tr>, ...PropertiesRender, <tr key={1}><td colSpan="6"><div style={{paddingBottom:'1rem'}}><Button onClick={()=>{this.handleSelect(this.props.plan_id)}} color="info" width="100%" size="lg" block>จองทัวร์นี้</Button></div></td></tr> ] }else{ return false; } } } export default _Collapse; function numberWithCommas (x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); }<file_sep>import React from 'react'; import { FormGroup, Label, Input, FormFeedback } from 'reactstrap'; const renderField = ({InputGroupAddon,InputGroup,Button, input, label, type, textarea, autoFocus, option, meta: { touched, error } }) => { const textareaType = <Input {...input} type="textarea" placeholder={label} />; const inputType = <Input {...input} placeholder={label} type={type} autoFocus={autoFocus} invalid={touched && error ? true : false} />; if (type === "select") { return ( <FormGroup> <Label for={input.id}>{label}</Label> <Label for={input.id}>{label}</Label> <Input {...input} multiple> {option && option.map((value, index) => { return <option key={value.id} value={value.id}>{value.label}</option> })} </Input> {touched && error && <FormFeedback tooltip>{error}</FormFeedback>} </FormGroup> ) } else if (type === "number") { return ( <FormGroup> <Label for={input.id}>{label}</Label> <Input {...input} type={type} autoFocus={autoFocus} invalid={touched && error ? true : false} /> {touched && error && <FormFeedback tooltip>{error}</FormFeedback>} </FormGroup> ) } else { return ( <FormGroup> <Label for={input.id}>{label}</Label> {textarea ? textareaType : inputType} {touched && error && <FormFeedback tooltip>{error}</FormFeedback>} </FormGroup> ) } } export default renderField;<file_sep>import React, { Component } from 'react' import { Container } from 'reactstrap' import FirstPage from './Presentational/FirstPage'; import SecondPage from './Presentational/SecondPage'; import ThirdPage from './Presentational/ThirdPage'; import { loadPeriod } from '../../../../redux/actions/periodActions' import { connect } from 'react-redux' class Period extends Component { constructor(props) { super(props) this.state = { Wizardpage: 1, Pessenger: null, Amount: 0 } this.nextPage = this.nextPage.bind(this) this.pessengerOpen = this.pessengerOpen.bind(this) } async componentDidMount() { await this.props.dispatch( loadPeriod( this.props.match.params.period ) ) } nextPage() { this.setState({ Wizardpage: this.state.Wizardpage + 1 }) } pessengerOpen(id) { const { Pessenger } = this.state if (id === Pessenger) { this.setState({ Pessenger: null }) } else { this.setState({ Pessenger: id }) } } componentDidUpdate(prevProps) { if (this.props.period.data !== prevProps.period.data) { this.setState({ Pessenger: prevProps.period.data }) } } render() { const { Wizardpage, Pessenger, Amount } = this.state const { period,bookingCreate } = this.props return ( <div> <Container> {Wizardpage === 1 && <FirstPage cursor={Pessenger} collapse={this.pessengerOpen} data={period.data} match={this.props.match.params.period} onSubmit={this.nextPage} />} {Wizardpage === 2 && <SecondPage nextPage={this.nextPage} data={period.data}/>} {Wizardpage === 3 && <ThirdPage booking={bookingCreate.data} />} </Container> </div> ) } } const mapStateToProps = (state, ownProps) => { return { period: state.periodReducers.period, bookingCreate:state.bookingReducers.bookingCreate, } } export default connect(mapStateToProps)(Period)<file_sep>const renderMembers = ({ fields, }) => ( <ul> {fields.map((member, index) => <li key={index}> <Field name={`${member}.firstName`} type="text" component={renderField} label="First Name"/> <Field name={`${member}.lastName`} type="text" component={renderField} label="Last Name"/> <FieldArray name={`${member}.hobbies`} component={renderHobbies}/> </li> )} </ul> )
b5d4f33b72c592dd6534c18beb94cff51fbbe3c7
[ "JavaScript" ]
13
JavaScript
TOURDD/tourdd.customer_service
4bf7e78ff95e75854e9511eb175f09e1ba1137bf
f38b5865e0890e0346aefad2d2412207be9b0720
refs/heads/master
<repo_name>mksmpc/q-expert_IPR<file_sep>/features/support/utils/browser_utils.rb def initialization_browser(scenario) @caps = Selenium::WebDriver::Remote::Capabilities.chrome(Settings.caps) @browser = Selenium::WebDriver.for(:chrome, desired_capabilities: @caps) @browser.manage.window.maximize end def screenshot time = Time.now.strftime('%Y-%m-%d_%H-%M-%S') filename = 'report_files/' + "#{time}.png" @browser.save_screenshot(filename) embed(filename, 'image/png') end def quit_browser @browser.quit end<file_sep>/features/support/utils/db_utils.rb def db_connect @connection = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "<PASSWORD>", :database => "cucumber") end def db_disconnect @connection.close end def db_record_step(scenario, step, error = nil) error_block = error ? "'fail', '#{error}'" : "'pass', NULL" values = "now(), '#{scenario}', '#{step}', #{error_block}" table = "log_time, scenario, step, status, error" @connection.query("INSERT INTO AutotestLog (#{table}) VALUES (#{values});") end<file_sep>/Readme.md ## Тестирование REST-сервиса http://petstore.swagger.io В этой главе тебе предстоит протестировать REST-сервис. Для начала перейди по ссылке http://petstore.swagger.io. Изучи инструмент Swagger, т.к. это один из самых современных инструментов описания REST-сервисов. Естественно, тестировать всю функциональность сервиса не имеет смысла. Твоя задача – протестировать следующую функциональность: 1. получение списка животных по статусу; 2. создание животного; 3. создание заказа на животное; 4. обновление информации по животному; 5. удаление животного; 6. удаление заказа на животное. Все запросы выполнять без использования авторизации. Составление тест-кейсов лежит на тебе (используй техники тест-дизайна). Вышеописанный функционал должен быть протестирован в полном объёме. ### Запуск браузера Google Chrome как отдельный сценарий Создай отдельный сценарий с запуском браузера Google Chrome и открытием страницы https://ya.ru. Автотест должен проверить, что элемент поиска доступен на странице. Если элемент не найден, сделай скриншот и приложи его к отчёту Cucumber. Ожидания используй неявные. При этом браузер Google Chrome должен быть портативным (запускаемым без установки на компьютере). Это делается для того, чтобы постоянные обновления браузера не ломали автотесты (при каждом обновлении браузера нужно будет использовать новую версию chromedriver). Портативный Google Chrome положи в файлы проекта и выкачивай его на GIT. ### Отчёт [файл отчёта](report_files/report_example.html) Отчёт о тестировании должен представлять из себя Cucumber отчёт. В нём должны быть явно отражены твои Cucumber сценарии и шаги. Продумай логи автотестов, чтобы было проще отлавливать дефекты. Например, выводи все запросы к сервису в лог автотеста (Cucumber отчёт + вывод в консоль). Также полный отчёт должен быть отражён в БД. Для этого создай свою БД произвольной структуры. В ней расположи таблицу AutotestLog с пятью столбцами: Время логирования, Название сценария, Название шага, Результат выполнения шага, Ошибка (может быть NULL). После каждого шага автотеста, в БД должна создаваться запись о статусе выполнения тестирования текущего шага. Столбец «Ошибка» заполняется только в том случае, если статус тестирования текущего шага упало с ошибкой. В остальных случаях столбец заполняется NULL. <file_sep>/features/support/utils/other_utils.rb def table_to_hash(table) hash = {} table.hashes.each do |row| hash[row['key'].to_sym] = row['value'] end hash end <file_sep>/features/step_definitions/pet_steps.rb When(/^Создали животное с id = (\d+)$/) do |id| @headers_hash.merge!({"Content-Type" => "application/json"}) @payload = JSON.generate({id: "#{id}"}) step("Отправили POST на /pet") end When(/^Создали заказ с id = (\d+)$/) do |id| @headers_hash.merge!({"Content-Type" => "application/json"}) @payload = JSON.generate({id: "#{id}"}) step 'Отправили POST на /store/order' end When(/^Сгенерировали данные животного с параметрами$/) do |table| params = table_to_hash table @generated_data = generate_random_pet params puts "Generate animal: #{@generated_data} \r\n with params: #{params}" end When(/^Сгенерировали данные животного$/) do @generated_data = generate_random_pet puts "Generate animal: #{@generated_data}" end When(/^Сохранили ID животного из ответа$/) do @pet_id = JSON.parse(@response.body)['id'] puts "Save pet ID: #{@pet_id}" end When(/^Получили животного по сохраненному ID$/) do @payload = nil puts "Get animal by ID: #{@pet_id}" step "Отправили GET на /pet/#{@pet_id}" end When(/^Добавили ID животного в сгенерированные данные$/) do @generated_data.merge!({id: @pet_id}) puts "Merge ID #{@pet_id} into\r\n #{@generated_data}" end When(/^Создали случайное животное$/) do step 'Сгенерировали данные животного' step 'Добавили сгенерированные данные в тело запроса' step 'Отправили POST на /pet' end When(/^Сохранили данные животного в переменную (.+)$/) do |variable_name| puts "Save into: #{variable_name} \r\n #{@generated_data}" @variables[variable_name] = @generated_data end When(/^Проверили, что данные животного из переменной ([^\s]+) и ответ с сервера отличаются$/) do |variable_name| puts "Compare data from #{variable_name} with response" json_response = JSON.parse(@response.body, :symbolize_names => true) expect(@variables[variable_name]).not_to eq(json_response.reject { |k| k == :id }) end<file_sep>/features/support/pages/yandex_page.rb class YandexPage include PageObject page_url 'https://ya.ru' text_field(:search_bar, id: "text") end <file_sep>/features/step_definitions/yandex_steps.rb When(/^Открыли страницу Яндекса$/) do visit YandexPage end When(/^Проверили, что присутствует форма поиска$/) do on YandexPage do |page| expect(page.search_bar?).to be true end end<file_sep>/features/step_definitions/rest_steps.rb When(/^Отправили (GET|POST|DELETE|PUT) на ([^"]*)$/) do |rest_method, urn| url = Settings.petstore.host + urn @response = send_rest(rest_method, url, headers: @headers_hash, payload: @payload) end When(/^Добавили в Headers:$/) do |table| @headers_hash = table_to_hash table end Then(/^Проверяем статус код == ([^"]*)$/) do |status_code| expect(status_code.to_s).to eq(@response.code.to_s) end When(/^Проверяем, что ответ пуст$/) do expect(@response.body).to be_empty end When(/^Указали содержимое файла (.*) в качестве тела запроса$/) do |file_path| @payload = File.read("files/#{file_path}") end Then(/^Проверили, что сгенерированные данные и ответ с сервера равны$/) do expect(@generated_data).to eq(JSON.parse(@response.body, :symbolize_names => true)) end When(/^Добавили сгенерированные данные в тело запроса$/) do @payload = JSON.generate @generated_data end<file_sep>/features/support/env.rb require 'cucumber' require 'rest-client' require 'config' require 'rspec/core' require 'rspec/expectations' require 'jsonpath' require 'selenium-webdriver' require 'page-object' require 'page-object/page_factory' require 'mysql2' require 'random-word' require 'i18n' World(PageObject::PageFactory) Selenium::WebDriver.logger.level = :error Selenium::WebDriver::Chrome.driver_path = "browsers/chromedriver.exe" env = ENV.fetch('ENV', 'LOCAL') puts "ENV = #{env}" Config.load_and_set_settings(Config.setting_files('config', env.downcase)) puts 'SYSTEM TIME = ' + Time.now.to_s<file_sep>/features/support/utils/generator_utils.rb def generate_random_pet(params = nil) pet = { category: { id: rand(9999), name: RandomWord.nouns.next }, name: RandomWord.nouns.next, photoUrls: random_urls, tags: random_tags, status: random_status } if params pet.merge! params end pet end def random_tags size = rand 10 tags = Array.new(size) tags.map! do |tag| tag = { id: rand(99999), name: RandomWord.nouns.next } end tags end def random_status statuses = %w[available pending sold] statuses.sample end def random_urls urls = %w[https://picsum.photos/200 https://picsum.photos/200/300] if rand > 0.7 return [] end urls.sample(1 + rand(urls.count)) end def random_date Time.at(rand * Time.now.to_i) end<file_sep>/features/step_definitions/json_steps.rb When(/^Парсим ответ в JSON$/) do @response_json = @json_path ? (@json_path.on @response) : JSON.parse(@response) expect(@response_json).not_to be_nil end When(/^Указываем jsonPath до конечного элемента: "([^"]+)"$/) do |json_path| @json_path = JsonPath.new("#{json_path}") end Then(/^Проверяем, что в ответе присутствует поле ([^"]+)$/) do |key| expect(@response_json).to include(key) end Then(/^Проверяем, что в ответе присутствует поле "([^"]+)" со значением "([^"]*)"$/) do |key, value| expect(@response_json).to include(key) expect(@response_json[key]).to eq(value) end When(/^Проверяем, что в каждом элементе присутствует поле "([^"]+)" со значением "([^"]*)"$/) do |key, value| puts "elements count: #{@response_json.length}" @response_json.each do |element| expect(element).to include(key) expect(element[key]).to eq(value) end end When(/^Проверяем, что JSON пуст$/) do expect(@response_json).to be_empty end<file_sep>/features/support/utils/rest_utils.rb def send_rest(method, url, headers: nil, payload: nil) log_request_params(method: method, url: url, headers: headers, payload: payload) response = nil RestClient::Request.execute(method: method, url: url, headers: headers, payload: payload) do |r| response = r end log_response_params response response end # Принимает любой объект и выводит его в консоль def log_request_params(args) puts 'log_request_params =====>' puts args puts '<=====' end # Форматированный вывод ответа на REST запрос def log_response_params(response) puts "log_response_params: #{response.request.url} =======>" puts "response_code: #{response.code}" puts "response_headers: #{response.headers}" puts "response_body: #{response.body}" puts '<=====' end<file_sep>/Gemfile # frozen_string_literal: true source 'https://rubygems.org' gem 'cucumber' gem 'config' gem 'selenium-webdriver' gem 'rspec-core' gem 'rspec-expectations' gem 'rest-client' gem 'jsonpath' gem 'page-object' gem 'mysql2' gem 'random-word'<file_sep>/features/support/hooks.rb Before('@rest') do @headers_hash = Hash.new end Before('@UI') do |scenario| initialization_browser scenario end After('@UI') do screenshot quit_browser end Before() do |scenario| @variables = {} @scenario_name = scenario.name @steps_counter = 0 db_connect end AfterStep do |result, step| @steps_counter += 1 step_name = step.text puts result db_record_step(@scenario_name, step_name) end After() do |scenario| if scenario.failed? error = scenario.exception failed_step_name = scenario.test_steps[@steps_counter] db_record_step(@scenario_name, failed_step_name, error) end db_disconnect end<file_sep>/browsers/GoogleChromePortable/App/AppInfo/installer.ini [DownloadFiles] DownloadURL=https://dl.google.com/release2/chrome/AIHcSO5F2NZdUg_Cy-Cbgy8_84.0.4147.89/84.0.4147.89_chrome_installer.exe DownloadName=Google Chrome (Stable) DownloadFilename=84.0.4147.89_chrome_installer.exe DownloadMD5=50bf8fbac5eb9f540b3cf6b33bff744f AdditionalInstallSize=182000 DoubleExtractFilename=chrome.7z DoubleExtract1To=App DoubleExtract1Filter=Chrome-bin\** [DirectoriesToPreserve] PreserveDirectory1=App\Chrome-bin\Plugins PreserveDirectory2=App\Chrome-bin\Dictionaries
c99092c0b270925b80cdd4b513ec32bd7b463f2e
[ "Markdown", "Ruby", "INI" ]
15
Ruby
mksmpc/q-expert_IPR
16ddfb87c6f25bc60a319d83d950f7c7f045156c
8076ddf575279ea3223873daf7252069b0322c76
refs/heads/master
<repo_name>pvarsh/applied_data_science<file_sep>/lab-2/code/cleaner_animals.py import os import glob from PIL import Image import ExifTags def changeType(img): im = Image.open(img) first = img.split(".")[0] im.save(first+".png") def resize(img, path_out = ""): #print 'a' im = Image.open(img).convert('LA') w,h = im.size newIm = im.resize((40,40)) first = img.split(".")[-2].split("/")[-1] #print '\naaaa: ', first #print '\n' newIm.save(path_out + first + ".png") ### alligator print "########\n alligator \n##########" path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/alligator/" path_out = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/alligator_proc/" images = glob.glob(path_in + "*.jpg") images = images + glob.glob(path_in + "*.JPG") images = images + glob.glob(path_in + "*.png") for image in images: print image resize(image, path_out) ### cat print "########\n cat \n##########" path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/cat/" path_out = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/cat_proc/" images = glob.glob(path_in + "*.jpg") images = images + glob.glob(path_in + "*.JPG") images = images + glob.glob(path_in + "*.png") for image in images: print image resize(image, path_out) ### dog print "########\n dog \n##########" path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/dog/" path_out = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/dog_proc/" images = glob.glob(path_in + "*.jpg") images = images + glob.glob(path_in + "*.JPG") images = images + glob.glob(path_in + "*.png") for image in images: print image resize(image, path_out) ### gorilla print "########\n gorilla \n##########" path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/gorilla/" path_out = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/gorilla_proc/" images = glob.glob(path_in + "*.jpg") images = images + glob.glob(path_in + "*.JPG") images = images + glob.glob(path_in + "*.png") for image in images: print image resize(image, path_out) ### giraffe print "########\n giraffe \n##########" path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/giraffe/" path_out = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/animals/giraffe_proc/" images = glob.glob(path_in + "*.jpg") images = images + glob.glob(path_in + "*.JPG") images = images + glob.glob(path_in + "*.png") for image in images: print image resize(image, path_out) <file_sep>/assignment_3/hw3.py ############################## # Applied Data Science # HW 3 # <NAME> ############################## import numpy as np import pandas as pd import matplotlib.pyplot as plt from scipy import stats from math import ceil import csv # set up paths to data, tables, figures directories hwpath = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/assignment_3/" datapath = hwpath + "data/" tablespath = hwpath + "tables/" figurespath = hwpath + "figures/" ## data filename for problem 1 grilFile = datapath + "griliches.dta" ## read data df = pd.read_stata(grilFile) ## columns for problem 1b cols1b = ['rns', 'mrt', 'smsa', 'med', 'iq', 'kww', 'age', 's', 'expr', 'lw'] cols1c = ['rns', 'mrt', 'smsa', 'kww', 'expr', 'lw'] ## output description to screen print df[cols1b].describe() ## output description to csv df[cols1b].describe().to_csv(tablespath + "table1b.csv") ## 1.c. plots def scPlots(dfIn): # makes scatter plots of all columns against last columns # get column names for all but last column cols1c = list(dfIn.columns.values)[0:-1] # summary stats for dfIn dfSummary = dfIn.describe() # set y limits ymin, ymax = dfSummary['lw'][[3,-1]] ywidth = ymax - ymin ymin, ymax = ymin - 0.05 * ywidth, ymax + 0.05 * ywidth #cols1c = ['rns', 'mrt', 'smsa', 'kww', 'expr'] #df1c = df[cols1c].describe() #ymin, ymax = df[cols1b].describe()['lw'][[3,-1]] #ywidth = ymax - ymin #ymin, ymax = ymin - 0.05 * ywidth, ymax + 0.05 * ywidth fig = plt.figure() nplots = len(cols1c) for col in cols1c: plt.plot(dfIn[col], dfIn['lw'], 'co') plt.xlabel(col) plt.ylabel('log wage') xmin, xmax = dfSummary[col][[3, -1]] xwidth = xmax - xmin xmin, xmax = xmin - 0.05 * xwidth, xmax + 0.05 * xwidth plt.axis([xmin, xmax, ymin, ymax]) plt.show() def scPlotsFig(dfIn, ncols = 3, fileOut = None, outFormat = 'png', linReg = False, suptitle = None): # makes scatter plots of all columns against last columns on one figure # parameters: # dfIn: data frame containing m columns, # the first m-1 columns will be plotted against mth column # ncols: number of columns in figure # fileOut: figure output file name with path. default will print to screen # outFormat: file format to print to. default will print to 'png' # linReg: include linear regression lines (True/False) # TODO: parse fileOut to extract format # TODO: change 'lw' in subsetting to last column that does not depend on name # get column names for all but last column indepCols = list(dfIn.columns.values)[0:-1] # summary stats for dfIn dfSummary = dfIn.describe() # set y limits ymin, ymax = dfSummary['lw'][[3,-1]] ywidth = ymax - ymin ymin, ymax = ymin - 0.1 * ywidth, ymax + 0.1 * ywidth # create figure fig = plt.figure() # calculate number of rows and plots per row print "# columns:", ncols nplots = len(indepCols) print "# plots: ", nplots nrows = int(ceil(float(nplots)/ncols)) print "# rows: ", nrows # create plots in fig for i, col in enumerate(indepCols): subPlotPosition = int(str(nrows) + str(ncols) + str(i+1)) fig.add_subplot(subPlotPosition) plt.plot(dfIn[col], dfIn['lw'], linestyle = 'None', marker = 'o', fillstyle = 'none', color = 'c') # add x-axis annotation plt.xlabel(col) # y-axis label only for first plot in each row if i % ncols == 0: plt.ylabel('log wage') xmin, xmax = dfSummary[col][[3, -1]] xwidth = xmax - xmin xmin, xmax = xmin - 0.1 * xwidth, xmax + 0.1 * xwidth plt.axis([xmin, xmax, ymin, ymax]) # add regression line if linReg == True: regOut = stats.linregress(dfIn[col], dfIn['lw']) plt.plot([xmin, xmax], [regOut[0]* v + regOut[1] for v in [xmin, xmax]], linestyle='-', linewidth = 2, color = '#EE9A00') # adjust space between plots plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=.3, hspace=.5) # add figure suptitle if suptitle != None: plt.suptitle(suptitle) # print to screen or to file if fileOut != None: plt.savefig(fileOut, format = outFormat) else: plt.show() ## Problem 1c, 1d. # print to file scPlotsFig(df[cols1c], ncols = 2, fileOut = figurespath + "fig1c.pdf", outFormat = 'pdf', linReg = True, suptitle = "Problem 1b, 1c") # print to screen #scPlotsFig(df[cols1c], ncols = 2, linReg = True, suptitle = "Problem 1b, 1c") ## Problem 1d p values for col in cols1c[:-1]: slope, intercept, rValue, pValue, stdErr = stats.linregress(df[col], df[cols1c[-1]]) print col.upper() print "slope, stdErr, P Value: %f, %f, %f" %(slope, stdErr, pValue) print "(%f, %f)" %(slope - 2*stdErr, slope + 2*stdErr) ## Problem 1e. 95%CI degFree = len(df['lw']) slope, intercept, rvalue, pvalue, stdErr = stats.linregress(df.s, df.lw) t_quant95 = stats.t.ppf([0.025, 0.975], degFree) print "Estimated model: lw = %4.3f + %4.3f S" %(intercept, slope) print "95%% CI for b_1: (%f, %f)" %(slope + stdErr * t_quant95[0], slope + stdErr * t_quant95[1]) #scPlotsFig(df[cols1c], ncols = 3, linReg = True) #scPlots(df[cols1b]) #fout = "table1b.csv" #with open(fout, 'r') as f: # writer = csv.writer(f) # writer.writerows(df[cols1b].describe() #x = {'a': [1,2,3], # 'b': ['foo']*3, # 'd': np.array([3,2,1], dtype = 'int32')} #print x # #df2 = pd.DataFrame(x) #print df2.head() #print df2.dtypes #print "indexaaaaa: " #print df2.index #print "columnsasdfasdf: " #print df2.columns #print "valuesdfasdjf: " #print df2.values <file_sep>/lab-2/code/facial_rec_two_out.py from pybrain.datasets.supervised import SupervisedDataSet from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure import SigmoidLayer from pybrain.structure import SoftmaxLayer import cv2 import glob import os import random def loadImage(path): im = cv2.imread(path) return flatten(im) def flatten(x): result = [] for el in x: if hasattr(el, "__iter__") and not isinstance(el, basestring): result.extend(flatten(el)) else: result.append(el) return result def print_f_list(flist, name = ""): print "\n### ", name for f, _ in flist: print f.split('/')[-1] if __name__ == "__main__": path_pos = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/faces/my-face/resized/" path_neg = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/other_faces_resized/" # truth:positive true_val = (1,0) false_val = (0,1) # making training set of positive images files_pos = [(f, true_val) for f in glob.glob(path_pos + "*.png")] random.shuffle(files_pos) splt = int(len(files_pos) * 2.0/3) files_pos_train = files_pos[:splt] files_pos_test = files_pos[splt:] # making training set of negative images files_neg = [(f, false_val) for f in glob.glob(path_neg + "*.png")] random.shuffle(files_neg) splt = int(len(files_neg) * 2.0/3) files_neg_train = files_neg[:splt] files_neg_test = files_neg[splt:] print_f_list(files_neg_train, "files_neg_train") print_f_list(files_neg_test, "files_neg_test") print_f_list(files_neg, "files_neg") # putting together training and test sets train = files_pos_train + files_neg_train test = files_pos_test + files_neg_test random.shuffle(train) random.shuffle(test) # first image to start the training set f, truth = train.pop() t = loadImage(f) # build network net = buildNetwork(len(t), int(.05*len(t)), int(0.05*len(t)), 2, bias = True, outclass = SoftmaxLayer) # initialize data set ds = SupervisedDataSet(len(t), 2) ds.addSample(t, truth) # add the rest of elements to data set for img, truth in train: print truth ds.addSample(loadImage(img), truth) # train the network trainer = BackpropTrainer(net, ds) error = 1 # was 10 iteration = 0 while error > 0.0001: # was 0.0001 error = trainer.train() iteration += 1 print "Iteration: {0} Error {1}".format(iteration, error) for img, truth in test: result = net.activate(loadImage(img)) print "Result (%2.4f, %2.4f): (%2.4f, %2.4f)" %(truth[0], truth[1], result[0], result[1]) # print "\nResult (N): ", net.activate(loadImage('pic/face_4copy.png')) # print "\nResult (Y): ", net.activate(loadImage('pic/image_9copy.png')) # print "\nResult (Y): ", net.activate(loadImage('pic/image_10copy.png')) # print "\nResult (N): ", net.activate(loadImage('pic/face_3copy.png')) # print "\nResult (Y): ", net.activate(loadImage('pic/image_15copy.png')) <file_sep>/lab-1/MultipleLinearRegression-master/testingNormality.py import pandas as pd from scipy import stats import numpy as np df = pd.read_csv("trafficking_data.csv") print stats.mstats.normaltest(df["gdp"]), "gdp" print stats.mstats.normaltest(df["Adult victims"]), "Adult victims" <file_sep>/lab-2/code/not1.py #learn XOR with a nerual network with saving of the learned paramaters import pybrain from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer import pickle if __name__ == "__main__": ds = SupervisedDataSet(2, 1) ds.addSample( (0,0) , (1,)) ds.addSample( (1,0) , (0,)) net = buildNetwork(2, 4, 1, bias=True) trainer = BackpropTrainer(net, learningrate = 0.01, momentum = 0.99) trainer.trainOnDataset(ds, 3000) trainer.testOnData() print net.activate((1,0)) print net.activate((1,0)) print net.activate((0,0)) print net.activate((0,0)) <file_sep>/eric-schles/MultipleLinearRegression-master/intro_pandas.py import pandas as pd import numpy as np import re df = pd.read_csv("trafficking_data.csv") #swapping out values print df[["gdp","Adult victims"]] #methods of replacement df_replace = df.replace(np.nan,0) print df_replace print df.interpolate() <file_sep>/playing with neural net/sine_neuralnet.R #install.packages("neuralnet") #library(neuralnet) set.seed(123) k = 300 x = seq(0, 20, length.out=k) y = sin(x) + rnorm(k, 0, .5) df = cbind(x, y) plot(x, y, pch = 19, cex = 0.1) nnet1 = neuralnet(y~x, data = df, hidden = c(2,5)) pred.net = prediction(nnet1) str(pred.net) y.pred = pred.net$rep1[,2] lines(x, y.pred) <file_sep>/examples/linear-regression-scipy.py # Linear example regression using scipy # From: http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html from scipy import stats import numpy as np from matplotlib import pyplot as plt np.random.seed(1234) x = np.random.random(10) y = np.random.random(10) slope, intercept, r_value, p_value, std_err = stats.linregress(x,y) plt.plot(x, y, 'co') plt.xlim(-.1, 1.1) plt.ylim(-.1, 1.1) plt.show() <file_sep>/lab-2/code/cleaner.py import os import glob from PIL import Image import ExifTags print 'aaa' def changeType(img): im = Image.open(img) first = img.split(".")[0] im.save(first+".png") def resize(img, path_out = ""): #print 'a' im = Image.open(img).convert('LA') w,h = im.size newIm = im.resize((40,40)) first = img.split(".")[-2].split("/")[-1] #print '\naaaa: ', first #print '\n' newIm.save(path_out + first + "copy.png") #path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/faces/full_size/" path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/faces/my-face/cropped/" path_out = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/faces/my-face/resized/" images = glob.glob(path_in + "*.jpg") images = images + glob.glob(path_in + "*.JPG") images = images + glob.glob(path_in + "*.png") print images for image in images: print image resize(image, path_out) ### NOT MY FACE print "########\n###########\n##########" path_in = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/other_faces/" path_out = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/other_faces_resized/" images = glob.glob(path_in + "*.jpg") images = images + glob.glob(path_in + "*.JPG") images = images + glob.glob(path_in + "*.png") print images for image in images: print image resize(image, path_out) #for image in images: # im = Image.open(image) # for orientation in ExifTags.TAGS.keys(): # print orientation #for image in images: # changeType(image) # #images = glob.glob(path_in + "*.png") #for image in images: # resize(image) <file_sep>/lab-2/code/Untitled0.py # coding: utf-8 # In[56]: import numpy as np import scipy import scipy.stats import matplotlib.pyplot as plt import pybrain from pybrain.structure import SigmoidLayer from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer import pickle import random import math ### inline plotting get_ipython().magic(u'matplotlib inline') ### Generate data random.seed(1234) n = 40 x = [random.gauss(0,1) for i in range(n)] y = [random.gauss(0,1) for i in range(n)] points = [[x[i], y[i]] for i in range(len(x))] ### Get normal quantiles # radius1 = scipy.stats.norm.ppf(4.0/6) # radius2 = scipy.stats.norm.ppf(5.0/6) #print "Radius 1: %4.3f, radius 2: %4.3f" %(radius1, radius2) radius1 = .87 radius2 = 1.45 ### Put points into categories for i in range(len(points)): modulus = math.sqrt(points[i][0]**2 + points[i][1]**2) if modulus < radius1: points[i].append(0) elif modulus < radius2: points[i].append(1) else: points[i].append(2) # z is the list of categories z = [points[i][2] for i in range(len(points))] # xi, yi (i = 0, 1, 2) are lists of x and y coordinates of points in # category i... this is ugly, but I couldn't find a way to plot # with different color for each category x0 = [value[0] for value in points if value[2]==0] y0 = [value[1] for value in points if value[2]==0] x1 = [value[0] for value in points if value[2]==1] y1 = [value[1] for value in points if value[2]==1] x2 = [value[0] for value in points if value[2]==2] y2 = [value[1] for value in points if value[2]==2] print "Length of 0: %d, of 1: %d, of 2: %d" %(len(x0), len(x1), len(x2)) plt.plot(x0, y0, "co") plt.plot(x1, y1, "yo") plt.plot(x2, y2, "go") plt.show() ## training set train= points[:int(0.7*len(points))] test = points[int(0.7*len(points)):] # In[57]: ## build network net = buildNetwork(2, 2, 3, bias = True, outclass = SigmoidLayer) print net ds = SupervisedDataSet(2, 3) for point in train: if point[2] == 0: ds.addSample( (point[0], point[1]), (1,0,0) ) elif point[2] == 1: ds.addSample( (point[0], point[1]), (0,1,0) ) else: ds.addSample( (point[0], point[1]), (0,0,1) ) trainer = BackpropTrainer(net, ds) error = 10 iteration = 0 while error > 0.0001: error = trainer.train() iteration += 1 print "Iteration: {0} Error {1}".format(iteration, error) print "done" # In[52]: ### testing on first 10 test cases for i in range(10): predicted = net.activate((test[i][0], test[i][1])) print str(predicted), test[i][2] #print "True cateogory %d, predicted %d" %(test[i][2], predicted) # In[53]: ### predictions predictions = [] for point in test: print point prediction = net.activate((point[0], point[1])) print prediction predictions.append(np.argmax(prediction)) print predictions # In[ ]: <file_sep>/lab-1/r-code/lab-1.R ### CLEAR rm(list = ls()) ### LIBRARIES ### FUNCTIONS df.hist = function(df, columns = F){ if (columns != F){ for (i in columns){ hist(df[ ,i], main = colnames(df)[i]) } } else { len = dim(df)[2] for (i in 1:len){ if (is.numeric(df[ ,i])){ hist(df[ ,i], main = colnames(df)[i]) } } } } compareLogTransforms = function(countries, y, x){ log.x = log(x) log.y = log(y) infinities = log.x == -Inf | log.y == -Inf trans.df = data.frame(x = log.x[!infinities], y = log.y[!infinities]) plot(x, y, main = "y against x") plot(trans.df$x, trans.df$y, main = "log(y) against log(x)") linmod = lm(log.y[!infinities] ~ log.x[!infinities]) abline(linmod, col = 'red') print(cat("\nP-value", summary(linmod)$coefficients[2, 4]), sep = " ") return(trans.df) } compareLogTransforms1 = function(df, xcol, ycol){ log.df = df[,c(1, xcol, ycol)] print(head(log.df)) exclude = log.df[2] == -Inf | log.df[3] == -Inf | log.df[2] == NaN | log.df[3] == NaN cat("Excluded ", sum(exclude), " rows") # infinities = log.x == -Inf | log.y == -Inf # trans.df = data.frame(x = log.x[!infinities], y = log.y[!infinities]) # plot(x, y, main = "y against x") # plot(trans.df$x, trans.df$y, main = "log(y) against log(x)") # linmod = lm(log.y[!infinities] ~ log.x[!infinities]) # abline(linmod, col = 'red') # print(cat("\nP-value", summary(linmod)$coefficients[2, 4]), sep = " ") # return(trans.df) } a = compareLogTransforms1(traff.df.outRem1, xcol = 7, ycol = 10) ###### READ DATA ## file paths data.path = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-1/data/" traff.data.file = paste0(data.path, "trafficking_data.csv") new.data.file = paste0(data.path, "new.csv") ## read files traff.df = read.csv(traff.data.file, header = TRUE, sep = ",", stringsAsFactors = F) new.df = read.csv(new.data.file, header = TRUE, sep = ",", stringsAsFactors = F) ###### CLEAN UP ## column names colnames(traff.df) = tolower(colnames(traff.df)) ## countries as factor traff.df$country = as.factor(traff.df$country) ## compute all victims traff.df$total.victims = traff.df$child.victims + traff.df$adult.victims ###### OUTLIERS summary(traff.df) ## plot histograms df.hist(traff.df) ###### PREDICTING ADULT VICTIMS names(traff.df) mod1.1 = lm(total.victims ~ . - child.victims - adult.victims, data = traff.df) sum1.1 = summary(mod1.1) print(sum1.1) mod1.2 = lm(total.victims ~ . - child.victims - adult.victims - country, data = traff.df) sum1.2 = summary(mod1.2) print(sum1.2) # The model using all predictors of total victims shows no significance except for country names. # No variables have predictive power. ### Removing outlying countries by persons.prosecuted outlier.cutoff = 10000 traff.df.outRem1 = traff.df[traff.df$persons.prosecuted < outlier.cutoff, ] #outlier Removed mod2.1 = lm(total.victims ~ . -child.victims - adult.victims, data = traff.df.outRem1) sum2.1 = summary(mod2.1) print(sum2.1) mod2.2 = lm(total.victims ~ . -child.victims - adult.victims - country, data = traff.df.outRem1) sum2.2 = summary(mod2.2) print(sum2.2) ### Log scale each predictor # gdp traff.df.outRem1$log.gdp = log(traff.df.outRem1$gdp) traff.df.outRem1[traff.df.outRem1$log.gdp < 0, c(1, 10)] # checking for what countries and values of total.victims log.gdp is negative traff.df.outRem2 = traff.df.outRem1[traff.df.outRem1$log.gdp > 0, ] # removing negative log.gdp log(traff.df.outRem2$total.victims), traff.df.outRem2$log.gdp # persons prosecuted traff.df.outRem1$log.persons.prosecuted = log(traff.df.outRem1$persons.prosecuted) plot(log(traff.df.outRem1$total.victims), log(traff.df.outRem1$persons.prosecuted)) # log - log has a linear trend # total.victims traff.df.outRem1$log.total.victims = log(traff.df.outRem1$total.victims) summary(lm(log.total.victims ~ log.gdp, data = traff.df.outRem1)) mod3.1 = lm(total.victims ~ log.gdp + year + persons.prosecuted + policy.index + x..females.in.primary.education + life.expectancy, data = traff.df.outRem2) summary(mod3.1) colnames(traff.df.outRem2) plot(traff.df.outRem2) ## GDP colored by Country plot plot(traff.df.outRem2$log.gdp, col = traff.df.outRem2$country) plot(traff.df.outRem2$log.gdp, traff.df.outRem2$year, col = traff.df.outRem2$country) a = compareLogTransforms(traff.df.outRem1$country, traff.df.outRem1$gdp, traff.df.outRem1$total.victims) a = compareLogTransforms1(traff.df.outRem1, xcol = 7, ycol = 10) ###### PREDICTING CHILD VICTIMS ###### PREDICTING PROSECUTIONS <file_sep>/lab-1/ipy-code/lab_1_applied_data_science.py # coding: utf-8 ## Applied Data Science: Lab 1 #### Setting up # In[191]: ### imports import math import numpy as np import scipy as sp import pandas as pd from matplotlib import pyplot as plt import statsmodels.api as sm import patsy import re get_ipython().magic(u'matplotlib inline') ### functions ### read file filepath = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-1/data/" traff_file = filepath + "trafficking_data.csv" traff = pd.read_csv(traff_file) ### clean column names colNames = traff.columns.values.tolist() colNames = [col.lower() for col in colNames] colNames = [re.sub(' ', '_', col) for col in colNames] colNames[7] = "percent_fem_educ" traff.columns = colNames ### clean country names cNames = {country: country.title() for country in traff.country} cNames['United Arab Emirate'] = 'United Arab Emirates' cNames['Viet Nam'] = 'Vietnam' traff.country = [cNames[c] for c in traff.country] ### total victims traff['total_victims'] = traff.child_victims + traff.adult_victims columns = traff.columns.values.tolist() columns_reorder = ['country', 'year', 'persons_prosecuted', 'adult_victims', 'child_victims', 'total_victims', 'gdp', 'policy_index', 'percent_fem_educ', 'life_expectancy'] traff = traff[columns_reorder] ### checking columns for missing data print "Missing values in columns:\n", traff.isnull().sum()[traff.isnull().sum() > 0] print traff.shape ### removing missing values traff = traff[traff.child_victims.notnull()] print traff.shape #### Problem 1: Checking predictive power ####### Modeling adult_victims # In[192]: ### All predictors including country names (obviously a bad model) # all_columns = traff.columns.values.tolist() # y, X = patsy.dmatrices('adult_victims ~ country + year + policy_index + percent_fem_educ + life_expectancy', # data = traff, # return_type='dataframe') # everything_bagel = sm.OLS(y, X) # results_everything = everything_bagel.fit() # print results_everything.summary() ### All predictors excluding country names y, X = patsy.dmatrices('adult_victims ~ gdp + year + policy_index + percent_fem_educ + life_expectancy + persons_prosecuted', data = traff, return_type='dataframe') main_effects_fit = sm.OLS(y, X).fit() print main_effects_fit.summary() ### Comparing all bivariates #print traff.columns.values cols = ['year', 'gdp', 'policy_index', 'percent_fem_educ', 'life_expectancy', 'persons_prosecuted'] bivariate_dmatrices = [patsy.dmatrices('adult_victims ~ ' + col, data = traff, return_type = 'dataframe') for col in cols] bivariate_fits = [sm.OLS(dmatrix[0], dmatrix[1]).fit() for dmatrix in bivariate_dmatrices] for fit in bivariate_fits: print '####################' print '####################' print fit.summary() ##### Modeling child_victims # In[193]: ### All predictors excluding country names y, X = patsy.dmatrices('child_victims ~ gdp + year + policy_index + percent_fem_educ + life_expectancy + persons_prosecuted', data = traff, return_type='dataframe') main_effects_fit = sm.OLS(y, X).fit() print main_effects_fit.summary() ### Comparing all bivariates #print traff.columns.values cols = ['year', 'gdp', 'policy_index', 'percent_fem_educ', 'life_expectancy', 'persons_prosecuted'] bivariate_dmatrices = [patsy.dmatrices('child_victims ~ ' + col, data = traff, return_type = 'dataframe') for col in cols] bivariate_fits = [sm.OLS(dmatrix[0], dmatrix[1]).fit() for dmatrix in bivariate_dmatrices] for fit in bivariate_fits: print '####################' print '####################' print fit.summary() ####### Modeling persons_prosecuted # In[194]: ### All predictors excluding country names y, X = patsy.dmatrices('persons_prosecuted ~ gdp + year + policy_index + percent_fem_educ + life_expectancy', data = traff, return_type='dataframe') main_effects_fit = sm.OLS(y, X).fit() print main_effects_fit.summary() ### Comparing all bivariates #print traff.columns.values cols = ['year', 'gdp', 'policy_index', 'percent_fem_educ', 'life_expectancy'] bivariate_dmatrices = [patsy.dmatrices('persons_prosecuted ~ ' + col, data = traff, return_type = 'dataframe') for col in cols] bivariate_fits = [sm.OLS(dmatrix[0], dmatrix[1]).fit() for dmatrix in bivariate_dmatrices] for fit in bivariate_fits: print '####################' print '####################' print fit.summary() #### Problem 2. Removing outliers # In[231]: print traff.columns.values.tolist() cols = ['persons_prosecuted', 'adult_victims', 'child_victims', 'total_victims', 'gdp', 'policy_index', 'percent_fem_educ', 'life_expectancy'] print traff[['country', 'year', 'persons_prosecuted']][traff.persons_prosecuted > 15000] print traff[['country', 'year', 'child_victims']][traff.child_victims > 300] print traff[['country', 'year', 'gdp']][traff.gdp > 0.3*1e13] print traff[['country', 'year', 'policy_index']][traff.policy_index < 2] ### plotting histograms for col in cols: plt.hist(traff[col], bins=15, color='orange') plt.xlabel(col) plt.show() # # for col in cols: # # plt.hist(np.log(traff[col]), bins=15, color='cyan') # # plt.xlabel('log ' + col) # # plt.show() # ### persons_prosecuted outliers # print traff.country[traff.persons_prosecuted > 5000] # traffOutRem = traff[traff.persons_prosecuted < 5000] # print traff.shape # print traffOutRem.shape # ### All predictors excluding country names # y, X = patsy.dmatrices('adult_victims ~ gdp + year + policy_index + percent_fem_educ + life_expectancy', # data = traffOutRem, # return_type='dataframe') # main_effects_fit = sm.OLS(y, X).fit() # print main_effects_fit.summary() # y, X = patsy.dmatrices('child_victims ~ gdp + year + policy_index + percent_fem_educ + life_expectancy', # data = traffOutRem, # return_type='dataframe') # main_effects_fit = sm.OLS(y, X).fit() # print main_effects_fit.summary() # y, X = patsy.dmatrices('total_victims ~ gdp + year + policy_index + percent_fem_educ + life_expectancy', # data = traffOutRem, # return_type='dataframe') # main_effects_fit = sm.OLS(y, X).fit() # print main_effects_fit.summary() ####### Looking at child_victims main effects model. # In[232]: y, X = patsy.dmatrices('child_victims ~ percent_fem_educ + life_expectancy + persons_prosecuted', data = traffOutRem, return_type='dataframe') main_effects_fit = sm.OLS(y, X).fit() print main_effects_fit.summary() #### Problem 3. Log transform ####### Log transofrm and -inf substitution # In[177]: ### log transform # traffNumeric = traffOutRem._get_numeric_data() # traffNumeric = np.log(traffNumeric) # ### change -inf to 1 # traffNumeric[traffNumeric == -np.inf] = 1 # ### change names # names = traffNumeric.columns.values.tolist() # for i in range(len(names)): # names[i] = 'log_' + names[i] # traffNumeric.columns = names # print traffNumeric.head # traffOutRem = pd.concat([traffOutRem, traffNumeric], axis = 0) # In[185]: y, X = patsy.dmatrices('log_child_victims ~ log_gdp + log_life_expectancy + log_percent_fem_educ + log_persons_prosecuted + log_policy_index', data = traffOutRem, return_type = 'dataframe') log_fit = sm.OLS(y, X).fit() print log_fit.summary() # In[241]: ### Reading internet penetration by country print filepath penetration_file = "internet-penetration-by-country.csv" penetration = pd.read_csv(filepath + "internet-penetration-by-country.csv") # In[ ]: <file_sep>/sound/cmydlarz-gx_5004-47fb49c6a23b/README.md #CUSP GX 5004 Sound Analytics GIT repository to store module content<file_sep>/examples/linear-regression-statsmodels.py # Linear regression examples # Code from: http://connor-johnson.com/2014/02/18/linear-regression-with-python/ # Doesn't run: fails to import statsmodels module import numpy as np import pandas from pandas import DataFrame, Series import statsmodels.formula.api as sm from sklearn.linear_model import LinearRegression import scipy, scipy.stats data_str = '''Region Alcohol Tobacco North 6.47 4.03 Yorkshire 6.13 3.76 Northeast 6.19 3.77 East Midlands 4.89 3.34 West Midlands 5.63 3.47 East Anglia 4.52 2.92 Southeast 5.89 3.20 Southwest 4.79 2.71 Wales 5.27 3.53 Scotland 6.08 4.51 Northern Ireland 4.02 4.56''' d = data_str.split('n') d = [ i.split('t') for i in d ] for i in range( len( d ) ): for j in range( len( d[0] ) ): try: d[i][j] = float( d[i][j] ) except: pass df = DataFrame( d[1:], columns=d[0] ) scatter( df.Tobacco, df.Alcohol, marker='o', edgecolor='b', facecolor='none', alpha=0.5 ) xlabel('Tobacco') ylabel('Alcohol') showplot() #savefig('alcohol_v_tobacco.png', fmt='png', dpi=100)<file_sep>/eric-schles/MultipleLinearRegression-master/testingHomoskedasticity.py import pandas as pd import statsmodels.stats.api as sms import statsmodels.formula.api as smf df = pd.read_csv("trafficking_data.csv") results = smf.ols('df["Adult victims"] ~ df["gdp"] + df["policy index"]',data=df).fit() print sms.het_breushpagan(results.resid, results.model.exog) <file_sep>/eric-schles/MultipleLinearRegression-master/linreg.py import pandas as pd import statsmodels.formula.api as smf import matplotlib.pyplot as plt import statsmodels.api as sm df = pd.read_csv("trafficking_data.csv") results_victims = smf.ols('df["Adult victims"] ~ df["gdp"] + df["policy index"]',data=df).fit() ind_vars = df[["gdp","policy index"]] results_prosecuted = sm.OLS(df["persons prosecuted"], ind_vars).fit() print results_victims.summary() print "Parameters:", results_victims.params print "R^2", results_victims.rsquared print results_prosecuted.summary() print "Parameters:", results_prosecuted.params print "R^2", results_prosecuted.rsquared <file_sep>/assignment_3/plotting_example.py import pandas as pd import numpy as np import matplotlib.pyplot as plt pd.options.display.mpl_style = 'default' ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000)) ts = ts.cumsum() ts.plot() df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) df = df.cumsum() plt.show() #plt.figure(); #df.plot();<file_sep>/assignment_3/submission/hw3-pv629.R library(foreign) library(car) ##### PROBLEM 1 ### a. Read the data. gril = read.dta("/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/assignment_3/data/griliches.dta") ### b. Generate summary statistics (see Python code) ### c. Generate scatter plots (see Python code) ### d. Estimate bivariate linear regressions (see Python code) ### e. Estimate bivariate linear model of lw ~ schooling mod1 = lm(lw~s, data = gril) summary(mod1) confint(mod1) ### f. Estimate a multivariate linear model of lw as a function of variables in (b) cols = c('rns', 'mrt', 'smsa', 'med', 'iq', 'kww', 'age', 's', 'expr', 'lw') gril1 = gril[cols] mod2 = lm(lw ~ ., data = gril1) summary(mod2) # confidence interval confint(mod2)[9, 1:2] ### g. adding age^2 and changing order gril1$agesq = gril1$age^2 colNewOrder = c("rns","mrt","smsa", "med","iq", "kww", "age", "agesq", "s", "expr", "lw") gril1 = gril1[, colNewOrder] ## linear regression with agesq mod3 = lm(lw~., data = gril1) summary(mod3) confint(mod3) ## Plotting schooling vs age and age^2 to understand correlations par(mfcol=c(1,2)) # 1 row 2 columns par(mar=c(5,4,1,1)) # margins plot(jitter(gril1$age, .8), jitter(gril1$s, .3), pch = 1, ylab = 'Years of schooling (s)', xlab = "Age (age)") abline(lm(s~age, data = gril1), col = 'orange2', lwd = 2) par(mar=c(5,3,1,2)) plot(jitter(gril1$agesq, 8), jitter(gril1$s, .3), pch = 1, ylab = '', xlab = "Age^2 (agesq)") abline(lm(s~agesq, data = gril1), col = 'orange2', lwd = 2) title("Age, age squared, and schooling", outer = T) ## Correlations of schooling, age, age^2 cor(gril1[c('s', 'age', 'agesq')]) ###### Problem 2. ### a. set.seed(12334) x1 = rnorm(1e4) x2 = rnorm(1e4) epsilon = rnorm(1e4) beta0 = 1 beta1 = 1 beta2 = 1 y = beta0 + beta1 * x1 + beta2 * x2 + epsilon mod1 = lm(y~x1) summary(mod1) mod2 = lm(y~x1 + x2) summary(mod2) ### b. par(mfrow = c(1,1)) set.seed(12334) z = rnorm(1e4) v = rnorm(1e4, 0, 1) w = rnorm(1e4, 0, 1) x1 = z + v x2 = -z + w y = 1 + x1 + x2 + rnorm(1e4) ## using least squares fit #mod1 = lsfit(x1, y) #mod1$coef ## using lm mod1 = lm(y~x1) mod1$coef summary(mod1) #smpl = sample.int(1e4, size = 500) #plot(x1[smpl], mod1$resid[smpl]) mod2 = lm(y~x1 + x2) summary(mod2) plot(x1, y) abline(lm(y~x1), col = 'orange2', lwd = 3) abline(h = mean(y), col = 'cyan2', lwd = 2) #plot(x2, y) #plot(x1, x2) ## Well behaved regression x = rnorm(1e4) y = 1 + x + rnorm(1e4) mod1 = lsfit(x, y) mod1$coef plot(x, mod1$resid) plot(y, mod1$resid) ########### PROBLEM 3 ### a. Read data. union = read.dta("/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/assignment_3/data/union.dta") ## strip line ID variable union$idcode = NULL ### b. ## training set and test set union.train = union[union$year >= 70 & union$year <= 78, ] summary(union.train) union.test = union[union$year < 70 | union$year > 78, ] summary(union.test) ## linear model lin.mod1 = lm(union ~ ., data = union.train) summary(lin.mod1) ## logistic model logit.mod1 = glm(union ~ ., data = union.train, family = binomial) summary(logit.mod1) ### c. Predictions threshold = 0.25 lin.prediction = predict(lin.mod1, newdata = union.test) >= threshold logit.prediction = predict(logit.mod1, newdata = union.test, type = "response") >= threshold ### d. ## Making and printing predictions threshold = 0.2 lin.prediction = predict(lin.mod1, newdata = union.test) >= threshold logit.prediction = predict(logit.mod1, newdata = union.test, type = "response") >= threshold cat("Actual union members:", sum(union.test$union)) cat("Predicted with linear probability model:", sum(lin.prediction)) cat("Predicted with logistic model:", sum(logit.prediction)) ## Making and printing predictions threshold = 0.25 lin.prediction = predict(lin.mod1, newdata = union.test) >= threshold logit.prediction = predict(logit.mod1, newdata = union.test, type = "response") >= threshold cat("Actual union members:", sum(union.test$union)) cat("Predicted with linear probability model:", sum(lin.prediction)) cat("Predicted with logistic model:", sum(logit.prediction)) ## Confusion matrices cat("Confusion matrices") table(lin.prediction, union.test$union) table(logit.prediction, union.test$union) ### Distribution of union to non-union sum(union$union) / length(union$union) sum(union.train$union) / length(union.train$union) sum(union.test$union) / length(union.test$union) <file_sep>/video_lectures_project/regression_accuracy_1.py # coding: utf-8 # In[2]: import os import sys import time import numpy as np import scipy.ndimage as nd import matplotlib.pyplot as plt ##### Load all digits in single image # In[3]: img = nd.imread('images/digits.png') nrow, ncol = img.shape[0:2] ##### Reshape and compute averages of each digit # In[4]: nums = img.reshape(50,20,100,20).transpose(0,2,1,3).reshape(5000,20,20) nums_avg = np.array([nums[i*500:(i+1)*500].mean(0) for i in range(10)]) ####### Regressing all numbers on averages # In[5]: PT = nums_avg.reshape(10,400) P = PT.transpose() PTPinv = np.linalg.inv(np.dot(PT,P)) PTyys = [[np.dot(PT, nums[im].flatten()) for im in range(i*500, (i+1)*500)] for i in range(10)] avecs = [[np.dot(PTPinv, PTy) for PTy in PTyys[i]] for i in range(10)] avecsAll = np.array(avecs) ####### Plotting histograms # In[131]: #fig, ax = plt.subplots(num = 0, figsize = (24,16), nrows = 10, ncols = 10, sharex = True) #fig.clf() #fig, ax = plt.subplots(num = 0, figsize = (24,16), nrows = 10, ncols = 10, sharex = True) #for i in range(10): # for j in range(10): # ax[j][i].cla() # ax[j][i].set_xlim(-2,2) # ax[j][i].hist(avecsAll[i, : , j], bins = 10, normed = True) ## if i != 0: ## ax[j][i].set_yticklabels([]) ## else: ## ax[j][i].set_yticks([0, .5, 1, 1.5, 2, 2.5]) ## ax[j][i].set_yticklabels([0, .5, 1, 1.5, 2, 2.5], fontsize = 8) # if j != 9: # ax[j][i].set_xticklabels([]) # else: # ax[j][i].set_xticks([-1.8, 0, 1.8]) # ax[j][i].set_xticklabels([-1.8,0,1.8], fontsize = 8) # ax[j][i].tick_params(axis='y', which='major', labelsize=8) #fig.subplots_adjust(hspace=0) #fig.canvas.draw() #fig.show() figures = [] for i in range(10): fig, ax = plt.subplots(num = i, figsize = (6, 12), nrows = 10, sharex = True) fig.suptitle('Distribution of regression coefficients for ' + str(i)) for j in range(10): ax[j].cla() ax[j].set_xlim(-2.5,2.5) ax[j].hist(avecsAll[i,:,j], bins = 10, normed = True) ax[j].tick_params(axis = 'y', which = 'major', labelsize = 8) ax[j].set_yticklabels([]) ax[j].set_ylabel(j) if j != 9: ax[j].set_xticklabels([]) fig.canvas.set_window_title('Histograms for ' + str(i) + ' digit') figures.append((fig, ax)) #print len(figures) #[fig[0].show() for fig in figures] #### Part 2. Error reports # In[5]: bins = np.arange(11)-0.5 hists = [np.array(np.histogram(np.argmax(avecsAll[i,:,:], axis = 1), bins = bins)[0]) for i in range(10)] successRate = [hists[i][i]/500. for i in range(10)] errorRate = [1 - s for s in successRate] commonError = [np.argpartition(a = hists[i], kth = -2)[-2:-1][0] for i in range(10)] # In[6]: # Printing accuracy, no intercept print " Accuracy for model fit without intercept" for i in range(10): print("{0}% of {1}s were incorrectly identified,".format(int(round(errorRate[i]*100,0)), i) + "the most common guess for those failures was {0}".format(commonError[i])) #### Part 3. Animation ######## Misclassified 1s # ## In[7]: # #errors = [] #classifiedAs = [] # #for i, bad in enumerate(list(np.argmax(avecsAll[1], axis = 1) != 1)): # #print truth, i, argmax(avecsAll[1], axis = 1)[i] # if bad: # errors.append(i) # classifiedAs.append(np.argmax(avecsAll[1], axis = 1)[i]) #classedAs = np.argmax(avecsAll[1], axis = 1)[np.argmax(avecsAll[1], axis = 1) != 1] # #fig1, ax1 = plt.subplots(num=1,figsize=[4,4]) #fig1.subplots_adjust(0,0,1,1) #ax1.axis('off') #im1 = ax1.imshow(nums[0]) #t1 = ax1.text(2, 2, "", fontsize=12, color = 'white') # #fig1.canvas.draw() # #for i in range(len(errors)): # im1.set_data(nums[500+errors[i]]) # t1.set_visible(False) # t1 = ax1.text(2, 2, classifiedAs[i], fontsize=12, color = 'white') # fig1.canvas.draw() # time.sleep(1) ####### Misclassified random 30-second animation # In[41]: badPredictions = np.array([(np.argmax(avecsAll[i], axis = 1) != i) for i in range(10)]).flatten() classifications = np.array([np.argmax(avecsAll[i], axis = 1).flatten() for i in range(10)]).flatten() index = np.arange(5000) whereBad = index[badPredictions] #fig1, ax1 = plt.subplots(num=1,figsize=[4,4]) #fig1.subplots_adjust(0,0,1,1) #fig1.canvas.set_window_title('Misclassified 1s') #ax1.axis('off') #im1 = ax1.imshow(nums[0]) #t1 = ax1.text(2, 2, "", fontsize=12, color = 'white') # In[68]: np.random.shuffle(whereBad) fig2, ax2 = plt.subplots(num = 11, figsize = [4,4]) fig2.subplots_adjust(0,0,1,1) fig2.canvas.set_window_title('Misclassified') ax2.axis('off') im2 = ax2.imshow(nums[whereBad[0]]) t2 = ax2.text(.5,1.5, "Classified as: " + str(classifications[whereBad[0]]), fontsize = 12, color = 'white') #fig1.canvas.draw() fig2.show() #fig1.show() #t0 = time.time() #dt = 0 #i = 1 #while dt < 15: # im2.set_data(nums[whereBad[i]]) # t2.set_visible(False) # t2 = ax2.text(.5,1.5, "Classified as: " + str(classifications[whereBad[i]]), fontsize = 12, color = 'white') # time.sleep(.8) # dt = time.time() - t0 # i += 1 # fig2.canvas.draw() #### Part 4. Regression with intercept # In[15]: PT = nums_avg.reshape(10,400) PT = np.row_stack((PT, np.ones(400))) P = PT.transpose() PTPinv = np.linalg.inv(np.dot(PT,P)) PTyys = [[np.dot(PT, nums[im].flatten()) for im in range(i*500, (i+1)*500)] for i in range(10)] avecs = [[np.dot(PTPinv, PTy) for PTy in PTyys[i]] for i in range(10)] avecsAll = np.array(avecs) PT = nums_avg.reshape(10,400) PT.shape ## In[11]: # #PT = nums_avg.reshape(10,400) #PT = np.row_stack((PT, np.ones(400))) #print "got here" #print "PT.shape", PT.shape #P = PT.transpose() #print "P.shape", P.shape #PTPinv = np.linalg.inv(np.dot(PT,P)) #print "PTPinv.shape", PTPinv.shape #print "nums.flatten.shape:", nums[10].flatten().shape #PTy0 = [np.dot(PT, nums[im].flatten()) for im in range(0*500, (0+1)*500)] #print "PTy0 shape", len(PTy0) #np.dot(PTPinv, PTy0[0]) # #PTyys = [[np.dot(PT, nums[im].flatten()) for im in range(i*500, (i+1)*500)] for i in range(10)] #print "PTyys len:", len(PTyys) #avecs = [[np.dot(PTPinv, PTy) for PTy in PTyys[i]] for i in range(10)] #print "avecs[0][0]:", avecs[0][0].shape #avecsAll = np.array(avecs) #print "avecsAll.shape", avecsAll.shape # # In[12]: aa = np.array([1,2,3,4,5]) #print np.insert(aa, 5, 6) # In[13]: bins = np.arange(11)-0.5 hists = [np.array(np.histogram(np.argmax(avecsAll[i,:,:], axis = 1), bins = bins)[0]) for i in range(10)] successRate = [hists[i][i]/500. for i in range(10)] errorRate = [1 - s for s in successRate] commonError = [np.argpartition(a = hists[i], kth = -2)[-2:-1][0] for i in range(10)] # In[14]: # Printing accuracy wit with intercept print " Accuracy for model fit with intercept" for i in range(10): print("{0}% of {1}s were incorrectly identified,".format(round(errorRate[i]*100,3), i) +\ "the most common guess for those failures was {0}".format(commonError[i])) # In[14]: # In[ ]: <file_sep>/lab-2/code/XOR_linear.py # coding: utf-8 # In[12]: #learn XOR with a nerual network with saving of the learned paramaters import pybrain from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer from pybrain.structure import SigmoidLayer import pickle import random from matplotlib import pyplot as plt if __name__ == "__main__": ds = SupervisedDataSet(2, 1) ds.addSample( (0,0) , (0,)) ds.addSample( (0,1) , (1,)) ds.addSample( (1,0) , (1,)) ds.addSample( (1,1) , (0,)) net = buildNetwork(2, 1, bias=True, outclass = SigmoidLayer) # try: # f = open('_learned', 'r') # net = pickle.load(f) # f.close() # except: trainer = BackpropTrainer(net, learningrate = 0.01, momentum = 0.99) trainer.trainOnDataset(ds, 500) trainer.testOnData() # f = open('_learned', 'w') # pickle.dump(net, f) # f.close() print net.activate((1,1)) print net.activate((1,0)) print net.activate((0,1)) print net.activate((0,0)) testUnif = [(random.uniform(0,1), random.uniform(0,1)) for i in range(1000)] predictions = [] for i in range(len(testUnif)): prediction = net.activate(testUnif[i])[0] predictions.append(prediction) #print predictions x = [pair[0] for pair in testUnif] y = [pair[1] for pair in testUnif] fig = plt.figure() plt.scatter(x,y, c = predictions) fig.savefig('xor.png', dpi = 300) # In[12]: # In[ ]: <file_sep>/assignment-4/assignment_4.rst .. code:: python import numpy as np import scipy as sp from matplotlib import pyplot as plt np.set_printoptions(precision=5, suppress = True) Problem 1.a. .. code:: python maze = [[.5, .5, 0], [.25, .5, .25], [0, .5, .5]] maze = np.array(maze) print "Transition probability matrix:" print maze for power in [2, 5, 10, 25]: print "Transition probabilities after %d steps" %power print np.linalg.matrix_power(maze, power) .. parsed-literal:: Transition probability matrix: [[ 0.5 0.5 0. ] [ 0.25 0.5 0.25] [ 0. 0.5 0.5 ]] Transition probabilities after 2 steps [[ 0.375 0.5 0.125] [ 0.25 0.5 0.25 ] [ 0.125 0.5 0.375]] Transition probabilities after 5 steps [[ 0.26562 0.5 0.23438] [ 0.25 0.5 0.25 ] [ 0.23438 0.5 0.26562]] Transition probabilities after 10 steps [[ 0.25049 0.5 0.24951] [ 0.25 0.5 0.25 ] [ 0.24951 0.5 0.25049]] Transition probabilities after 25 steps [[ 0.25 0.5 0.25] [ 0.25 0.5 0.25] [ 0.25 0.5 0.25]] Problem 1.b. .. code:: python maze = [[1, 0, 0], [.25, .5, .25], [0, 0, 1]] maze = np.array(maze) print "Transition probability matrix with absorbing states:" print maze for power in [2, 5, 10, 25]: print "Transition probabilities after %d steps" %power print np.linalg.matrix_power(maze, power) .. parsed-literal:: Transition probability matrix with absorbing states: [[ 1. 0. 0. ] [ 0.25 0.5 0.25] [ 0. 0. 1. ]] Transition probabilities after 2 steps [[ 1. 0. 0. ] [ 0.375 0.25 0.375] [ 0. 0. 1. ]] Transition probabilities after 5 steps [[ 1. 0. 0. ] [ 0.48438 0.03125 0.48438] [ 0. 0. 1. ]] Transition probabilities after 10 steps [[ 1. 0. 0. ] [ 0.49951 0.00098 0.49951] [ 0. 0. 1. ]] Transition probabilities after 25 steps [[ 1. 0. 0. ] [ 0.5 0. 0.5] [ 0. 0. 1. ]] Problem 1.c. .. code:: python maze = [[ 1, 0, 0, 0, 0], [.25, .5, .25, 0, 0], [ 0, .25, .5, .25, 0], [ 0, 0, .25, .5, .25], [ 0, 0, 0, .5, .5]] maze = np.array(maze) print "Transition probability matrix:" print maze for power in [84, 125]: print "Transition probabilities after %d iterations:" %power print np.linalg.matrix_power(maze, power) .. parsed-literal:: Transition probability matrix: [[ 1. 0. 0. 0. 0. ] [ 0.25 0.5 0.25 0. 0. ] [ 0. 0.25 0.5 0.25 0. ] [ 0. 0. 0.25 0.5 0.25] [ 0. 0. 0. 0.5 0.5 ]] Transition probabilities after 84 iterations: [[ 1. 0. 0. 0. 0. ] [ 0.98153 0.00281 0.0052 0.00679 0.00367] [ 0.96587 0.0052 0.0096 0.01255 0.00679] [ 0.9554 0.00679 0.01255 0.01639 0.00887] [ 0.95173 0.00735 0.01358 0.01774 0.0096 ]] Transition probabilities after 125 iterations: [[ 1. 0. 0. 0. 0. ] [ 0.99624 0.00057 0.00106 0.00138 0.00075] [ 0.99305 0.00106 0.00196 0.00256 0.00138] [ 0.99091 0.00138 0.00256 0.00334 0.00181] [ 0.99017 0.0015 0.00277 0.00361 0.00196]] <file_sep>/bikeshare/code/R/learning_arma.R #install.packages("tseries") #library(tseries) ### Generate a sin wave pi ### Create x x = seq(0, 8*pi, length = 200) ### Create y y = sin(x) + rnorm(length(x), 0, 0.3) ### Plot time series plot.ts(y) ### arma models arma.1 = arma(y, order = c(6,0)) yNA = y yNA[20:23] = NA yNA[50:53] = NA yNA[80:83] = NA yNA[110:113] = NA yNA[140:143] = NA yNA[170:173] = NA plot.ts(yNA) arma.2 = arma(y, order = c(6,0)) summary(arma.2) ### From http://www.statoek.wiso.uni-goettingen.de/veranstaltungen/zeitreihen/sommer03/ts_r_intro.pdf ### Page 17 sim.ar<-arima.sim(list(ar=c(0.4,0.4)),n=1000) sim.ma<-arima.sim(list(ma=c(0.6,-0.4)),n=1000) par(mfrow=c(2,2)) acf(sim.ar,main="ACF of AR(2) process") acf(sim.ma,main="ACF of MA(2) process") pacf(sim.ar,main="PACF of AR(2) process") pacf(sim.ma,main="PACF of MA(2) process") plot(sim.ma) <file_sep>/lab-1/MultipleLinearRegression-master/testingCorrelation.py from scipy.stats.stats import pearsonr import pandas as pd df = pd.read_csv("trafficking_data.csv") print pearsonr(df["persons prosecuted"],df["Adult victims"]) <file_sep>/lab-2/code/and.py #learn XOR with a nerual network with saving of the learned paramaters import pybrain from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer import pickle def buildAndTrain(ds): net = buildNetwork(2, 4, 1, bias=True) # try: # f = open('_learned', 'r') # net = pickle.load(f) # f.close() # except: trainer = BackpropTrainer(net, learningrate = 0.01, momentum = 0.99) trainer.trainOnDataset(ds, 1000) trainer.testOnData() return net if __name__ == "__main__": ds = SupervisedDataSet(2, 1) ds.addSample( (0,0) , (0,)) ds.addSample( (0,1) , (0,)) ds.addSample( (1,0) , (0,)) ds.addSample( (1,1) , (1,)) ntrials = 100 results = [] counter = 0 for i in range(ntrials): net = buildAndTrain(ds) points = [(1,1), (1,0), (0,1), (0,0)] result = [net.activate(point)[0] for point in points] results.append(result) #print result counter += 1 print counter, " of ", ntrials AND = [1, 0, 0, 0] errors = [] counter = 0 for result in results: counter += 1 error = sum([(result[i] - AND[i])**2 for i in range(4)]) if error >= 0.1: print "Iteration %d" %counter print "Error %7.6f" %error for r in result: print "%7.6f" %r <file_sep>/lab-2/code/clean_images.py import os import os.path full_size_path = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/faces/full_size/" resized_path = "/Users/petervarshavsky/Documents/Git_NYU/applied_data_science/lab-2/images/faces/resized/" files = [f for f in os.listdir(full_size_path) if os.path.isfile(os.path.join(full_size_path, f))] print files <file_sep>/video_lectures_project/image_exploration_part1.py # coding: utf-8 # In[1]: import os import sys import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf ####### Functions # In[2]: def initializeRectangle(ax): """ Initiealizes four empty lines and returns them in a list to be used to display bounding rectangle """ return [ax.plot([],[],color = 'white', lw = 0.8, alpha = 0.7)[0] for i in range(4)] def setLineData(lines, upperLeft, lowerRight): """ Takes a list of four lines and upperLeft and lowerRight points for a bounding rectangle sets data for lines to display bounding rectangle """ #line1 x1 = [upperLeft[0], lowerRight[0]] y1 = [upperLeft[1], upperLeft[1]] lines[0].set_data(x1, y1) #line2 x2 = [lowerRight[0], lowerRight[0]] y2 = [upperLeft[1], lowerRight[1]] lines[1].set_data(x2, y2) #line3 x3 = [lowerRight[0], upperLeft[0]] y3 = [lowerRight[1], lowerRight[1]] lines[2].set_data(x3, y3) #line4 x4 = [upperLeft[0], upperLeft[0]] y4 = [lowerRight[1], upperLeft[1]] lines[3].set_data(x4, y4) def histograms(img, fig, ax): #fig.subplots_adjust(0,0,1,1) #ax[0].axis('off') colors = ['red', 'green', 'blue'] for i in range(3): ax[i].cla() ax[i].set_xlim((0,255)) ax[i].hist(img[:,:,i].flatten(), bins = 256, facecolor = colors[i], lw = 0, normed = True) fig.canvas.draw() fig.show() #infile = "images/ml.jpg" dpath, fname = sys.argv[1:3] infile = os.path.join(dpath, fname) img = nd.imread(infile) # In[4]: ### Plot image nrow, ncol = img.shape[:2] ysize = 10. xsize = ysize * float(ncol)/float(nrow) fig1, ax1 = plt.subplots(num = 1, figsize = [xsize, ysize]) #windowLine, = ax1.plot([], [], color = 'white') lines = initializeRectangle(ax1) #rect = Rectangle((-1, -1), 0, 0, facecolor = 'none') #fig1Rect = ax1.add_patch(rect) #rectPoints = [[10, 10], [40, 40], [10, 40], [40, 10]] #rectPatch = plt.Polygon(rectPoints, facecolor = 'none') #ax1.add_patch(rectPatch) fig1.subplots_adjust(0, 0, 1, 1) fig1.canvas.set_window_title('<NAME>') ax1.imshow(img) ax1.axis('off') fig1.canvas.draw() ### Plot histograms fig2, ax2 = plt.subplots(num = 2, nrows = 3, ncols = 1) fig2.canvas.set_window_title('Histograms') histograms(img, fig2, ax2) # In[5]: # Get rectangles from image and update histograms rflag = True while rflag: try: upperLeft, lowerRight = [(int(round(i)), int(round(j))) for i, j in fig1.ginput(2, show_clicks = True)] x = [upperLeft[0], lowerRight[0]] y = [upperLeft[1], lowerRight[1]] if x[0] == x[1] and y[0] == y[1]: histograms(img, fig2, ax2) for line in lines: line.set_visible(False) else: setLineData(lines, upperLeft, lowerRight) for line in lines: line.set_visible(True) histograms(img[upperLeft[1]:lowerRight[1], upperLeft[0]:lowerRight[0], :], fig2, ax2) fig1.canvas.draw() except: rflag = False <file_sep>/assignment_1/assignment_1.R # Numbers from random.org x = c(6,3,6,8,1,3,8,4,9,1) y = c(0,5,3,0,0,6,5,9,3,8) ### Problem 1 problem1 = function(){ cat("PROBLEM 1") # a. plot(x, y, main = "Problem 1.a") # b. cat("\nMean of x is", mean(x)) cat("\nMean of y is", mean(y)) # c. cat("\nVariance of x is", var(x)) cat("\nVariance of y is", var(y)) # d. cat("\nStandard deviation of x is", sd(x)) cat("\nStandard deviation of y is", sd(y)) # e. cat("\nCovariance of x and y is", cov(x,y)) # f. cat("\nCorrelation of x and y is", cor(x,y)) # g. slope = cov(x,y)/var(x) cat("\nThe slope of the regression line is cov(x,y) / var(x) =", slope) new.x = 13 pred.y = mean(y) + slope * (new.x - mean(x)) cat("\nFor x =", new.x, "the point estimate for y is y =", pred.y) } problem1() ### 2. # a. Discrete. The number of rides taken by a resident in a month is a count variable that takes values on the set of natural numbers, which is discrete. # b. Continuous. Bicyclist's speed can take any real value bounded from below by 0 and from above by the speed of light. No particular value of speed has probabily mass, only density. # c. Continuous. Minute variations in lamps and current suggest a continuous variable. If the minute variations are not of interest, then the luminosity measurements can be converted to a discrete variable. # d. Discrete. Assuming bankers cannot receive arbitrarily small fractions of a dollar, the salaries are discrete, however a continuous variable may be more convenient. # e. Discrete. The number of hotels in Manhattan is a count variable. # f. Continuous. Loudness is continuous. # g. Discrete. Coffee can be 'good or bad' or 'very good, good, average, bad, very bad'. One could devise other metrics that would yield a continuous variable. ### 3. #There are several things to consider. #1. If we are arguing that Wall St. bankers have higher salaries compared to general population or some other specific professions, then we need to obtain data about salaries, IQs, and education. #2. If we are trying to explain variation of salaries among Wall St. bankers, then we can try to do it with the given data by looking at scatter plots of salary vs IQ and salary vs education, we can examine correlations, or we can build a linear model. In doing so we should check that IQ and education are not too highly correlated, because high correlation would give unstable estimates. We can do the correlation check manually, or do model comparison using adjusted R^2 or anova. <file_sep>/lab-2/code/logical.py #learn boolean operators with a nerual network with saving of the learned paramaters import sys import pybrain from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer import pickle def buildAndTrain(ds): net = buildNetwork(2, 4, 1, bias=True) trainer = BackpropTrainer(net, learningrate = 0.01, momentum = 0.99) trainer.trainOnDataset(ds, 1000) return net def main(argv): operator = argv[0] ds = SupervisedDataSet(2, 1) if operator == 'and': ds.addSample( (0,0) , (0,)) ds.addSample( (0,1) , (0,)) ds.addSample( (1,0) , (0,)) ds.addSample( (1,1) , (1,)) correct = [1, 0, 0, 0] elif operator == 'or': ds.addSample( (0,0) , (0,)) ds.addSample( (0,1) , (1,)) ds.addSample( (1,0) , (1,)) ds.addSample( (1,1) , (1,)) correct = [1, 1, 1, 0] elif operator == 'nor': ds.addSample( (0,0) , (1,)) ds.addSample( (0,1) , (0,)) ds.addSample( (1,0) , (0,)) ds.addSample( (1,1) , (0,)) correct = [0, 0, 0, 1] elif operator == 'not': ds.addSample( (0,0) , (1,)) ds.addSample( (0,1) , (1,)) ds.addSample( (1,0) , (0,)) ds.addSample( (1,1) , (0,)) correct = [0, 0, 1, 1] ntrials = int(argv[1]) results = [] counter = 0 for i in range(ntrials): net = buildAndTrain(ds) points = [(1,1), (1,0), (0,1), (0,0)] result = [net.activate(point)[0] for point in points] results.append(result) #print result counter += 1 print counter, " of ", ntrials if len(argv) == 3 and argv[2] == "true": for r in result: print "%7.6f" %r errors = [] counter = 0 for result in results: counter += 1 error = sum([(result[i] - correct[i])**2 for i in range(len(points))]) if error >= 0.1: print "Iteration %d" %counter print "Error %7.6f" %error for r in result: print "%7.6f" %r if __name__ == "__main__": if len(sys.argv) >= 3: main(sys.argv[1:]) else: print "Incorrect number of parameters" <file_sep>/lab-2/code/playing_neuralnet.py import numpy as np import scipy as sp import matplotlib.pyplot as plt import pybrain from pybrain.datasets import * from pybrain.tools.shortcuts import buildNetwork from pybrain.supervised.trainers import BackpropTrainer import pickle import random import math #from enthought import chaco random.seed(1234) n = 100 x = [random.uniform(-1,1) for i in range(n)] y = [random.uniform(-1,1) for i in range(n)] points = [[x[i], y[i]] for i in range(len(x))] for i in range(len(points)): modulus = math.sqrt(points[i][0]**2 + points[i][1]**2) if modulus < 0.3: points[i].append(0) elif modulus < 0.6: points[i].append(1) else: points[i].append(2) # z is the list of categories z = [points[i][2] for i in range(len(points))] # xi, yi (i = 0, 1, 2) are lists of x and y coordinates of points in # category i... this is ugly, but I couldn't find a way to plot # with different color for each category x0 = [value[0] for value in points if value[2]==0] y0 = [value[1] for value in points if value[2]==0] x1 = [value[0] for value in points if value[2]==1] y1 = [value[1] for value in points if value[2]==1] x2 = [value[0] for value in points if value[2]==2] y2 = [value[1] for value in points if value[2]==2] plt.plot(x0, y0, "co") plt.plot(x1, y1, "yo") plt.plot(x2, y2, "go") plt.show() ## training set train= points[:int(0.7*len(points))] test = points[int(0.7*len(points)):] ## build network net = buildNetwork(2, 2, 3, bias = True) ds = SupervisedDataSet(2, 3) for point in train: if point[2] == 0: ds.addSample( (point[0], point[1]), (1,0,0) ) elif point[2] == 1: ds.addSample( (point[0], point[1]), (0,1,0) ) else: ds.addSample( (point[0], point[1]), (0,0,1) ) trainer = BackpropTrainer(net, learningrate = 0.01, momentum = 0.99) trainer.trainOnDataset(ds, 1000) print "done" <file_sep>/video_lectures_project/image_manipulation.py # coding: utf-8 # ### Final project for image analysis module # In[1]: import os import sys import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as nd from scipy.ndimage.filters import median_filter as mf ####### Problem 1 # In[2]: img = mf((255 - nd.imread('images/ml.jpg')[::1,::2,::-1]).astype(float), (8, 2, 1)).clip(0,255).astype(np.uint8) ### Explanation: ### 1. nd.imread reaturns a 3D array ### 2. Then subsetting [::2, ::1, ::-1] inverses colors and skips every other column ### 3. 255 - ... converts to negative ### 4. .astype(float) ### 5. mf() applies median filter ### 6. .clip() clips ### 7. .astype(np.uint8) converts to uint nrow, ncol = img.shape[:2] ysize = 10. xsize = ysize * float(ncol)/float(nrow) fig1, ax1 = plt.subplots(num = 1, figsize = [xsize, ysize]) fig1.canvas.set_window_title('modiefied Mona Lisa') fig1.subplots_adjust(0, 0, 1, 1) ax1.axis('off') im1 = ax1.imshow(img) fig1.canvas.draw() plt.show() # In[ ]: <file_sep>/video_lectures_project/README.md Applied Data Science 2014 ========================= <file_sep>/examples/adding-lines-to-plots-hline-vline.py # Adding lines to plots # From http://stackoverflow.com/questions/12864294/adding-an-arbitrary-line-to-a-matplotlib-plot-in-ipython-notebook import numpy as np from matplotlib import pyplot as plt np.random.seed(5) x = np.arange(1, 101) y = 20 + 3 * x + np.random.normal(0, 60, 100) p = plt.plot(x, y, "o") plt.vlines(70,100,250) plt.show()<file_sep>/assignment-4/assignment_4_3.rst .. code:: python ### imports import random import numpy as np import scipy as sp import pandas as pd import statsmodels.api as sm import patsy import csv from matplotlib import pyplot as plt import matplotlib.pylab as pylab ### settings %matplotlib inline pylab.rcParams['figure.figsize'] = 16, 5 # that's default image size for this interactive session np.set_printoptions(precision=5, suppress = True) Problem 3.a. .. code:: python x1 = np.random.normal(0, 1, 1000) x2 = np.random.normal(0, 2, 1000) x4 = np.random.normal(0, 4, 1000) plt.figure(1) plt.subplot(131) plt.ylim((-15, 15)) plt.plot(x4, marker ='>', linestyle = 'None', color = '#ee9a00') plt.subplot(132) plt.ylim((-15, 15)) plt.plot(x2, 'm<') plt.subplot(133) plt.ylim((-15, 15)) plt.plot(x1, 'co') plt.savefig('problem3a.png', bbox_inches='tight') plt.show() .. image:: assignment_4_3_files/assignment_4_3_2_0.png Problem 3.b. .. code:: python #X1 = np.random.normal(0,1,1000) #X2 = np.random.normal(0,1,1000) X_save = np.column_stack([X1, X2]) X1_dm = sm.add_constant(X1) # dm for design matrix fit1 = sm.OLS(X2, X1_dm).fit() print sm.OLS(X2, X1_dm).fit().summary() plt.figure(2) plt.plot(X1, X2, marker = 'o', linestyle = 'None', color = "#ee9a00") plt.plot(X1, fit1.params[0] + fit1.params[1]*X1, 'c-') plt.savefig('problem3b.png', bbox_inches='tight') with open('strange_x.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['const', 'X1', 'X2']) writer.writerows(X_save) .. parsed-literal:: OLS Regression Results ============================================================================== Dep. Variable: y R-squared: 0.008 Model: OLS Adj. R-squared: 0.007 Method: Least Squares F-statistic: 8.435 Date: Sat, 25 Oct 2014 Prob (F-statistic): 0.00376 Time: 18:33:53 Log-Likelihood: -1460.1 No. Observations: 1000 AIC: 2924. Df Residuals: 998 BIC: 2934. Df Model: 1 ============================================================================== coef std err t P>|t| [95.0% Conf. Int.] ------------------------------------------------------------------------------ const -0.0014 0.033 -0.042 0.967 -0.066 0.063 x1 0.0960 0.033 2.904 0.004 0.031 0.161 ============================================================================== Omnibus: 2.243 Durbin-Watson: 2.051 Prob(Omnibus): 0.326 Jarque-Bera (JB): 2.315 Skew: 0.105 Prob(JB): 0.314 Kurtosis: 2.894 Cond. No. 1.02 ============================================================================== .. image:: assignment_4_3_files/assignment_4_3_4_1.png .. code:: python fit1.params .. parsed-literal:: array([-0.00138, 0.09605]) Problem 3.c. .. code:: python slopes = [] for i in range(1000): z1 = np.random.normal(0,1,1000) z2 = np.random.normal(0,1,1000) z1_dm = sm.add_constant(z1) # dm for design matrix slope = sm.OLS(z2, z1_dm).fit().params[1] slopes.append(slope) plt.hist(slopes, color = "c") plt.savefig('problem3c.png', bbox_inches='tight') .. image:: assignment_4_3_files/assignment_4_3_7_0.png <file_sep>/bikeshare/code/R/arima.R #install.packages('forecast') #library(forecast) par(mfrow=c(1,1)) ### generate moving average model x = seq(0, 8*pi, len = 400) plot(x) y = sin(x) + 0.5*cos(4*x) + rnorm(length(x), 0, 0.5) + 0.1*x y[90:100] = NA y[190:200] = NA y[290:300] = NA z = sin(x) plot(y, type = 'l') ### mod1 = Arima(y, order = c(1, 1, 1)) #tsdiag(mod1) #summary(mod1) plot(mod1$x, type = 'l') lines(fitted(mod1), col = 'cyan') pacf(y) summary(mod1) <file_sep>/lab-1/MultipleLinearRegression-master/regexing.py import re first = """This is a very long string. It has numbers like 15, 27, 34, 96 and letters like a,b,c r f and g. Sometimes I forget to include commas but I always remember to do some things. Because periods are important, especially this one. And this one. Too. I know that this is kind of a boring sentence. However, I really think it's great! Data: 42,57,68,92,33""" #finding all the numbers result = re.search("[0-9]",first) print result.start() print first[49:64] second = first[65:] result = re.search("[0-9]",second) print result.start() print second[278:]
788b4d987b2fa95defe6b6775cdefc296ff3bd94
[ "Markdown", "Python", "R", "reStructuredText" ]
35
Python
pvarsh/applied_data_science
6c3cc21e40ef992cdfaa302f0c6b7e1bdfff410e
c6f34f4547397c0be6802913e84362acd41b923b
refs/heads/master
<file_sep>package com.rasmitap.tailwebs_assigment2.Map; import android.os.AsyncTask; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.PolylineOptions; import java.util.ArrayList; import java.util.Iterator; public class Routing extends AsyncTask<LatLng, Void, Route> { protected ArrayList<RoutingListener> _aListeners = new ArrayList(); protected TravelMode _mTravelMode; public enum TravelMode { BIKING("biking"), DRIVING("driving"), WALKING("walking"), TRANSIT("transit"); protected String _sValue; private TravelMode(String sValue) { this._sValue = sValue; } protected String getValue() { return this._sValue; } } public Routing(TravelMode mTravelMode) { this._mTravelMode = mTravelMode; } public void registerListener(RoutingListener mListener) { this._aListeners.add(mListener); } protected void dispatchOnStart() { Iterator it = this._aListeners.iterator(); while (it.hasNext()) { ((RoutingListener) it.next()).onRoutingStart(); } } protected void dispatchOnFailure() { Iterator it = this._aListeners.iterator(); while (it.hasNext()) { ((RoutingListener) it.next()).onRoutingFailure(); } } protected void dispatchOnSuccess(PolylineOptions mOptions, Route route) { Iterator it = this._aListeners.iterator(); while (it.hasNext()) { ((RoutingListener) it.next()).onRoutingSuccess(mOptions, route); } } protected Route doInBackground(LatLng... aPoints) { for (LatLng mPoint : aPoints) { if (mPoint == null) { return null; } } return new GoogleParser(constructURL(aPoints)).parse(); } protected String constructURL(LatLng... points) { LatLng start = points[0]; LatLng dest = points[1]; StringBuffer mBuf = new StringBuffer("http://maps.googleapis.com/maps/api/directions/json?"); mBuf.append("origin="); mBuf.append(start.latitude); mBuf.append(','); mBuf.append(start.longitude); mBuf.append("&destination="); mBuf.append(dest.latitude); mBuf.append(','); mBuf.append(dest.longitude); mBuf.append("&sensor=true&mode="); mBuf.append(this._mTravelMode.getValue()); return mBuf.toString(); } protected void onPreExecute() { dispatchOnStart(); } protected void onPostExecute(Route result) { if (result == null) { dispatchOnFailure(); return; } PolylineOptions mOptions = new PolylineOptions(); for (LatLng point : result.getPoints()) { mOptions.add(point); } dispatchOnSuccess(mOptions, result); } } <file_sep>package com.example.trackingandchattingapplication; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.graphics.drawable.ColorDrawable; import android.location.Address; import android.location.Geocoder; import android.os.SystemClock; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.rasmitap.tailwebs_assigment2.R; import com.rasmitap.tailwebs_assigment2.utils.ConstantStore; import com.rasmitap.tailwebs_assigment2.utils.GPSTracker; import com.rasmitap.tailwebs_assigment2.utils.Utility; import com.rasmitap.tailwebs_assigment2.view.LoginActivity; import com.rasmitap.tailwebs_assigment2.view.MapActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { TextView textlogout,btn_trackhistroy; LinearLayout ll_track; private long mLastClickTime = 0; GPSTracker gps; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textlogout=findViewById(R.id.textlogout); btn_trackhistroy=findViewById(R.id.btn_trackhistroy); ll_track=findViewById(R.id.ll); textlogout.setOnClickListener(this); ll_track.setOnClickListener(this); btn_trackhistroy.setOnClickListener(this); gps=new GPSTracker(MainActivity.this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.textlogout: try { if (SystemClock.elapsedRealtime() - mLastClickTime < 2000) { return; } mLastClickTime = SystemClock.elapsedRealtime(); } catch (Exception e) { e.printStackTrace(); } openLogoutConfirmDialog(); break; case R.id.btn_trackhistroy: break; case R.id.ll: if (gps != null) { if (gps.canGetLocation()) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); ConstantStore.LATITUDE = gps.getLatitude(); ConstantStore.LONGITUDE = gps.getLongitude(); String lata = String.valueOf(latitude); String longt = String.valueOf(longitude); if (!lata.equalsIgnoreCase("0.0") && !longt.equalsIgnoreCase("0.0")) { Intent intent = new Intent(MainActivity.this, MapActivity.class); intent.putExtra("latitude", lata); intent.putExtra("Longitide", longt); startActivity(intent); finish(); } } } break; } } public void openLogoutConfirmDialog() { final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.logout_confirm_dialog); dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT)); dialog.setCancelable(true); dialog.show(); TextView tv_no = (TextView) dialog.findViewById(R.id.tv_no); TextView tv_yes = (TextView) dialog.findViewById(R.id.tv_yes); TextView txt_logout_title = (TextView) dialog.findViewById(R.id.txt_logout_title); TextView txt_logout_tagline = (TextView) dialog.findViewById(R.id.txt_logout_tagline); txt_logout_title.setText("Logout"); txt_logout_tagline.setText("Are you sure you want to logout?"); tv_yes.setText("Yes"); tv_no.setText("No"); tv_no.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { dialog.dismiss(); } }); tv_yes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { Utility.clearPreference(MainActivity.this); dialog.dismiss(); Intent intent = new Intent(MainActivity.this, LoginActivity.class); startActivity(intent); finish(); } }); Window window = dialog.getWindow(); WindowManager.LayoutParams wlp = window.getAttributes(); wlp.windowAnimations = R.style.DialogAnimation; wlp.gravity = Gravity.CENTER; window.setAttributes(wlp); } }<file_sep>package com.rasmitap.tailwebs_assigment2.utils; /** * Created by administrator on 4/12/17. */ import android.content.Context; import android.content.SharedPreferences; public class Utility { public static Context appContext; private static String PREFERENCE; private static Utility mInstance; private static Context mCtx; private static final String SHARED_PREF_NAME = "FCMSharedPref"; private static final String TAG_TOKEN = "tagtoken"; public Utility(Context context) { mCtx = context; } public static synchronized Utility getInstance(Context context) { if (mInstance == null) { mInstance = new Utility(context); } return mInstance; } public static void setStringSharedPreference(Context context, String name, String value) { appContext = context; SharedPreferences settings = context.getSharedPreferences(PREFERENCE, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString(name, value); editor.commit(); } public boolean saveDeviceToken(String token){ SharedPreferences sharedPreferences = mCtx.getSharedPreferences(SHARED_PREF_NAME, Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(TAG_TOKEN, token); editor.apply(); return true; } public static String getStringSharedPreferences(Context context, String name) { SharedPreferences settings = context.getSharedPreferences(PREFERENCE, 0); return settings.getString(name, ""); } public static void clearPreference(Context context) { SharedPreferences sp = context.getSharedPreferences(PREFERENCE, 0); SharedPreferences.Editor editor = sp.edit(); editor.clear(); editor.commit(); editor.apply(); } }<file_sep>package com.rasmitap.tailwebs_assigment2.Map; import android.util.Log; import com.google.android.gms.maps.model.LatLng; import com.google.firebase.BuildConfig; import com.google.firebase.analytics.FirebaseAnalytics; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class GoogleParser extends XMLParser implements Parser { private int distance; public GoogleParser(String feedUrl) { super(feedUrl); } public Route parse() { String result = convertStreamToString(getInputStream()); if (result == null) { return null; } Route route = new Route(); Segment segment = new Segment(); try { JSONObject json = new JSONObject(result); route.setPolyline(json.getJSONArray("routes").getJSONObject(0).getJSONObject("overview_polyline").getString("points")); JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0); JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0); JSONArray steps = leg.getJSONArray("steps"); int numSteps = steps.length(); route.setName(leg.getString("start_address") + " to " + leg.getString("end_address")); route.setCopyright(jsonRoute.getString("copyrights")); route.setDurationText(leg.getJSONObject("duration").getString("text")); route.setDistanceText(leg.getJSONObject("distance").getString("text")); route.setEndAddressText(leg.getString("end_address")); route.setLength(leg.getJSONObject("distance").getInt(FirebaseAnalytics.Param.VALUE)); if (!jsonRoute.getJSONArray("warnings").isNull(0)) { route.setWarning(jsonRoute.getJSONArray("warnings").getString(0)); } for (int i = 0; i < numSteps; i++) { JSONObject step = steps.getJSONObject(i); JSONObject start = step.getJSONObject("start_location"); segment.setPoint(new LatLng(start.getDouble("lat"), start.getDouble("lng"))); int length = step.getJSONObject("distance").getInt(FirebaseAnalytics.Param.VALUE); this.distance += length; segment.setLength(length); segment.setDistance((double) (this.distance / 1000)); segment.setInstruction(step.getString("html_instructions")); if (step.has("maneuver")) { segment.setManeuver(step.getString("maneuver")); } else { segment.setManeuver(BuildConfig.FLAVOR); } route.addPoints(decodePolyLine(step.getJSONObject("polyline").getString("points"))); route.addSegment(segment.copy()); } return route; } catch (JSONException e) { Log.e("Routing Error", e.getMessage()); e.printStackTrace(); return null; } } /* JADX WARNING: inconsistent code. */ /* Code decompiled incorrectly, please refer to instructions dump. */ /* private static String convertStreamToString(java.io.InputStream r7) { *//* if (r7 != 0) goto L_0x0004; L_0x0002: r4 = 0; L_0x0003: return r4; L_0x0004: r2 = new java.io.BufferedReader; r4 = new java.io.InputStreamReader; r4.<init>(r7); r2.<init>(r4); r3 = new java.lang.StringBuilder; r3.<init>(); r1 = 0; L_0x0014: r1 = r2.readLine(); Catch:{ IOException -> 0x001e } if (r1 == 0) goto L_0x0030; L_0x001a: r3.append(r1); Catch:{ IOException -> 0x001e } goto L_0x0014; L_0x001e: r0 = move-exception; r4 = "Routing Error"; r5 = r0.getMessage(); Catch:{ all -> 0x004a } android.util.Log.e(r4, r5); Catch:{ all -> 0x004a } r7.close(); Catch:{ IOException -> 0x003f } L_0x002b: r4 = r3.toString(); goto L_0x0003; L_0x0030: r7.close(); Catch:{ IOException -> 0x0034 } goto L_0x002b; L_0x0034: r0 = move-exception; r4 = "Routing Error"; r5 = r0.getMessage(); android.util.Log.e(r4, r5); goto L_0x002b; L_0x003f: r0 = move-exception; r4 = "Routing Error"; r5 = r0.getMessage(); android.util.Log.e(r4, r5); goto L_0x002b; L_0x004a: r4 = move-exception; r7.close(); Catch:{ IOException -> 0x004f } L_0x004e: throw r4; L_0x004f: r0 = move-exception; r5 = "Routing Error"; r6 = r0.getMessage(); android.util.Log.e(r5, r6); goto L_0x004e; *//* throw new UnsupportedOperationException("Method not decompiled: com.karwa.app.hyperlinkGoogle.route.GoogleParser.convertStreamToString(java.io.InputStream):java.lang.String"); }*/ private String convertStreamToString(InputStream is) { ByteArrayOutputStream oas = new ByteArrayOutputStream(); copyStream(is, oas); String t = oas.toString(); try { oas.close(); oas = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return t; } private void copyStream(InputStream is, OutputStream os) { final int buffer_size = 1024; try { byte[] bytes=new byte[buffer_size]; for(;;) { int count=is.read(bytes, 0, buffer_size); if(count==-1) break; os.write(bytes, 0, count); } } catch(Exception ex){} } private List<LatLng> decodePolyLine(String poly) { int len = poly.length(); int index = 0; List<LatLng> decoded = new ArrayList(); int lat = 0; int lng = 0; while (index < len) { int index2; int shift = 0; int result = 0; while (true) { index2 = index + 1; int b = poly.charAt(index) - 63; result |= (b & 31) << shift; shift += 5; if (b < 32) { break; } index = index2; } lat += (result & 1) != 0 ? (result >> 1) ^ -1 : result >> 1; shift = 0; result = 0; index = index2; while (true) { index2 = index + 1; int b = poly.charAt(index) - 63; result |= (b & 31) << shift; shift += 5; if (b < 32) { break; } index = index2; } lng += (result & 1) != 0 ? (result >> 1) ^ -1 : result >> 1; decoded.add(new LatLng(((double) lat) / 100000.0d, ((double) lng) / 100000.0d)); index = index2; } return decoded; } } <file_sep>package com.rasmitap.tailwebs_assigment2.utils; public class Validation { public static boolean isRequiredField(String strText) { return strText != null && !strText.trim().isEmpty(); } } <file_sep>package com.rasmitap.tailwebs_assigment2.utils; public class ConstantStore { public static final String is_Login = "is_Login"; public static final String UserName = "UserName"; public static final String Password = "<PASSWORD>"; public static String LOGIN_PREFERENCES = "LOGIN_PREFERENCES"; public static final int PERMISSION_CODE =123 ; public static String LOCATION_ENABLE_BR = "location_enable_br"; public static String LOCATION_ENABKE_VALUE_KEY = "location_enable_key"; public static double LATITUDE; public static double LONGITUDE; public static String CUSRRENT_LOCATION = ""; } <file_sep>package com.rasmitap.tailwebs_assigment2.view; import android.Manifest; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Criteria; import android.location.Location; import com.google.android.gms.common.util.MapUtils; import com.google.android.gms.location.LocationListener; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.CameraPosition; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.google.android.material.bottomsheet.BottomSheetBehavior; import com.google.firebase.FirebaseApp; import com.rasmitap.tailwebs_assigment2.Map.Route; import com.rasmitap.tailwebs_assigment2.Map.Routing; import com.rasmitap.tailwebs_assigment2.Map.RoutingListener; import com.rasmitap.tailwebs_assigment2.R; import com.rasmitap.tailwebs_assigment2.utils.ConstantStore; import com.rasmitap.tailwebs_assigment2.utils.GPSTracker; import com.rasmitap.tailwebs_assigment2.utils.GlobalMethods; import com.rasmitap.tailwebs_assigment2.utils.Utility; import com.rasmitap.tailwebs_assigment2.utils.Validation; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; public class MapActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, GoogleMap.OnCameraIdleListener, RoutingListener,GoogleMap.OnMarkerClickListener,GoogleMap.InfoWindowAdapter, LocationListener { GoogleMap mGoogleMap; SupportMapFragment mapFrag; LocationRequest mLocationRequest; GoogleApiClient mGoogleApiClient; Location mLastLocation; Marker mCurrLocationMarker; private BottomSheetBehavior mBottomSheetBehavior; View bottomSheet; TextView txttimer, btn_stoptrack; private int seconds = 0; private boolean running; private boolean wasRunning; GPSTracker gps; MapUtils mapUtil; String StartLat = ""; String StartLon = ""; LatLng start_location_lanlng, destination_location_lanlng; Polyline line; private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place"; private static final String API_KEY = "<KEY>"; private Polyline polyline; private static final int UPDATE_INTERVAL = 15 * 1000; private static final int FASTEST_UPDATE_INTERVAL = 2 * 1000; public static String LATELONG = "latlong"; public static String LONG = "long"; public static String ADDRESS = "address"; Marker pick_up_location_marker, destination_location_marker; boolean is_camera_move = false; // Static LatLng LatLng startLatLng; LatLng endLatLng; LocationRequest locationRequest; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); txttimer = (TextView) findViewById(R.id.txttimer); btn_stoptrack = (TextView) findViewById(R.id.btn_stoptrack); mapUtil = new MapUtils(); FirebaseApp.initializeApp(this); getLocationLatLong(); locationRequest = LocationRequest.create() //Set the required accuracy level .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) //Set the desired (inexact) frequency of location updates .setInterval(UPDATE_INTERVAL) //Throttle the max rate of update requests .setFastestInterval(FASTEST_UPDATE_INTERVAL); if (savedInstanceState != null) { // Get the previous state of the stopwatch // if the activity has been // destroyed and recreated. seconds = savedInstanceState .getInt("seconds"); running = savedInstanceState .getBoolean("running"); wasRunning = savedInstanceState .getBoolean("wasRunning"); } runTimer(); onClickStart(); btn_stoptrack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickStop(); } }); if (gps != null) { if (gps.canGetLocation()) { getLocationLatLong(); } else { gps.showSettingsAlert(); } } checkPermission(); String urlTopass = makeURL(startLatLng.latitude, startLatLng.longitude, endLatLng.latitude, endLatLng.longitude); new connectAsyncTask(urlTopass).execute(); // mGoogleMap.setMyLocationEnabled(true); // mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(startLatLng)); // mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12)); } @Override public void onStart() { super.onStart(); // Check if user is signed in (non-null) and update UI accordingly. } private class connectAsyncTask extends AsyncTask<Void, Void, String> { private ProgressDialog progressDialog; String url; connectAsyncTask(String urlPass) { url = urlPass; } @Override protected void onPreExecute() { // TODO Auto-generated method stub super.onPreExecute(); progressDialog = new ProgressDialog(MapActivity.this); progressDialog.setMessage("Fetching route, Please wait..."); progressDialog.setIndeterminate(true); progressDialog.show(); } @Override protected String doInBackground(Void... params) { JSONParser jParser = new JSONParser(); String json = jParser.getJSONFromUrl(url); return json; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); progressDialog.hide(); if (result != null) { drawPath(result); } } } public String makeURL(double sourcelat, double sourcelog, double destlat, double destlog) { StringBuilder urlString = new StringBuilder(); urlString.append("http://maps.googleapis.com/maps/api/directions/json"); urlString.append("?origin=");// from urlString.append(Double.toString(sourcelat)); urlString.append(","); urlString.append(Double.toString(sourcelog)); urlString.append("&destination=");// to urlString.append(Double.toString(destlat)); urlString.append(","); urlString.append(Double.toString(destlog)); urlString.append("&sensor=false&mode=driving&alternatives=true"); return urlString.toString(); } public class JSONParser { InputStream is = null; JSONObject jObj = null; String json = ""; // constructor public JSONParser() { } public String getJSONFromUrl(String url) { // Making HTTP request try { // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader( new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } json = sb.toString(); is.close(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } return json; } } public void drawPath(String result) { if (line != null) { mGoogleMap.clear(); } mGoogleMap.addMarker(new MarkerOptions().position(endLatLng).icon( BitmapDescriptorFactory.fromResource(R.drawable.marker))); mGoogleMap.addMarker(new MarkerOptions().position(startLatLng).icon( BitmapDescriptorFactory.fromResource(R.drawable.marker))); try { // Tranform the string into a json object final JSONObject json = new JSONObject(result); JSONArray routeArray = json.getJSONArray("routes"); JSONObject routes = routeArray.getJSONObject(0); JSONObject overviewPolylines = routes .getJSONObject("overview_polyline"); String encodedString = overviewPolylines.getString("points"); List<LatLng> list = decodePoly(encodedString); for (int z = 0; z < list.size() - 1; z++) { LatLng src = list.get(z); LatLng dest = list.get(z + 1); line = mGoogleMap.addPolyline(new PolylineOptions() .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude)) .width(5).color(Color.BLUE).geodesic(true)); } } catch (Exception e) { e.printStackTrace(); } } private List<LatLng> decodePoly(String encoded) { List<LatLng> poly = new ArrayList<LatLng>(); int index = 0, len = encoded.length(); int lat = 0, lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = encoded.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; LatLng p = new LatLng((((double) lat / 1E5)), (((double) lng / 1E5))); poly.add(p); } return poly; } private void initMapConponet() { Log.e("test", "==>>initMapConponet() calll"); try { mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); MapsInitializer.initialize(getApplicationContext()); mapFrag.getMapAsync(this); Log.e("test", "camera change"); // mapFragment.getMapAsync(HomeFragment.this); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_HIGH); criteria.setAltitudeRequired(false); criteria.setSpeedRequired(false); criteria.setCostAllowed(true); criteria.setBearingRequired(false); //API level 9 and up criteria.setHorizontalAccuracy(Criteria.ACCURACY_HIGH); criteria.setVerticalAccuracy(Criteria.ACCURACY_HIGH); } catch (Exception e) { e.printStackTrace(); } } private void checkPermission() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { String[] permissions = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}; if (GlobalMethods.isPermissionNotGranted(getApplicationContext(), permissions)) { requestPermissions(permissions, ConstantStore.PERMISSION_CODE); return; } else { initMapConponet(); } } else initMapConponet(); } public void getLocationLatLong() { gps = new GPSTracker(this); if (gps != null) { double latitude = gps.getLatitude(); double longitude = gps.getLongitude(); String lata = String.valueOf(latitude); String longt = String.valueOf(longitude); ConstantStore.LATITUDE = latitude; ConstantStore.LONGITUDE = longitude; if (!lata.equalsIgnoreCase("0.0") && !longt.equalsIgnoreCase("0.0")) { startLatLng = new LatLng(latitude, longitude); endLatLng = new LatLng(latitude, longitude); } } } @Override public void onSaveInstanceState( Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState .putInt("seconds", seconds); savedInstanceState .putBoolean("running", running); savedInstanceState .putBoolean("wasRunning", wasRunning); } @Override public void onPause() { super.onPause(); wasRunning = running; running = false; //stop location updates when Activity is no longer active if (mGoogleApiClient != null) { LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); } } @Override protected void onResume() { super.onResume(); if (wasRunning) { running = true; } } @Override public void onMapReady(GoogleMap googleMap) { mGoogleMap = googleMap; mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL); mGoogleMap.getUiSettings().isMyLocationButtonEnabled(); mGoogleMap.getUiSettings().isZoomControlsEnabled(); mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true); // mMap.setOnInfoWindowClickListener(this); fixZoomForMarkers1(mGoogleMap, startLatLng); LatLng latLng = new LatLng(ConstantStore.LATITUDE, ConstantStore.LONGITUDE); Log.e("test", "onMapReady: " + ConstantStore.LATITUDE); Log.e("test", "onMapReady: " + ConstantStore.LONGITUDE); /* mMap.addMarker(new MarkerOptions().position(latLng) .title(CommonKeys.CUSRRENT_LOCATION));*/ destination_location_lanlng = latLng; fixZoomForMarkers(mGoogleMap, latLng); } public void fixZoomForMarkers(GoogleMap googleMap, LatLng latLng) { if (destination_location_marker != null) { destination_location_marker.remove(); } destination_location_marker = mGoogleMap.addMarker(new MarkerOptions().position(destination_location_lanlng).title("Current Point").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))); LatLngBounds.Builder bc = new LatLngBounds.Builder(); bc.include(destination_location_marker.getPosition()); CameraPosition cameraPosition = CameraPosition.fromLatLngZoom(latLng, 15.0f); CameraUpdate cu = CameraUpdateFactory.newCameraPosition(cameraPosition); googleMap.animateCamera(cu); destination_location_marker.showInfoWindow(); // googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), 20),2000,null); } public void fixZoomForMarkers1(GoogleMap googleMap, LatLng latLng) { if (start_location_lanlng != null) { pick_up_location_marker = mGoogleMap.addMarker(new MarkerOptions().position(start_location_lanlng).title("Started Point").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))); LatLngBounds.Builder bc = new LatLngBounds.Builder(); bc.include(pick_up_location_marker.getPosition()); CameraPosition cameraPosition = CameraPosition.fromLatLngZoom(latLng, 15.0f); CameraUpdate cu = CameraUpdateFactory.newCameraPosition(cameraPosition); googleMap.animateCamera(cu); pick_up_location_marker.showInfoWindow(); } } protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); mGoogleApiClient.connect(); } @Override public void onConnected(Bundle bundle) { mLocationRequest = new LocationRequest(); mLocationRequest.setInterval(1000); mLocationRequest.setFastestInterval(1000); mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY); if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); } } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } @Override public void onLocationChanged(Location location) { mLastLocation = location; if (mCurrLocationMarker != null) { mCurrLocationMarker.remove(); } //Place current location marker destination_location_lanlng = new LatLng(location.getLatitude(), location.getLongitude()); mCurrLocationMarker = mGoogleMap.addMarker(new MarkerOptions().position(destination_location_lanlng).title("Current Location").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))); LatLngBounds.Builder bc = new LatLngBounds.Builder(); bc.include(mCurrLocationMarker.getPosition()); CameraPosition cameraPosition = CameraPosition.fromLatLngZoom(destination_location_lanlng, 15.0f); CameraUpdate cu = CameraUpdateFactory.newCameraPosition(cameraPosition); mGoogleMap.animateCamera(cu); mCurrLocationMarker.showInfoWindow(); UpdateRoute1(start_location_lanlng, destination_location_lanlng); } public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99; private void checkLocationPermission() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. new android.app.AlertDialog.Builder(this) .setTitle("Location Permission Needed") .setMessage("This app needs the Location permission, please accept to use location functionality") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //Prompt the user once explanation has been shown ActivityCompat.requestPermissions(MapActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } }) .create() .show(); } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSIONS_REQUEST_LOCATION); } } } LatLngBounds.Builder builder; private void UpdateRoute1(LatLng start, LatLng destination) { if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) { // mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } if (start != null && destination != null) { this.builder = new LatLngBounds.Builder(); this.builder.include(start); this.builder.include(destination); Routing routing = new Routing(Routing.TravelMode.DRIVING); routing.registerListener((RoutingListener) MapActivity.this); routing.execute(new LatLng[]{start, destination}); } } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case MY_PERMISSIONS_REQUEST_LOCATION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Do the // location-related task you need to do. if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { if (mGoogleApiClient == null) { buildGoogleApiClient(); } if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mGoogleMap.setMyLocationEnabled(true); } else { // Show rationale and request permission. } } } else { // permission denied, boo! Disable the // functionality that depends on this permission. Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show(); } return; } // other 'case' lines to check for other // permissions this app might request } } public void onClickStart() { running = true; } public void onClickStop() { running = false; } public void onClickReset(View view) { running = false; seconds = 0; } private void runTimer() { // Get the text view. final TextView timeView = (TextView) findViewById( R.id.txttimer); final Handler handler = new Handler(); handler.post(new Runnable() { @Override public void run() { int hours = seconds / 3600; int minutes = (seconds % 3600) / 60; int secs = seconds % 60; // Format the seconds into hours, minutes, // and seconds. String time = String .format(Locale.CANADA.getDefault(), "%d:%02d:%02d", hours, minutes, secs); // Set the text view text. timeView.setText(time); // If running is true, increment the // seconds variable. if (running) { seconds++; } // Post the code again // with a delay of 1 second. handler.postDelayed(this, 1000); } }); } @Override public View getInfoWindow(Marker marker) { View view = getLayoutInflater().inflate(R.layout.info_window,null); TextView tv_km=(TextView) view.findViewById(R.id.tv_distance); if(Validation.isRequiredField(marker.getTitle())) { tv_km.setText(marker.getTitle()); } return view; } @Override public View getInfoContents(Marker marker) { return null; } @Override public void onCameraIdle() { } @Override public boolean onMarkerClick(Marker marker) { return false; } @Override public void onRoutingFailure() { } @Override public void onRoutingStart() { } @Override public void onRoutingSuccess(PolylineOptions mPolyOptions, Route route) { Log.e("test","onRoutingSuccess"); if (this.mGoogleMap != null) { mGoogleMap.clear(); ///this.route1 = route; //this.IsRoutSucess = 0; String time = route.getDurationText().replace(" ", "\n"); String timeNew = route.getDurationText().toString(); if(start_location_lanlng!=null){ pick_up_location_marker= mGoogleMap.addMarker(new MarkerOptions().position(start_location_lanlng).title("SET_PICKUP_LOCATION").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))); // pick_up_location_marker.hideInfoWindow(); } if(destination_location_lanlng!=null){ destination_location_marker= mGoogleMap.addMarker(new MarkerOptions().position(destination_location_lanlng).title("SET_DESTINATION").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))); destination_location_marker.showInfoWindow(); } try { this.mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(this.builder.build(), (int) getResources().getDimension(R.dimen._50sdp))); } catch (Exception e2) { e2.printStackTrace(); } } is_camera_move=true; //Check the current state of bottom sheet bottomSheet.setVisibility(View.VISIBLE); if (mBottomSheetBehavior.getState() == BottomSheetBehavior.STATE_COLLAPSED){ mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED); Log.e("test","STATE_EXPANDED"); } else{ Log.e("test","STATE_COLLAPSED"); //else if state is expanded collapse it // mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED); } PolylineOptions polyoptions = new PolylineOptions(); if(this.polyline!=null){ this.polyline.remove(); } polyoptions.color(Color.parseColor("#003366")); polyoptions.width(8.0f); polyoptions.addAll(mPolyOptions.getPoints()); this.polyline = this.mGoogleMap.addPolyline(polyoptions); try { this.mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(this.builder.build(), (int) getResources().getDimension(R.dimen._50sdp))); } catch (Exception e2) { e2.printStackTrace(); } } }<file_sep>package com.rasmitap.tailwebs_assigment2.model; import java.util.ArrayList; import java.util.List; public class Datamodel { public String Marks; public String getUserName() { return UserName; } public void setUserName(String userName) { UserName = userName; } public String UserName; public Datamodel(String StudentName, String Marks, String Subject) { this.Marks=Marks; this.StudentName=StudentName; this.Subject=Subject; } public Datamodel() { } public String getMarks() { return Marks; } public void setMarks(String marks) { Marks = marks; } public String getStudentName() { return StudentName; } public void setStudentName(String studentName) { StudentName = studentName; } public String getSubject() { return Subject; } public void setSubject(String subject) { Subject = subject; } private String StudentName; private String Subject; public static List<Datamodel> getList(){ List<Datamodel> list=new ArrayList<>(); list.add(new Datamodel("Voucher ","Biscuits","$8.00")); list.add(new Datamodel("Voucher ","Vegetables","$10.00")); list.add(new Datamodel("Voucher ","Soft Drinks","$15.00")); return list; } } <file_sep>include ':app' rootProject.name = "TrackingAndChattingApplication"<file_sep>/** * Copyright 2016 Google Inc. All Rights Reserved. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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. */ package com.rasmitap.tailwebs_assigment2; import android.content.SharedPreferences; import android.os.Build; import android.util.Config; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.rasmitap.tailwebs_assigment2.utils.Utility; public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIIDService"; Config config; private SharedPreferences sharedPreferences; private String refreshedToken; @Override public void onTokenRefresh() { refreshedToken = FirebaseInstanceId.getInstance().getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); sharedPreferences = getSharedPreferences("FIREBASE", 0); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("TOKEN", refreshedToken); editor.commit(); storeToken(refreshedToken); } public String getDeviceName() { String manufacturer = Build.MANUFACTURER; String model = Build.MODEL; if (model.startsWith(manufacturer)) { return capitalize(model); } else { return capitalize(manufacturer) + " " + model; } } private String capitalize(String s) { if (s == null || s.length() == 0) { return ""; } char first = s.charAt(0); if (Character.isUpperCase(first)) { return s; } else { return Character.toUpperCase(first) + s.substring(1); } } private void storeToken(String token) { //saving the token on shared preferences Utility.getInstance(getApplicationContext()).saveDeviceToken(token); // ParsingHelper.GetAPI(config.reg_deviceId,config.refreshedToken,config.reg_deviceName,config.reg_eDevicetype,"1"); } } <file_sep>package com.rasmitap.tailwebs_assigment2.Map; public interface Parser { Route parse(); } <file_sep>package com.rasmitap.tailwebs_assigment2.QuickBlox; import android.util.SparseArray; import com.quickblox.users.model.QBUser; import java.util.ArrayList; import java.util.List; /** * Created by admin on 12/12/17. */ public class QBUserHolder { public static QBUserHolder instance; private SparseArray<QBUser> qbUserSparseArray; public static synchronized QBUserHolder getInstance() { if(instance == null) { instance = new QBUserHolder(); } return instance; } private QBUserHolder() { qbUserSparseArray = new SparseArray<>(); } public void putUsers(List<QBUser> users) { for(QBUser user:users) { putUsers(user); } } private void putUsers(QBUser user) { qbUserSparseArray.put(user.getId(),user); } public QBUser getUserById(int id) { return qbUserSparseArray.get(id); } public List<QBUser> getUsersByIds(List<Integer> ids) { List<QBUser> qbUser = new ArrayList<>(); for(Integer id : ids) { QBUser user = getUserById(id); if(user != null) { qbUser.add(user); } } return qbUser; } }
3f50f37aa0c0f6c49d4375718f9ac52e947b0687
[ "Java", "Gradle" ]
12
Java
Rasmita9428/TrackingAndChattingApplication
af91705941ea7b30340e45038f465c72d528f799
2e758033a133fa26fff50d653bf85501d809fd1f
refs/heads/master
<repo_name>akshayaravindan/HelloWorld2019<file_sep>/backend/__tests__/integration/admin.test.ts import 'jest'; import * as supertest from 'supertest'; import { generateUsers } from '../helper'; import Server from '../../server'; import { Role } from '../../../shared/user.enums'; import { IUserModel, User } from '../../models/user'; let server: Server; let request: supertest.SuperTest<supertest.Test>; let users: { user: IUserModel; token: string }[]; let user: { user: IUserModel; token: string }; describe('Suite: /api/admin -- Integration', () => { beforeEach(async () => { server = await Server.createInstance(); request = supertest(server.app); await server.mongoose.connection.dropDatabase(); users = await Promise.all<{ user: IUserModel; token: string }>( generateUsers(6).map(u => request .post('/api/auth/signup') .send(u) .then(response => response.body.response) ) ); user = users[0]; }); afterEach(() => server.mongoose.disconnect()); describe('Update roles', () => { it('Fails to update role because unauthorized', async () => { const { body: { error }, status } = await request.post(`/api/admin/role`); expect(status).toEqual(401); expect(error).toEqual('You must be logged in!'); }); it('Fails to update role because only USER role', async () => { const { body: { error }, status } = await request.post(`/api/admin/role`).auth(user.token, { type: 'bearer' }); expect(status).toEqual(401); expect(error).toEqual('Insufficient permissions'); }); it('Fails to update role because only EXEC role', async () => { user.user = await User.findByIdAndUpdate( user.user._id, { $set: { role: Role.EXEC } }, { new: true } ); const { body: { error }, status } = await request.post(`/api/admin/role`).auth(user.token, { type: 'bearer' }); expect(status).toEqual(401); expect(error).toEqual('Insufficient permissions'); }); it('Fails to update role because no role', async () => { user.user = await User.findByIdAndUpdate( user.user._id, { $set: { role: Role.ADMIN } }, { new: true } ); const oldUser = users[1].user; const { body: { error }, status } = await request .post(`/api/admin/role`) .send({ email: oldUser.email }) .auth(user.token, { type: 'bearer' }); expect(status).toEqual(400); expect(error).toEqual('Invalid Role'); }); it('Fails to update role because invalid role', async () => { user.user = await User.findByIdAndUpdate( user.user._id, { $set: { role: Role.ADMIN } }, { new: true } ); const oldUser = users[1].user; const role = 'invalid'; const { body: { error }, status } = await request .post(`/api/admin/role`) .send({ email: oldUser.email, role }) .auth(user.token, { type: 'bearer' }); expect(status).toEqual(400); expect(error).toEqual('Invalid Role'); }); it('Fails to update role non existant user', async () => { user.user = await User.findByIdAndUpdate( user.user._id, { $set: { role: Role.ADMIN } }, { new: true } ); const email = 'blah'; const { body: { error }, status } = await request .post(`/api/admin/role`) .send({ email, role: Role.MENTOR }) .auth(user.token, { type: 'bearer' }); expect(status).toEqual(400); expect(error).toEqual(`There is no user with email: ${email}`); }); it('Successfully updates a users role', async () => { user.user = await User.findByIdAndUpdate( user.user._id, { $set: { role: Role.ADMIN } }, { new: true } ); const oldUser = users[1].user; const { body: { response }, status } = await request .post(`/api/admin/role`) .send({ email: oldUser.email, role: Role.MENTOR }) .auth(user.token, { type: 'bearer' }); expect(status).toEqual(200); expect(response).toBeTruthy(); expect(response).toEqual( expect.objectContaining({ ...oldUser, updatedAt: response.updatedAt, role: Role.MENTOR }) ); }); }); }); <file_sep>/backend/controllers/globals.controller.ts import { JsonController, Get, Authorized, Post, BodyParam, BadRequestError } from 'routing-controllers'; import { BaseController } from './base.controller'; import { Role } from '../../shared/user.enums'; import { ApplicationsStatus } from '../../shared/globals.enums'; import { Globals, IGlobalsModel } from '../models/globals'; @JsonController('/api/globals') export class GlobalsController extends BaseController { @Get('/') async getGlobals() { const globals: IGlobalsModel = await Globals.findOneAndUpdate( {}, {}, { upsert: true, setDefaultsOnInsert: true, new: true } ) .lean() .exec(); return globals; } // TODO: Add tests @Post('/status') @Authorized([Role.ADMIN]) async updateApplicationsStatus(@BodyParam('status') s: string) { const status = Object.values(ApplicationsStatus).find(stat => stat === s); if (!status) throw new BadRequestError('Invalid status'); const globals: IGlobalsModel = await Globals.findOneAndUpdate( {}, { applicationsStatus: status }, { upsert: true, setDefaultsOnInsert: true, new: true } ) .lean() .exec(); return globals; } // TODO: Add tests @Post('/public') @Authorized([Role.ADMIN]) async makeApplicationsPublic(@BodyParam('status') status: boolean) { const globals: IGlobalsModel = await Globals.findOneAndUpdate( {}, { applicationsPublic: status }, { upsert: true, setDefaultsOnInsert: true, new: true } ) .lean() .exec(); return globals; } } <file_sep>/backend/controllers/user.controller.ts import { Request } from 'express'; import { ObjectId } from 'mongodb'; import { JsonController, Get, QueryParam, Param, BadRequestError, Put, Req, Body, CurrentUser, UnauthorizedError, Post, Authorized, Params } from 'routing-controllers'; import { BaseController } from './base.controller'; import { User, UserDto, IUserModel } from '../models/user'; import { ApplicationDto, Application } from '../models/application'; import { userMatches, hasPermission } from '../utils'; import { Role } from '../../shared/user.enums'; import { Inject } from 'typedi'; import { GlobalsController } from './globals.controller'; import { ApplicationsStatus } from '../../shared/globals.enums'; import { storageService } from '../services/storage.service.ts' @JsonController('/api/users') export class UserController extends BaseController { constructor(private storageService?: storageService) { super(); } @Inject() globalController: GlobalsController; @Get('/') @Authorized([Role.EXEC]) async getAll(@QueryParam('sortBy') sortBy?: string, @QueryParam('order') order?: number) { order = order === 1 ? 1 : -1; sortBy = sortBy || 'createdAt'; let contains = false; User.schema.eachPath(path => { if (path.toLowerCase() === sortBy.toLowerCase()) contains = true; }); if (!contains) sortBy = 'createdAt'; const results = await User.find() .sort({ [sortBy]: order }) .lean() .exec(); return { users: results }; } @Get('/:id/application') @Authorized() async getUserApplication(@Param('id') id: string, @CurrentUser() currentUser: IUserModel) { if (!ObjectId.isValid(id)) throw new BadRequestError('Invalid user ID'); if (!userMatches(currentUser, id, true)) throw new UnauthorizedError('You are unauthorized to view this application'); const user = await User.findById(id) .lean() .exec(); if (!user) throw new BadRequestError('User does not exist'); const appQuery = Application.findOne({ user }).populate('user'); if (hasPermission(currentUser, Role.EXEC)) appQuery.select('+statusInternal'); const application = await appQuery.exec(); return application; } // TODO: Add tests @Get('/application') @Authorized() async getOwnApplication(@CurrentUser() currentUser: IUserModel) { const application = await Application.findOne({ user: currentUser }) .populate('user') .exec(); return application; } // Regex because route clashes with get application route above ^ // Get('/:id') @Get(/\/((?!application)[a-zA-Z0-9]+)$/) @Authorized([Role.EXEC]) async getById(@Params() params: string[]) { const id = params[0]; if (!ObjectId.isValid(id)) throw new BadRequestError('Invalid user ID'); const user = await User.findById(id) .lean() .exec(); if (!user) throw new BadRequestError('User does not exist'); return user; } // TODO: Add tests @Put('/:id') @Authorized() async updateById( @Param('id') id: string, @Body() userDto: UserDto, @CurrentUser({ required: true }) currentUser: IUserModel ) { if (!ObjectId.isValid(id)) throw new BadRequestError('Invalid user ID'); if (!userMatches(currentUser, id)) throw new UnauthorizedError('You are unauthorized to edit this profile'); let user = await User.findById(id, '+password').exec(); if (!user) throw new BadRequestError('User not found'); user = await User.findByIdAndUpdate(id, userDto, { new: true }) .lean() .exec(); return user; } @Post('/:id/apply') @Authorized() async apply( @Req() req: Request, @Param('id') id: string, @Body() applicationDto: ApplicationDto, @CurrentUser({ required: true }) currentUser: IUserModel ) { if (!ObjectId.isValid(id)) throw new BadRequestError('Invalid user ID'); const user = await User.findById(id).exec(); if (!user) throw new BadRequestError('User not found'); if (!userMatches(currentUser, id)) throw new UnauthorizedError('You are unauthorized to edit this application'); const globals = await this.globalController.getGlobals(); const closed = currentUser.role === Role.ADMIN ? false : globals.applicationsStatus === ApplicationsStatus.CLOSED; if (closed) throw new UnauthorizedError('Sorry, applications are closed!'); const appQuery = Application.findOneAndUpdate( { user }, { ...applicationDto, user }, { new: true, upsert: true, setDefaultsOnInsert: true } ).populate('user'); if (hasPermission(currentUser, Role.EXEC)) appQuery.select('+statusInternal'); const files: Express.Multer.File[] = req.files ? (req.files as Express.Multer.File[]) : new Array<Express.Multer.File>(); const resume = files.find(file => file.fieldname === 'resume'); if (resume) { try { applicationDto.resume = await this.storageService.uploadToStorage( resume, 'resumes', applicationDto ); } catch (error) { this.logger.emerg('Error uploading resume:', error); throw new BadRequestError('Something is wrong! Unable to upload at the moment!'); } } const app = await appQuery.exec(); user.application = app; await user.save(); return app; } } <file_sep>/frontend/next.config.js const withTypescript = require('@zeit/next-typescript'); const withCss = require('@zeit/next-css'); const withLess = require('@zeit/next-less'); const withPlugins = require('next-compose-plugins'); const withTM = require('next-plugin-transpile-modules'); const lessToJS = require('less-vars-to-js'); const webpack = require('webpack'); const { readFileSync } = require('fs'); const { resolve } = require('path'); const { publicRuntimeConfig, serverRuntimeConfig } = require('../backend/config/env-config'); // fix: prevents error when .css/.less files are required by node if (typeof require !== 'undefined') { // tslint:disable: no-empty require.extensions['.less'] = () => {}; require.extensions['.css'] = () => {}; } const themeVariables = lessToJS(readFileSync(resolve(__dirname, './assets/theme.less'), 'utf8')); module.exports = withPlugins( [ [ withTM, { transpileModules: ['shared'] } ], [withTypescript], [withCss], [ withLess, { lessLoaderOptions: { javascriptEnabled: true, modifyVars: themeVariables // Change theme } } ] ], { publicRuntimeConfig, serverRuntimeConfig, webpack: (config, options) => { const { dev, isServer } = options; // if (isServer && dev) { // const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin'); // config.plugins.push( // new ForkTsCheckerWebpackPlugin({ // tsconfig: '../tsconfig.server.json', // tslint: '../tslint.json' // }) // ); // } // config.plugins.push( // new webpack.DefinePlugin({ // 'process.env.NODE_ENV': process.env.NODE_ENV // }) // ); return config; } } ); <file_sep>/backend/controllers/base.controller.ts import { createLogger } from '../utils/logger'; import { Logger } from 'winston'; export class BaseController { readonly logger: Logger; constructor() { this.logger = createLogger(this); } } <file_sep>/backend/index.ts import 'reflect-metadata'; require('source-map-support').install(); import Server from './server'; import CONFIG from './config'; const { PORT } = CONFIG; const start = async () => { try { const server = await Server.createInstance(); await server.initFrontend(); const httpServer = server.app.listen(PORT, () => { server.logger.info('CONFIG:', CONFIG); server.logger.info(`Listening on port: ${PORT}`); }); // Graceful shutdown process.on('SIGTERM', async () => { await server.mongoose.disconnect(); httpServer.close(); process.exit(0); }); return server; } catch (error) { console.error('Error:', error); throw error; } }; start(); <file_sep>/backend/config/env-config.js require('dotenv').config(); const env = process.env; const sharedConfig = { PORT: env.PORT || 5000, TRACKING_ID: env.TRACKING_ID || 'UA-124576559-2' }; const serverRuntimeConfig = { DB: env.DB || 'mongodb://0.0.0.0:27017/HelloWorld', EMAIL: env.EMAIL || '<EMAIL>', EXPIRES_IN: env.EXPIRES_IN || '7 days', GC_BUCKET: env.GC_BUCKET || 'mybucket', GC_CLIENT_EMAIL: env.GC_CLIENT_EMAIL || '<EMAIL>', GC_PRIVATE_KEY: env.GC_PRIVATE_KEY || 'myprivatekey', GC_PROJECT_ID: env.GC_PROJECT_ID || 'myprojectid', NODE_ENV: env.NODE_ENV || 'development', ORG_NAME: env.ORG_NAME || 'Purdue Hackers', REDIS_URL: env.REDIS_URL || 'redis://0.0.0.0:6379', SECRET: env.SECRET || 'my-secret', SENDGRID_KEY: env.SENDGRID_KEY || 'mysendgridkey', ...sharedConfig }; const publicRuntimeConfig = { API_URL: env.API_URL ? env.API_URL : `http://localhost:${sharedConfig.PORT}/api`, NODE_ENV: env.NODE_ENV || 'development', ...sharedConfig }; module.exports = { publicRuntimeConfig, serverRuntimeConfig }; <file_sep>/backend/middleware/globalError.ts import { getFromContainer } from 'routing-controllers'; import { AuthorizationRequiredError } from 'routing-controllers/error/AuthorizationRequiredError'; import { errorRes } from '../utils'; import { createLogger } from '../utils/logger'; import { EmailService } from '../services/email.service'; import CONFIG from '../config'; const logger = createLogger('GlobalError'); const emailService = getFromContainer(EmailService); export const globalError = (err, req, res, next) => { let { message, httpCode } = err; message = message || 'Whoops! Something went wrong!'; httpCode = httpCode || 500; // Send an email if error is from server if (httpCode === 500) { logger.emerg('Unhandled exception:', err); if (CONFIG.NODE_ENV === 'production') emailService .sendErrorEmail(err, req.user) .then(() => logger.info('Email sent')) .catch(error => logger.error('Error sending email:', error)); errorRes(res, httpCode, 'Whoops! Something went wrong!'); } else { if (err instanceof AuthorizationRequiredError) message = 'You must be logged in!'; logger.error('Caught error:', message); errorRes(res, httpCode, message); // next(err); } }; <file_sep>/backend/utils/logger.ts import * as util from 'util'; import chalk from 'chalk'; import { createLogger as createWinstonLogger, format, transports, config } from 'winston'; import CONFIG from '../config'; const customConsoleFormat = format.printf(({ level, timestamp, context, message, meta }) => { let result = `[${level}] [${timestamp}]`; if (context) result += ` ${chalk.yellow(`[${context}]`)} --`; result += ` ${message}`; if (meta && Array.isArray(meta)) result += `${(util as any).formatWithOptions({ colors: true, compact: false }, ...meta)}`; else if (meta) result += ` ${(util as any).formatWithOptions({ colors: true, compact: false }, meta)}`; return result; }); const enumerateErrorFormat = format((info: any) => { if (info.message instanceof Error) { info.message = Object.assign( { message: info.message.message, stack: info.message.stack }, info.message ); } if (info instanceof Error) { return Object.assign( { message: info.message, stack: info.stack }, info ); } return info; }); const transporters = context => [ new transports.Console({ format: format.combine( format(info => { info.level = info.level.toUpperCase(); info.context = context; info.timestamp = new Date(Date.now()).toLocaleString(); return info; })(), enumerateErrorFormat(), format.splat(), format.colorize(), customConsoleFormat ) }) ]; // tslint:disable-next-line:ban-types export const createLogger = (context: string | object | (() => any)) => { if (typeof context === 'object') context = context.constructor.name; if (typeof context === 'function') context = context.name; return createWinstonLogger({ transports: transporters(context), silent: CONFIG.NODE_ENV === 'test', levels: config.syslog.levels }).on('error', err => { console.log('Logger Error:', err); }); }; <file_sep>/frontend/redux/actions/index.ts import ReactGA from 'react-ga'; import { Dispatch } from 'redux'; import * as jwt from 'jsonwebtoken'; import { ICreateUser, ILoginUser, ILoginResponse, IContext, IApplication, IUser, IGlobals, IStatsResponse } from '../../@types'; import { api } from '../../utils'; import { setCookie, removeCookie, getToken } from '../../utils/session'; import * as flash from '../../utils/flash'; import { Status } from '../../../shared/app.enums'; import { setToken, setUser, setGreenFlash, setRedFlash } from '../creators'; import { Role } from '../../../shared/user.enums'; import { ApplicationsStatus } from '../../../shared/globals.enums'; // Auth Actions // TODO: Signing up should not log user in export const signUp = (body: ICreateUser) => async (dispatch: Dispatch) => { try { const { data: { response } } = await api.post('/auth/signup', body); dispatch(setToken(response.token)); dispatch(setUser(response.user)); setCookie('token', response.token); const resp: ILoginResponse = response; return resp; } catch (error) { throw error.response ? error.response.data : error; } }; export const signIn = (body: ILoginUser) => async (dispatch: Dispatch) => { try { const { data: { response } } = await api.post('/auth/login', body); dispatch(setToken(response.token)); dispatch(setUser(response.user)); setCookie('token', response.token); ReactGA.set({ userId: response.user._id }); const resp: ILoginResponse = response; return resp; } catch (error) { throw error.response ? error.response.data : error; } }; export const signOut = (ctx?: IContext) => async (dispatch: Dispatch) => { try { dispatch(setToken('')); dispatch(setUser(null)); removeCookie('token', ctx); ReactGA.set({ userId: null }); } catch (error) { throw error; } }; export const forgotPassword = async (email: string) => { try { const { data: { response } } = await api.post('/auth/forgot', { email }); return response; } catch (error) { throw error.response ? error.response.data : error; } }; export const resetPassword = async (password: string, passwordConfirm: string, token: string) => { try { const { data: { response } } = await api.post('/auth/reset', { password, passwordConfirm, token }); return response; } catch (error) { throw error.response ? error.response.data : error; } }; // Should only be called in the "server-side" context in _app.tsx export const refreshToken = (ctx?: IContext, params?: any) => async (dispatch: Dispatch) => { try { if (ctx && ctx.res && ctx.res.headersSent) return; const token = getToken(ctx); if (!token) { dispatch(setUser(null)); dispatch(setToken('')); removeCookie('token', ctx); ReactGA.set({ userId: null }); return null; } const { data: { response } } = await api.get('/auth/refresh', { params, headers: { Authorization: `Bearer ${token}` } }); dispatch(setUser(response.user)); dispatch(setToken(response.token)); setCookie('token', response.token, ctx); ReactGA.set({ userId: response.user._id }); return response; } catch (error) { // if (!error.response) throw error; dispatch(setUser(null)); dispatch(setToken('')); removeCookie('token', ctx); ReactGA.set({ userId: null }); return null; } }; // User Actions export const getOwnApplication = async (ctx?: IContext) => { try { const token = getToken(ctx); const id = (jwt.decode(token) as any)._id; return getUserApplication(id, ctx); } catch (error) { throw error.response ? error.response.data : error; } }; export const getUserApplication = async (id: string, ctx?: IContext) => { try { const token = getToken(ctx); const { data: { response } } = await api.get(`/users/${id}/application`, { headers: { Authorization: `Bearer ${token}` } }); const app: IApplication = response; return app; } catch (error) { throw error.response ? error.response.data : error; } }; export const sendApplication = async (body: IApplication, ctx?: IContext, id?: string) => { try { const token = getToken(ctx); if (!id) id = (jwt.decode(token) as any)._id; const { data: { response } } = await api.post(`/users/${id}/apply`, body, { headers: { Authorization: `Bearer ${token}` } }); const app: IApplication = response; return app; } catch (error) { throw error.response ? error.response.data : error; } }; // Application Actions export const getApplications = async (ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.get(`/applications`, { params, headers: { Authorization: `Bearer ${token}` } }); return response; } catch (error) { throw error.response ? error.response.data : error; } }; export const getApplication = async (id: string, ctx?: IContext) => { try { const token = getToken(ctx); const { data: { response } } = await api.get(`/applications/${id}`, { headers: { Authorization: `Bearer ${token}` } }); const app: IApplication = response; return app; } catch (error) { throw error.response ? error.response.data : error; } }; export const updateApplicationStatus = async (id: string, status: Status, ctx?: IContext) => { try { const token = getToken(ctx); const { data: { response } } = await api.post( `/applications/${id}/status`, { status }, { headers: { Authorization: `Bearer ${token}` } } ); const app: IApplication = response; return app; } catch (error) { throw error.response ? error.response.data : error; } }; export const getStats = async (ctx?: IContext) => { try { const token = getToken(ctx); const { data: { response } } = await api.get(`/applications/stats`, { headers: { Authorization: `Bearer ${token}` } }); const stats: IStatsResponse = response; return stats; } catch (error) { throw error.response ? error.response.data : error; } }; // Exec Actions export const getCheckin = async (ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.get(`/exec/checkin`, { params, headers: { Authorization: `Bearer ${token}` } }); const users: IUser[] = response; return users; } catch (error) { throw error.response ? error.response.data : error; } }; export const checkinUser = async (email: string, ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.post( `/exec/checkin/${email}`, {}, { params, headers: { Authorization: `Bearer ${token}` } } ); const user: IUser = response; return user; } catch (error) { throw error.response ? error.response.data : error; } }; // Admin Actions export const getUsers = async (ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.get(`/admin/users`, { params, headers: { Authorization: `Bearer ${token}` } }); const users: IUser[] = response; return users; } catch (error) { throw error.response ? error.response.data : error; } }; export const updateRole = async (email: string, role: Role, ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.post( `/admin/role/`, { email, role }, { params, headers: { Authorization: `Bearer ${token}` } } ); const user: IUser = response; return user; } catch (error) { throw error.response ? error.response.data : error; } }; export const sendMassEmails = async (ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.post( `/admin/emails/`, {}, { params, headers: { Authorization: `Bearer ${token}` } } ); return response; } catch (error) { throw error.response ? error.response.data : error; } }; // Globals Actions export const fetchGlobals = async (ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.get(`/globals/`, { params, headers: { Authorization: `Bearer ${token}` } }); const globals: IGlobals = response; return globals; } catch (error) { throw error.response ? error.response.data : error; } }; export const updateApplicationsStatus = async ( status: ApplicationsStatus, ctx?: IContext, params? ) => { try { const token = getToken(ctx); const { data: { response } } = await api.post( `/globals/status/`, { status }, { params, headers: { Authorization: `Bearer ${token}` } } ); return response; } catch (error) { throw error.response ? error.response.data : error; } }; export const makePublicApplications = async (status: boolean, ctx?: IContext, params?) => { try { const token = getToken(ctx); const { data: { response } } = await api.post( `/globals/public/`, { status }, { params, headers: { Authorization: `Bearer ${token}` } } ); return response; } catch (error) { throw error.response ? error.response.data : error; } }; // Flash Actions export const sendErrorMessage = (msg: string, ctx?: IContext) => (dispatch: Dispatch) => { dispatch(setRedFlash(msg)); flash.set({ red: msg }, ctx); }; export const sendSuccessMessage = (msg: string, ctx?: IContext) => (dispatch: Dispatch) => { dispatch(setGreenFlash(msg)); flash.set({ green: msg }, ctx); }; export const clearFlashMessages = (ctx?: IContext) => (dispatch: Dispatch) => { dispatch(setGreenFlash('')); dispatch(setRedFlash('')); removeCookie('flash', ctx); }; export const storageChanged = e => (dispatch, getState) => { const token = getToken(getState()); if (!token) signOut()(dispatch); else dispatch(setToken(token)); };
dc942ed8fa26e747023a82b9e855f90cc6c85dcc
[ "JavaScript", "TypeScript" ]
10
TypeScript
akshayaravindan/HelloWorld2019
e35447944b651da2a1f05a5083b7ed3506905401
e98bffa387a899111421797d2cd59ba7edd6c6c2
refs/heads/master
<repo_name>jaouadtelmoudy/cvtheque<file_sep>/src/main/java/com/org/entities/Pays.java package com.org.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.RequiredArgsConstructor; import lombok.Setter; @Entity @Table(name="pays") @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Pays { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(name="libelle") private String libelle; } <file_sep>/src/main/java/com/org/controllers/CandidatsController.java package com.org.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; 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.RestController; import com.org.dao.CandidatsDAO; import com.org.entities.Candidats; @RestController @RequestMapping("/candidats") public class CandidatsController { @Autowired private CandidatsDAO candidatsDAO; @GetMapping public List<Candidats> getAllCandidate(){ return candidatsDAO.getAllCandidats(); } @PostMapping public Candidats save(@RequestBody Candidats c){ return candidatsDAO.save(c); } @PutMapping @RequestMapping("/{id}") public Candidats update(@RequestBody Candidats c, @PathVariable Long id){ c.setId(id); return candidatsDAO.update(c); } @DeleteMapping @RequestMapping("/delete/{id}") public void delete(@PathVariable Long id) { Candidats c =new Candidats(); c.setId(id); candidatsDAO.delete(c); } } <file_sep>/src/main/java/com/org/controllers/LoisirsController.java package com.org.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; 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.RestController; import com.org.dao.LoisirsDAO; import com.org.entities.Loisirs; @RestController @RequestMapping("/loisirs") public class LoisirsController { @Autowired private LoisirsDAO loisirsDAO; @GetMapping public List<Loisirs> getAllLoisirs(){ return loisirsDAO.getAllLoisirs(); } @PostMapping public Loisirs save(@RequestBody Loisirs l){ return loisirsDAO.save(l); } @PutMapping @RequestMapping("/{id}") public Loisirs update(@RequestBody Loisirs l, @PathVariable Long id){ l.setId(id); return loisirsDAO.update(l); } @DeleteMapping @RequestMapping("/delete/{id}") public void delete(@PathVariable Long id) { Loisirs l =new Loisirs(); l.setId(id); loisirsDAO.delete(l); } } <file_sep>/src/main/java/com/org/controllers/OrganismesController.java package com.org.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; 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.RestController; import com.org.dao.OrganismesDAO; import com.org.entities.Organisme; @RestController @RequestMapping("/organismes") public class OrganismesController { @Autowired private OrganismesDAO organismesDAO; @GetMapping public List<Organisme> getAllOrganismes(){ return organismesDAO.getAllOrganismes(); } @PostMapping public Organisme save(@RequestBody Organisme o){ return organismesDAO.save(o); } @PutMapping @RequestMapping("/{id}") public Organisme update(@RequestBody Organisme o, @PathVariable Long id){ o.setId(id); return organismesDAO.update(o); } @DeleteMapping @RequestMapping("/delete/{id}") public void delete(@PathVariable Long id) { Organisme o =new Organisme(); o.setId(id); organismesDAO.delete(o); } } <file_sep>/src/main/java/com/org/dao/OffresDAO.java package com.org.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.org.entities.Offres; import com.org.repositories.OffresRepository; @Component public class OffresDAO { @Autowired private OffresRepository offresRepository; public List<Offres> getAllOffres(){ return offresRepository.findAll(); } public Offres save(Offres o) { return offresRepository.save(o); } public Offres update(Offres o) { return offresRepository.saveAndFlush(o); } public void delete(Offres o) { offresRepository.delete(o); } } <file_sep>/src/main/java/com/org/controllers/VillesController.java package com.org.controllers; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; 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.RestController; import com.org.dao.VillesDAO; import com.org.entities.Villes; @RestController @RequestMapping("/villes") public class VillesController { @Autowired private VillesDAO villesDAO; @GetMapping public List<Villes> getAllVilles(){ return villesDAO.getAllVilles(); } @PostMapping public Villes save(@RequestBody Villes v){ return villesDAO.save(v); } @PutMapping @RequestMapping("/{id}") public Villes update(@RequestBody Villes v, @PathVariable Long id){ v.setId(id); return villesDAO.update(v); } @DeleteMapping @RequestMapping("/delete/{id}") public void delete(@PathVariable Long id) { Villes v =new Villes(); v.setId(id); villesDAO.delete(v); } } <file_sep>/src/main/java/com/org/entities/Experiences.java package com.org.entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Table(name="experiences") @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Experiences { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long id; @Column(name="societe") private String societe; @Column(name="poste") private String poste; @Column(name="dateDebut") private Date dateDebut; @Column(name="dateFin") private Date dateFin; } <file_sep>/src/main/java/com/org/dao/VillesDAO.java package com.org.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.org.entities.Villes; import com.org.repositories.VillesRepository; @Service public class VillesDAO { @Autowired private VillesRepository villesRepository; public List<Villes> getAllVilles(){ return villesRepository.findAll(); } public Villes save(Villes v) { return villesRepository.save(v); } public Villes update(Villes v) { return villesRepository.saveAndFlush(v); } public void delete(Villes v) { villesRepository.delete(v); } } <file_sep>/src/main/java/com/org/repositories/ExperiencesRepository.java package com.org.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.org.entities.Experiences; public interface ExperiencesRepository extends JpaRepository<Experiences, Long>{ } <file_sep>/src/main/java/com/org/dao/LanguesDAO.java package com.org.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.org.entities.Langues; import com.org.repositories.LanguesRepository; @Component public class LanguesDAO { @Autowired private LanguesRepository languesRepository; public List<Langues> getAllLangues(){ return languesRepository.findAll(); } public Langues save(Langues l) { return languesRepository.save(l); } public Langues update(Langues l) { return languesRepository.saveAndFlush(l); } public void delete(Langues l) { languesRepository.delete(l); } } <file_sep>/src/main/java/com/org/repositories/FormationsRepository.java package com.org.repositories; import org.springframework.data.jpa.repository.JpaRepository; import com.org.entities.Formations; public interface FormationsRepository extends JpaRepository<Formations, Long> { } <file_sep>/src/main/java/com/org/entities/Formations.java package com.org.entities; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Entity @Table(name="formations") @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Formations { @Id @GeneratedValue(strategy= GenerationType.AUTO) private Long id; @Column(name="diplome") private String diplome; @Column(name="etablissement") private String etablissement; @Column(name="anneeScolaire") private int anneeScolaire; @Column(name="mention") private String mention; } <file_sep>/src/main/java/com/org/dao/CandidatsDAO.java package com.org.dao; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import com.org.entities.Candidats; import com.org.repositories.CandidatsRepository; @Component public class CandidatsDAO { @Autowired private CandidatsRepository candidatsRepository; public List<Candidats> getAllCandidats(){ return candidatsRepository.findAll(); } public Candidats save(Candidats c) { return candidatsRepository.save(c); } public Candidats update(Candidats c) { return candidatsRepository.saveAndFlush(c); } public void delete(Candidats c) { candidatsRepository.delete(c); } }
8932665e0ddc4601edea4e9a113bd7846191966d
[ "Java" ]
13
Java
jaouadtelmoudy/cvtheque
b20b1524d3395af5476db43f35c18c888fa75e41
1b7e90e2a575d34a7ed7a9d4881161a3076451d2
refs/heads/master
<file_sep>from copy import deepcopy from Individual import Individual import unittest from numpy.random import random from random import randint import random from random import sample from Algorithm import Algorithm from Population import population import matplotlib.pyplot as plt def main(size,popsize): """ Make a horse happy by guiding it to a path on the chessboard in such a way that it moves to every single square once and only once. The little horsie can jump obviously only in the classic L shape (the chess’ horse move). Generate random permutations of chess board squares Find best individual Show statistics :param size: Size of the chess board :param popsize: Size of population """ print("Running") tuples=[] popl=[] for i in range(size): for j in range(size): tuples.append((i , j)) for i in range(popsize): random.shuffle(tuples) individ=Individual(size,deepcopy(tuples)) popl.append(deepcopy(individ)) finpop=population(popsize,popl,size) algo=Algorithm(size,finpop) evaluation,fitness,iter=algo.run() #statistics plt.plot(range(iter), fitness, label='BestFitness vs iteration') plt.xlabel('Iteration') plt.ylabel('BestFitness') plt.title("BestFitness evolution") plt.legend() plt.show() main(5,10) <file_sep>from copy import deepcopy import Individual import unittest from numpy.random import random from random import randint import random from random import sample class population: ''' A group of individuals noPop: population size indiv: list of Individuals size: size of the board specified in the problem ''' def __init__(self,noPop,indiv,size): self.noPop=noPop self.indiv=indiv self.size=size def evaluate(self): ''' Give the newly created Individuals fitness values If fitness value of an individual is close to response return said individual :return: Individual if problem is solved , None otherwise ''' for e in self.indiv: if e.fit==0: e.fitness() if e.fit>self.size*self.size-4: return e #print(e.fit) #print("Bye") return None def choose(self,choices): ''' Return a random :param choices: :return: ''' max = sum(choices.values()) pick = random.uniform(0, max) current = 0 for key, value in choices.items(): current += value if current > pick: return key def selection(self,pressure): ''' ranking selection Sort individuals based on fitness,trim population Generate new population :param pressure: value used to specify the selection pressure :return: the fitness of individual 0,presumed best Individual ''' rankedSelect = sorted(self.indiv, key=lambda indiv:indiv.fit,reverse=True) self.indiv = rankedSelect[:self.noPop] #trim the population dictValueRank={} bsize=self.size**2 #give each individual a rank for i in range(len(rankedSelect)): dictValueRank[rankedSelect[i]]=(2-pressure)/(bsize)+2*i*(pressure-1)/(bsize*(bsize-1)) #choose randomly 2 individuals based on their ranks #generate offsprings using orderedCrossover #mutate the children and add them to population for i in range(0,10): indv1 = self.choose(dictValueRank) indv2 = self.choose(dictValueRank) copy1=deepcopy(indv1) copy2=deepcopy(indv2) tup=copy1.orderedCrossover(copy2) tup[0].mutation(0.5) tup[1].mutation(0.5) self.indiv.append(tup[0]) self.indiv.append(tup[1]) return self.indiv[0].fit <file_sep>from Population import population class Algorithm: def __init__(self,size,population): self.size=size self.popl=population def run(self): """ evaluate and select the population until a solution is found :return: solution or best individual, list of best individuals during evolution,number of iterations """ fit=[] iters=0 while self.popl.evaluate()==None: fit.append(self.popl.selection(1.3)) iters+=1 return (self.popl.evaluate(),fit,iters) <file_sep>import unittest from numpy.random import random from random import randint import random from random import sample class Individual: #perm is a permutation of touples (x,y) representing a board square #size is the size of the board #fit is the fitness value of Individual def __init__ (self,size,perm): self.size=size self.perm=perm self.fit=0 self.beginOfSequence=1000 def fitness(self): #returns number of correct horse jumps in the sequence currentSequenceLen = 1 for index in range(0,len(self.perm)-1): xy1 = (self.perm[index][0] - 2, self.perm[index][1] - 1) xy2 = (self.perm[index][0] - 2, self.perm[index][1] + 1) xy3 = (self.perm[index][0] + 2, self.perm[index][1] - 1) xy4 = (self.perm[index][0] + 2, self.perm[index][1] + 1) xy5 = (self.perm[index][0] - 1, self.perm[index][1] - 2) xy6 = (self.perm[index][0] - 1, self.perm[index][1] + 2) xy7 = (self.perm[index][0] + 1, self.perm[index][1] - 2) xy8 = (self.perm[index][0] + 1, self.perm[index][1] + 2) #print(xy1,xy2,xy3,xy4,xy5,xy6,xy7,xy8) if self.perm[index + 1] == xy1 or self.perm[index + 1]==xy2 or self.perm[index + 1]==xy3 or self.perm[index + 1]==xy4 or self.perm[index + 1]==xy5 or self.perm[index + 1]==xy6 or self.perm[index + 1]==xy7 or self.perm[index + 1]==xy8: currentSequenceLen += 1 self.fit= currentSequenceLen def mutation(self,probability): #randomly swap two tuples from sequence r = random.random() if r > probability: idx = range(len(self.perm)) i1, i2 = random.sample(idx, 2) self.perm[i1], self.perm[i2] = self.perm[i2], self.perm[i1] def orderedCrossover(self, ind2): """Executes an ordered crossover (OX) on the input individuals. The two individuals are modified in place. This crossover expects :term:`sequence` individuals of indices, the result for any other type of individuals is unpredictable. :param self: The first individual participating in the crossover. :param ind2: The second individual participating in the crossover. :returns: A tuple of two individuals. Moreover, this crossover generates holes in the input individuals. A hole is created when an attribute of an individual is between the two crossover points of the other individual. Then it rotates the element so that all holes are between the crossover points and fills them with the removed elements in order. """ size = len(self.perm) a, b = random.sample(range(size), 2) if a > b: a, b = b, a newPerm1 = [0] * size newPerm2 = [0] * size for i in range(a,b+1): newPerm1[i]=self.perm[i] #cut part from 1st parent newPerm2[i]=ind2.perm[i] #cut part from 2nd parent i=(b+1)%size while 0 in newPerm1: oldi=i while (ind2.perm[i] in newPerm1): i = (i + 1) % size newPerm1[oldi]=ind2.perm[i] i=(oldi+1)%size i = (b + 1)%size while 0 in newPerm2: oldi = i while (self.perm[i] in newPerm2): i = (i + 1) % size newPerm2[oldi] = self.perm[i] i = (oldi + 1) % size return Individual(size,newPerm1),Individual(size,newPerm2) class TestStringMethods(unittest.TestCase): def test_fit(self): in1=Individual(3,[(0,0),(1,2),(2,0)]) in1.fitness() assert(in1.fit==3) in2 = Individual(5, [(0, 0), (1, 2), (2, 0),(1,1),(2,3)]) in2.fitness() assert (in2.fit == 4) def test_crossover(self): in1 = Individual(3, [(1,1), (2, 2), (3, 3), (4 , 4),(5, 5) ]) in2 = Individual(3, [(5 ,5), (3, 3),(2, 2), (1,1), (4, 4) ]) in3,in4=in1.orderedCrossover(in2) #print(in1.perm,in2.perm) #print(in3.perm,in4.perm) <file_sep># Knight-s-tour Knight's tour problem solved with an evolutionary algorithm Individuals are possible solutions to the problem and are represented here as permutations of tuples containing the possition of the chess board square ( X , Y ). Individuals can generate two new offsprings by applying an ordered crossover on two individuals or mutate. Each Individual has a fitness equal to the number of correct moves on the chess board pressent in the permutation. The Population is a list of Individuals.The population multiplies and then executes a ranked select to return to original size. This process repeats until a suitable answer is found. The initial population is randomly generated. Statistics show the number of iterations of the evolution process and the best Individual of each iteration.
d1b444f8474cb0819bf19f9070734e51dba4e245
[ "Markdown", "Python" ]
5
Python
Ducuvlad/Knight-s-tour
11a3f35b77b73b746232f6f82390ffeb62baead4
bcfa1aaae3e46ad30828af0a1f14792a8c3a3da4
refs/heads/master
<repo_name>murmusandeep/NewsDemo<file_sep>/app/src/main/java/com/example/newsdemo/MainActivity.java package com.example.newsdemo; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; import com.example.newsdemo.Retrofit.ApiClient; import com.example.newsdemo.Retrofit.ApiInterface; import com.example.newsdemo.Retrofit.Articles; import com.example.newsdemo.Retrofit.ArticlesAdapter; import com.example.newsdemo.Retrofit.NewsData; import java.util.Date; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private NewsData newsData; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRecyclerView = findViewById(R.id.recyclerView); mRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL); mRecyclerView.addItemDecoration(dividerItemDecoration); getNewsData(); } private void getNewsData() { ApiInterface apiInterface = ApiClient.getClient(MainActivity.this).create(ApiInterface.class); Call<NewsData> call = apiInterface.getNewsData(); call.enqueue(new Callback<NewsData>() { @Override public void onResponse(Call<NewsData> call, Response<NewsData> response) { newsData = response.body(); //HomeActivityAdapter mainActivitySectionAdapter = new HomeActivityAdapter(HomeActivity.this, mData); //mRecyclerViewSection.setAdapter(mainActivitySectionAdapter); ArticlesAdapter articlesAdapter = new ArticlesAdapter(MainActivity.this, newsData); mRecyclerView.setAdapter(articlesAdapter); } @Override public void onFailure(Call<NewsData> call, Throwable t) { } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.searchNews: Toast.makeText(MainActivity.this, "Search is Clicked", Toast.LENGTH_SHORT).show(); return true; case R.id.setting: Toast.makeText(MainActivity.this, "Setting is Clicked", Toast.LENGTH_SHORT).show(); return true; default: return super.onOptionsItemSelected(item); } } }<file_sep>/app/src/main/java/com/example/newsdemo/Retrofit/ApiInterface.java package com.example.newsdemo.Retrofit; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Query; public interface ApiInterface { @GET("top-headlines?country=in&pageSize=30&apiKey=4ada2e0c19864489967a3d8c5a51c31e") Call<NewsData> getNewsData(); }
f7225ee8169a2490c53fb3ca37be93a19e06767a
[ "Java" ]
2
Java
murmusandeep/NewsDemo
9280f6130f1d746246eb7d824daebf38c367cfbe
4d2d642602e8d2cdef6d7f244774a9e70e4a143e