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>davewinwood/octolux<file_sep>/lib/app.rb # frozen_string_literal: true require 'roda' class App < Roda plugin :json plugin :padrino_render, engine: 'slim', views: 'www/templates', layout: 'layouts/application', cache: false route do |r| r.get '' do render 'index' end r.on 'api' do r.get 'inputs' do LuxListener.inputs end r.get 'registers' do LuxListener.registers end end end end <file_sep>/lib/gpio.rb # frozen_string_literal: true begin # may not be installed if not on a Pi! require 'rpi_gpio' rescue LoadError nil end class GPIO def initialize(gpios:) @gpios = gpios # do nothing if RPi is not available return unless defined?(RPi) RPi::GPIO.set_numbering(:board) RPi::GPIO.set_warnings(false) # initialise each GPIOs as output gpios.each_value { |pin| setup(pin) } end def setup(pin) RPi::GPIO.setup(pin, as: :output) end def on(pin) RPi::GPIO.set_high(lookup_pin(pin)) end def off(pin) RPi::GPIO.set_low(lookup_pin(pin)) end def set(pin, value) value ? on(pin) : off(pin) end private def lookup_pin(pin) pin = gpios[pin] if pin.is_a?(String) raise 'unknown GPIO' unless pin pin end end <file_sep>/Gemfile # frozen_string_literal: true source 'https://rubygems.org' ruby '>= 2.3.0' gem 'zeitwerk' gem 'inifile' gem 'lxp-packet', '~> 0.5.0' group :pi do gem 'rpi_gpio' end group :webserver do gem 'roda' gem 'slim' gem 'tilt' end group :mqtt do gem 'mqtt-sub_handler' end <file_sep>/README.md # LuxPower Inverter / Octopus Time-of-use Tariff Integration This is a Ruby script to parse [Octopus ToU tariff](https://octopus.energy/agile/) prices and control a [LuxPower ACS inverter](https://www.luxpowertek.com/ac-ess.html) according to rules you specify. The particular use-case of this is to charge your home batteries when prices are cheap, and use that power at peak times. There's also support for toggling Raspberry Pi GPIO pins as an added bonus. ## Installation You'll need Ruby - at least 2.3 should be fine, which can be found in all good Linux distributions. This apt-get command also installs the Ruby development headers and a compiler so Ruby can build extensions as part of installing dependencies: ``` sudo apt-get install ruby ruby-dev ruby-bundler git build-essential ``` Clone this repository to your machine: ``` git clone https://github.com/celsworth/octolux.git cd octolux ``` Now install the gems. You may occasionally need to re-run this as I update the repository and bring in new dependencies or update existing ones. This will install gems to `./vendor/bundle`, and so should not need root: ``` bundle update ``` If you are running on a Raspberry Pi and want to use the GPIO support, you can install it with: (you only need to do this once, subsequent `bundle installs` will remember you want the pi package) ``` bundle update --with pi ``` Create a `config.ini` using the `doc/config.ini.example` as a template: ``` cp doc/config.ini.example config.ini ``` This script needs to know: * where to find your Lux inverter, host and port. * the serial numbers of your inverter and datalogger (the plug-in WiFi unit), which are normally printed on the sides. * how many batteries you have, which determines the maximum charge rate (used in agile_cheap_slots rules) * which Octopus tariff you're on, AGILE-18-02-21 is my current one for Octopus Agile. * if you're using MQTT, where to find your MQTT server. * optionally on the Pi, a list of GPIOs you'll be controlling. Copy `rules.rb` from the example as a starting point: ``` cp doc/rules.example.5p.rb rules.rb ``` The idea behind keeping the rules separate is you can edit it and be unaffected by any changes to the main script in the git repository (hopefully). ### Inverter Setup Moved to a separate document, see [INVERTER_SETUP.md](doc/INVERTER_SETUP.md). ## Usage There are two components. ### server.rb `server.rb` is a long-running process that we use for background work. In particular, it monitors the inverter for status packets (these include things like battery state-of-charge). It starts a HTTP server which `octolux.rb` can then query to get realtime inverter data. It can also connect to MQTT and publish inverter information there. See [MQ.md](doc/MQ.md) for more information about this. It's split like this because there's no way to ask the inverter for the current battery SOC. You just have to wait (up to two minutes) for it to tell you. The server will return the latest SOC on-demand via HTTP. The simplest thing to do is just start it in screen: ``` screen ./server.rb ``` A systemd unit file will be added at some point so it starts automatically on boot. ### octolux.rb `octolux.rb` is intended to be from cron, and enables or disables AC charge depending on the logic written in `rules.rb` (you'll need to copy/edit an example from docs/). There's also a wrapper script, `octolux.sh`, which will divert output to a logfile (`octolux.log`), and also re-runs `octolux.rb` if it fails the first time (usually due to transient failures like the inverter not responding, which can occasionally happen). You'll want something like this in cron: ``` 0,30 * * * * /home/pi/octolux/octolux.sh ``` To complement the wrapper script, there's a log rotation script which you can use like this: ``` 59 23 * * * /home/pi/octolux/rotate.sh ``` This will move the current `octolux.log` into `logs/octolux.YYYYMMDD.log` at 23:59 each night. ## Development Notes In your `rules.rb`, you have access to a few objects to do some heavy lifting. *`octopus`* contains Octopus tariff price data. The most interesting method here is `price`: * `octopus.price` - the current tariff price, in pence * `octopus.prices` - a Hash of tariff prices, starting with the current price. Keys are the start time of the price, values are the prices in pence. *`lc`* is a LuxController, which can do the following: * `lc.charge(true)` - enable AC charging * `lc.charge(false)` - disable AC charging * `lc.discharge(true)` - enable forced discharge * `lc.discharge(false)` - disable forced discharge * `lc.charge_pct` - get AC charge power rate, 0-100% * `lc.charge_pct = 50` - set AC charge power rate to 50% * `lc.discharge_pct` - get discharge power rate, 0-100% * `lc.discharge_pct = 50` - set discharge power rate to 50% Forced discharge may be useful if you're paid for export and you have a surplus of stored power when the export rate is high. Setting the power rates is probably a bit of a niche requirement. Note that discharge rate is *all* discharging, not just forced discharge. This can be used to cap the power being produced by the inverter. Setting it to 0 will disable discharging, even if not charging. *`gpio`* is a GPIO controller (only available on the Raspberry Pi). These two methods take a string which corresponds to your configuration. See the example config under the `[gpios]` section. * `gpio.on('zappi')` - turn on the GPIO pin identified as *zappi* in your config. * `gpio.off('zappi')` - turn off the GPIO pin identified as *zappi* in your config. * `gpio.set('zappi', true)` - alternative way of turning on a GPIO. Pass `false` to turn it off.
97d5f565769598212e96be4a0421de93f83d38e8
[ "Markdown", "Ruby" ]
4
Ruby
davewinwood/octolux
529c6f3ca34223d19dc1eb1a985324c277b0f65a
01f6c720796b58220443b29b7b4446d7d0cbe5ea
refs/heads/master
<repo_name>kashenfelter/miktex<file_sep>/Programs/MiKTeX/PackageManager/Qt/MainWindow.cpp /* MainWindow.cpp: Copyright (C) 2008-2018 <NAME> This file is part of MiKTeX Package Manager. MiKTeX Package Manager is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. MiKTeX Package Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with MiKTeX Package Manager; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if defined(__MINGW32__) #define _WIN32_WINNT 0x0600 #endif #include <QtWidgets> #include <QProgressDialog> #include <memory> #include <thread> #include "mpm-version.h" #include <miktex/Core/Debug> #include <miktex/Core/Exceptions> #include <miktex/Core/Paths> #include <miktex/UI/Qt/ErrorDialog> #include <miktex/UI/Qt/PackageInfoDialog> #include <miktex/UI/Qt/SiteWizSheet> #include <miktex/UI/Qt/UpdateDialog> #if defined(MIKTEX_WINDOWS) #include <miktex/Core/win/WindowsVersion.h> #include <commctrl.h> #endif #include "MainWindow.h" #include "PackageProxyModel.h" #include "PackageTableModel.h" using namespace MiKTeX::Core; using namespace MiKTeX::Packages; using namespace MiKTeX::UI::Qt; using namespace std; void MainWindow::SetupFilterToolBar() { toolBarFilter = new QToolBar(this); toolBarFilter->setObjectName(QStringLiteral("fiterToolBar")); addToolBar(Qt::TopToolBarArea, toolBarFilter); lineEditFilter = new QLineEdit(toolBarFilter); lineEditFilter->setClearButtonEnabled(true); toolBarFilter->addWidget(lineEditFilter); toolBarFilter->addAction(actionFilter); connect(lineEditFilter, SIGNAL(returnPressed()), this, SLOT(Filter())); } void MainWindow::SetupContextMenu() { contextMenu = new QMenu(treeView); treeView->setContextMenuPolicy(Qt::ActionsContextMenu); treeView->addAction(actionInstall); treeView->addAction(actionUninstall); treeView->addAction(actionProperties); } MainWindow::MainWindow() : packageManager(PackageManager::Create()) { setupUi(this); SetupFilterToolBar(); SetupContextMenu(); if (session->IsAdminMode()) { setWindowTitle(windowTitle() + " (Admin)"); } model = new PackageTableModel(packageManager, this); proxyModel = new PackageProxyModel(this); proxyModel->setSourceModel(model); proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); treeView->setModel(proxyModel); treeView->sortByColumn(0, Qt::AscendingOrder); connect(treeView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(EnableActions())); connect(actionProperties, SIGNAL(triggered()), this, SLOT(PropertyDialog())); connect(actionSelectInstallablePackages, SIGNAL(triggered()), this, SLOT(SelectInstallablePackages())); connect(actionInstall, SIGNAL(triggered()), this, SLOT(Install())); connect(actionUninstall, SIGNAL(triggered()), this, SLOT(Uninstall())); connect(actionChangeRepository, SIGNAL(triggered()), this, SLOT(RepositoryWizard())); connect(actionUpdateWizard, SIGNAL(triggered()), this, SLOT(UpdateWizard())); connect(actionSynchronize, SIGNAL(triggered()), this, SLOT(Synchronize())); connect(actionAbout, SIGNAL(triggered()), this, SLOT(AboutDialog())); connect(actionFilter, SIGNAL(triggered()), this, SLOT(Filter())); EnableActions(); } void MainWindow::EnableActions() { try { QModelIndexList selectedRows = treeView->selectionModel()->selectedRows(); actionProperties->setEnabled(selectedRows.count() == 1); bool enableInstall = (selectedRows.count() > 0); bool enableUninstall = (selectedRows.count() > 0); if (session->IsMiKTeXDirect()) { enableInstall = false; enableUninstall = false; } for (QModelIndexList::const_iterator it = selectedRows.begin(); it != selectedRows.end() && (enableInstall || enableUninstall); ++it) { PackageInfo packageInfo; if (!model->TryGetPackageInfo(proxyModel->mapToSource(*it), packageInfo)) { MIKTEX_UNEXPECTED(); } if (packageInfo.timeInstalled > 0) { enableInstall = false; enableUninstall = (enableUninstall && packageInfo.isRemovable); } else { enableUninstall = false; } } actionInstall->setEnabled(enableInstall); actionUninstall->setEnabled(enableUninstall); } catch (const MiKTeXException& e) { ErrorDialog::DoModal(this, e); } catch (const exception& e) { ErrorDialog::DoModal(this, e); } } void MainWindow::PropertyDialog() { try { for (const QModelIndex& ind : treeView->selectionModel()->selectedRows()) { PackageInfo packageInfo; if (!model->TryGetPackageInfo(proxyModel->mapToSource(ind), packageInfo)) { MIKTEX_UNEXPECTED(); } PackageInfoDialog::DoModal(this, packageInfo); } } catch (const MiKTeXException& e) { ErrorDialog::DoModal(this, e); } catch (const exception& e) { ErrorDialog::DoModal(this, e); } } void MainWindow::SelectInstallablePackages() { try { QItemSelection selection; for (const auto& p : model->GetData()) { if (p.second.timeInstalled == 0) { selection.append(QItemSelectionRange(proxyModel->mapFromSource(model->index(p.first, 0)))); } } treeView->selectionModel()->select(selection, QItemSelectionModel::Select | QItemSelectionModel::Rows); } catch (const MiKTeXException& e) { ErrorDialog::DoModal(this, e); } catch (const exception& e) { ErrorDialog::DoModal(this, e); } } void MainWindow::Install() { try { vector<string> toBeInstalled; vector<string> toBeRemoved; for (const QModelIndex& ind : treeView->selectionModel()->selectedRows()) { PackageInfo packageInfo; if (!model->TryGetPackageInfo(proxyModel->mapToSource(ind), packageInfo)) { MIKTEX_UNEXPECTED(); } else if (packageInfo.timeInstalled == 0) { toBeInstalled.push_back(packageInfo.deploymentName); } else { toBeRemoved.push_back(packageInfo.deploymentName); } } QString message = tr("Your MiKTeX installation will now be updated:\n\n") + tr("%n package(s) will be installed\n", "", toBeInstalled.size()) + tr("%n package(s) will be removed", "", toBeRemoved.size()); if (QMessageBox::Ok != QMessageBox::information(this, "MiKTeX Package Manager", message, QMessageBox::Ok | QMessageBox::Cancel)) { return; } int ret = UpdateDialog::DoModal(this, packageManager, toBeInstalled, toBeRemoved); if (ret == QDialog::Accepted) { model->Reload(); treeView->update(); } } catch (const MiKTeXException& e) { ErrorDialog::DoModal(this, e); } catch (const exception& e) { ErrorDialog::DoModal(this, e); } } void MainWindow::Uninstall() { Install(); } void MainWindow::RepositoryWizard() { try { if (SiteWizSheet::DoModal(this) == QDialog::Accepted) { emit Synchronize(); } } catch (const MiKTeXException& e) { ErrorDialog::DoModal(this, e); } catch (const exception& e) { ErrorDialog::DoModal(this, e); } } void MainWindow::Synchronize() { try { unique_ptr<PackageInstaller> pInstaller(packageManager->CreateInstaller()); pInstaller->UpdateDbAsync(); int numSteps = 10; QProgressDialog progress(tr("Synchronizing the package database..."), tr("Cancel"), 0, numSteps, this); progress.setWindowModality(Qt::WindowModal); progress.setMinimumDuration(1000); for (int step = 0; !progress.wasCanceled(); ++step) { if (step < numSteps) { progress.setValue(step); } PackageInstaller::ProgressInfo progressinfo = pInstaller->GetProgressInfo(); if (progressinfo.ready) { break; } this_thread::sleep_for(chrono::milliseconds(1000)); } pInstaller->Dispose(); model->Reload(); treeView->update(); if (!progress.wasCanceled()) { progress.setValue(numSteps); } } catch (const MiKTeXException& e) { ErrorDialog::DoModal(this, e); } catch (const exception& e) { ErrorDialog::DoModal(this, e); } } void MainWindow::AboutDialog() { QString message; message = tr("MiKTeX Package Manager"); message += " "; message += MIKTEX_COMPONENT_VERSION_STR; message += "\n\n"; message += tr("MiKTeX Package Manager is free software. You are welcome to redistribute it under certain conditions. See the help file for more information.\n\nMiKTeX Package Manager comes WITH ABSOLUTELY NO WARRANTY OF ANY KIND."); QMessageBox::about(this, tr("MiKTeX Package Manager"), message); } void MainWindow::Filter() { proxyModel->SetFilter(lineEditFilter->text().toUtf8().constData()); } void MainWindow::ContextMenu(const QPoint& point) { QModelIndex index = treeView->indexAt(point); if (index.isValid()) { contextMenu->exec(treeView->mapToGlobal(point)); } } void MainWindow::UpdateWizard() { try { if (!session->UnloadFilenameDatabase()) { MIKTEX_UNEXPECTED(); } PathName exePath = session->GetSpecialPath(SpecialPath::InternalBinDirectory); exePath /= session->IsAdminMode() ? MIKTEX_UPDATE_ADMIN_EXE : MIKTEX_UPDATE_EXE; Process::Start(exePath); } catch (const MiKTeXException& e) { ErrorDialog::DoModal(this, e); } catch (const exception& e) { ErrorDialog::DoModal(this, e); } } <file_sep>/cmake/modules/BundleUtilitiesOverrides.cmake function(gp_item_default_embedded_path_override item default_embedded_path_var) set(path "${${default_embedded_path_var}}") if(item MATCHES "\\.dylib$") set(path "@executable_path/../lib") endif() set(${default_embedded_path_var} "${path}" PARENT_SCOPE) endfunction() <file_sep>/LICENSE.md # MiKTeX Software Copying Conditions To the best of my knowledge, all components of the MiKTeX software are freely redistributable (libre, that is, not necessarily gratis), within the Free Software Foundation's definition and the Debian Free Software Guidelines. That said, the MiKTeX software has neither a single copyright holder nor a single license covering its entire contents, since it is a collection of many independent components. Therefore, you may use the MiKTeX software only if you comply with the requirements placed thereon by the owners of the respective components. To most easily learn these requirements, I suggest checking the source code. <NAME> <file_sep>/Programs/TeXAndFriends/luatex/source/luasocket/src/lua_preload.c #include <stdlib.h> #include "lua.h" #include "lauxlib.h" #include "ftp_lua.c" #include "headers_lua.c" #include "http_lua.c" #include "ltn12_lua.c" #include "mbox_lua.c" #include "mime_lua.c" #include "smtp_lua.c" #include "socket_lua.c" #include "tp_lua.c" #include "url_lua.c" #define TEST(A) do { if (A) { \ fprintf(stderr,"FATAL error while preloading lua module " #A); \ exit(1); \ } \ } while (0) void luatex_socketlua_open (lua_State *L) { TEST(luatex_mbox_lua_open(L)); TEST(luatex_headers_lua_open(L)); TEST(luatex_socket_lua_open(L)); TEST(luatex_ltn12_lua_open(L)); TEST(luatex_mime_lua_open(L)); TEST(luatex_url_lua_open(L)); TEST(luatex_tp_lua_open(L)); TEST(luatex_smtp_lua_open(L)); TEST(luatex_http_lua_open(L)); TEST(luatex_ftp_lua_open(L)); } <file_sep>/Programs/TeXAndFriends/luatex/source/luatex_svnversion.h #define luatex_svn_revision 6574 <file_sep>/Programs/TeXAndFriends/pdftex/source/pdftex_version.h #define PDFTEX_VERSION "1.40.18" <file_sep>/Libraries/MiKTeX/Setup/win/winSetupService.h /* winSetupService.h: internal definitions -*- C++ -*- Copyright (C) 2014-2017 <NAME> This file is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This file is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this file; if not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ BEGIN_INTERNAL_NAMESPACE; struct ShellLinkData { bool isUrl; const char* lpszFolder; const char* lpszName; const char* lpszPathName; unsigned long flags; const char* lpszDescription; const char* lpszArgs; const char* lpszIconPath; int iconIndex; const char* lpszWorkingDir; int showCmd; WORD hotKey; }; class winSetupServiceImpl : public SetupServiceImpl { public: winSetupServiceImpl(); public: virtual void Initialize(); private: void ULogAddRegValue(HKEY hkey, const std::string& valueName, const std::string& value) override; private: void CreateProgramIcons() override; private: void RegisterUninstaller() override; private: void UnregisterShellFileTypes() override; private: void RemoveRegistryKeys() override; private: void UnregisterPath(bool shared) override; private: void RemoveRegistryKey(HKEY hkeyRoot, const MiKTeX::Core::PathName& subKey); private: bool Exists(HKEY hkeyRoot, const MiKTeX::Core::PathName& subKey); private: bool IsEmpty(HKEY hkeyRoot, const MiKTeX::Core::PathName& subKey); private: bool winSetupServiceImpl::RemoveBinDirFromPath(std::string& path); private: void AddUninstallerRegValue(HKEY hkey, const char* valueName, const char* value); private: void AddUninstallerRegValue(HKEY hkey, const char* valueName, DWORD value); private: MiKTeX::Core::PathName CreateProgramFolder(); private: void CreateShellLink(const MiKTeX::Core::PathName& pathFolder, const ShellLinkData& ld); private: void CreateInternetShortcut(const MiKTeX::Core::PathName& path, const char* url); }; END_INTERNAL_NAMESPACE;
6555529c196e8917bc3a00abce54b5a5093c285d
[ "Markdown", "C", "CMake", "C++" ]
7
C++
kashenfelter/miktex
161ab579aebeda6de773dd688085c9d53bdd7bf2
cbd16a4c61d85b1502057c3216a57c4337fcc8d0
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using PartimeSalaryWithTdd.Utility; namespace PartimeSalaryWithTdd { public class SalaryCard { private double normalWorkingHourLimit = 8; public int HourlySalary { get; set; } public DateTime StartTime { get; set; } public DateTime EndTime { get; set; } public double CalculateSalary() { var workingHour = this.GetWorkingHour(); if (workingHour <= normalWorkingHourLimit) { var result = workingHour * this.HourlySalary; return result; } else { var normalPay = normalWorkingHourLimit * this.HourlySalary; var overTimePay = GetOverTimePay(workingHour); var result = normalPay + overTimePay; return result; } } private double GetOverTimePay(double workingHour) { var overTimeHour = GetOverTimeHours(workingHour); // separate two phase of overtime hour var firstOverTime = overTimeHour <= 2 ? overTimeHour : 2; var secondOverTime = overTimeHour > 2 ? overTimeHour - firstOverTime : 0; var firstOverTimePay = firstOverTime * this.FirstOverTimeRatio * this.HourlySalary; var secondOverTimePay = secondOverTime * this.SecondOverTimeRatio * this.HourlySalary; var overTimePay = firstOverTimePay + secondOverTimePay; return overTimePay; } private double GetOverTimeHours(double workingHour) { var overTimeHour = workingHour - normalWorkingHourLimit; // 加班最多只能報4hr var result = overTimeHour > 4 ? 4 : overTimeHour; return result; } private double GetWorkingHour() { var moringEnd = new DateTime(this.StartTime.Year, this.StartTime.Month, this.StartTime.Day, 12, 0, 0); var afternoonStart = new DateTime(this.StartTime.Year, this.StartTime.Month, this.StartTime.Day, 13, 0, 0); var morningWorkhour = DateTimeHelper.TotalHours(this.StartTime, moringEnd); var afternoonWorkhour = DateTimeHelper.TotalHours(afternoonStart, this.EndTime); var workingHour = morningWorkhour + afternoonWorkhour; return workingHour; } public double FirstOverTimeRatio { get; set; } public int SecondOverTimeRatio { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PartimeSalaryWithTdd.Utility { public static class DateTimeHelper { /// <summary> /// 傳入兩個時間,回傳間隔的小時數 /// </summary> /// <param name="start"></param> /// <param name="end"></param> /// <returns></returns> public static double TotalHours(DateTime start, DateTime end) { var result = new TimeSpan(end.Ticks - start.Ticks).TotalHours; return result; } } } <file_sep>using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using PartimeSalaryWithTdd; namespace PartimeSalaryWithTdd.Tests { /// <summary> /// SalaryCardTests 的摘要描述 /// </summary> [TestClass] public class SalaryCardTests { public SalaryCardTests() { // // TODO: 在此加入建構函式的程式碼 // } private TestContext testContextInstance; /// <summary> ///取得或設定提供目前測試回合 ///的相關資訊與功能的測試內容。 ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region 其他測試屬性 // // 您可以使用下列其他屬性撰寫您的測試: // // 執行該類別中第一項測試前,使用 ClassInitialize 執行程式碼 // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // 在類別中的所有測試執行後,使用 ClassCleanup 執行程式碼 // [ClassCleanup()] // public static void MyClassCleanup() { } // // 在執行每一項測試之前,先使用 TestInitialize 執行程式碼 // [TestInitialize()] // public void MyTestInitialize() { } // // 在執行每一項測試之後,使用 TestCleanup 執行程式碼 // [TestCleanup()] // public void MyTestCleanup() { } // #endregion 其他測試屬性 [TestMethod] public void TestCalculateSalary_沒有加班_正常上班8小時_時薪100乘以8_薪資應為800() { //Scenario: 沒有加班,正常上班8小時,時薪100乘以8,薪資應為800 //Given 正常上班一小時薪資為 100 //And 上班時間時間為 "2014/8/30 08:00:00" //And 下班時間為 "2014/8/30 17:00:00" //When 呼叫CalculateSalary方法 //Then 薪資計算結果應為 800 var target = new SalaryCard(); target.HourlySalary = 100; target.StartTime = new DateTime(2014, 8, 30, 8, 0, 0); target.EndTime = new DateTime(2014, 8, 30, 17, 0, 0); //act var actual = target.CalculateSalary(); //assert var expected = 800; Assert.AreEqual(expected, actual); } [TestMethod] public void TestCalculateSalary_加班2小時_加班頭2小時比例為1點66_薪資應為1132() { //Scenario: 加班2小時: // 上班8小時,時薪100乘以8,加班2小時,加班費100乘以1.66乘以2,薪資應為1132 // Given 正常上班一小時薪資為 100 // And 加班薪資頭2小時,時薪比例為 1.66 // And 上班時間為 "2014/8/30 08:00:00" // And 下班時間為 "2014/8/30 19:00:00" // When 呼叫CalculateSalary方法 // Then 薪資計算結果應為 1132 var target = new SalaryCard(); target.HourlySalary = 100; //新增property target.FirstOverTimeRatio = 1.66; target.StartTime = new DateTime(2014, 8, 30, 8, 0, 0); target.EndTime = new DateTime(2014, 8, 30, 19, 0, 0); //act var actual = target.CalculateSalary(); //assert var expected = 1132; Assert.AreEqual(expected, actual); } [TestMethod] public void TestCalculateSalary_加班3小時_加班頭2小時比例為1點66_加班第3小時起比例為2_薪資應為1332() { //Scenario: 加班3小時: // 上班8小時,時薪100乘以8,加班前2小時,加班費100乘以1.66乘以2,加班第3小時起,加班費100乘以2,薪資應為1332 // Given 正常上班一小時薪資為 100 // And 加班薪資頭2小時,時薪比例為 1.66 // And 加班薪資第3小時開始,時薪比例為 2 // And 上班時間為 "2014/8/30 08:00:00" // And 下班時間為 "2014/8/30 20:00:00" // When 呼叫CalculateSalary方法 // Then 薪資計算結果應為 1332 var target = new SalaryCard(); target.HourlySalary = 100; target.FirstOverTimeRatio = 1.66; //新增property target.SecondOverTimeRatio = 2; target.StartTime = new DateTime(2014, 8, 30, 8, 0, 0); target.EndTime = new DateTime(2014, 8, 30, 20, 0, 0); //act var actual = target.CalculateSalary(); //assert var expected = 1332; Assert.AreEqual(expected, actual); } [TestMethod] public void TestCalculateSalary_加班5小時最多只能申報4小時_加班頭2小時比例為1點66_加班第3與第4小時比例為2_薪資應為1532() { //Scenario: 加班5小時,加班只能申報4小時 // 上班8小時,時薪100乘以8,加班前2小時,加班費100乘以1.66乘以2,加班第3小時與第4小時,加班費100乘以2乘以2,薪資應為1532 // Given 正常上班一小時薪資為 100 // And 加班薪資頭2小時,時薪比例為 1.66 // And 加班薪資第3小時開始,時薪比例為 2 // And 上班時間為 "2014/8/30 08:00:00" // And 下班時間為 "2014/8/30 22:00:00" // When 呼叫CalculateSalary方法 // Then 薪資計算結果應為 1532 var target = new SalaryCard(); target.HourlySalary = 100; target.FirstOverTimeRatio = 1.66; target.SecondOverTimeRatio = 2; target.StartTime = new DateTime(2014, 8, 30, 8, 0, 0); target.EndTime = new DateTime(2014, 8, 30, 22, 0, 0); //act var actual = target.CalculateSalary(); //assert var expected = 1532; Assert.AreEqual(expected, actual); } } }
76db5088f8064aba964c6f643899535169be86f6
[ "C#" ]
3
C#
hatelove/PartimeSalaryWithTdd
9dd053426efa31393b6cb70916e30fb680149800
d9fc257a2b8939143564e31dd4a7bd902062be76
refs/heads/master
<repo_name>akkasuddin/NeoQuad<file_sep>/QuadTimer.cpp #include "QuadTimer.h" double QuadTimer::StartTime = GetCurrentSystemTime(); QuadTimer::QuadTimer() { time = GetCurrentSystemTime(); } double QuadTimer::GetProcessTime() { return GetCurrentSystemTime() - StartTime; } double QuadTimer::getTimeDiffSec() { double time2 = GetCurrentSystemTime(); double diffTime = time2 - time; time = time2; return diffTime; } double QuadTimer::GetCurrentSystemTime() { struct timeval time; if (gettimeofday(&time,NULL)){ // Handle error return 0; } return (double)time.tv_sec + (double)time.tv_usec * .000001; } <file_sep>/main.cpp /****************************************************************** * Name: main.cpp * Purpose: main routines are defined here * * Author: <NAME> * Email : <EMAIL> * * Creation Date: 09/19/2015 *******************************************************************/ #include<iostream> #include<cmath> #include<GL/glut.h> #include "QuadTimer.h" #include "camera.h" #include "NeoQuad.h" #include "Button.h" //#include <pthread.h> //#include "SOIL.h" using namespace std; using namespace glm; //Create the Camera Camera camera; /* void *simplefunc(void*) { return NULL; } void forcePThreadLink(){ pthread_t t1; pthread_create(&t1,NULL,&simplefunc,NULL); } */ class Window { public: Window() { this->interval = 1000 / 60; //60 FPS this->window_handle = -1; } int window_handle, interval; ivec2 size; float window_aspect; } window; //Resize the window and properly update the camera viewport void ReshapeFunc(int w, int h) { if (h > 0) { window.size = ivec2(w, h); window.window_aspect = float(w) / float(h); } camera.SetViewport(0, 0, window.size.x, window.size.y); } //Keyboard input for camera, also handles exit case void CameraKeyboardFunc(unsigned char c, int x, int y) { switch (c) { case 'i': camera.Move(FORWARD); break; case 'j': camera.Move(LEFT); break; case 'k': camera.Move(BACK); break; case 'l': camera.Move(RIGHT); break; case 'u': camera.Move(DOWN); break; case 'o': camera.Move(UP); break; case 'x': case 27: exit(0); return; default: break; } } bool cameraControltoggle = true; //Used when person clicks mouse void CallBackMouseFunc(int mousebutton, int state, int x, int y) { if(cameraControltoggle) camera.SetPos(mousebutton, state, x, y); if(Button::checkClick(state, x,window.size.y-y)!=NULL) { if(state == GLUT_DOWN) cameraControltoggle = false; } if(state == GLUT_UP) cameraControltoggle = true; } //Used when person drags mouse around void CallBackMotionFunc(int x, int y) { if(cameraControltoggle) camera.Move2D(x, y); } //Redraw based on fps set for window void TimerFunc(int value) { if (window.window_handle != -1) { glutTimerFunc(window.interval, TimerFunc, value); glutPostRedisplay(); } } void initializeRendering() { glEnable(GL_TEXTURE_2D); // Enable texture mapping. glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // glBlendFunc(GL_SRC_ALPHA, GL_ONE); // Set the blending function for translucency (note off at init time) glClearColor(0.0f, 0.0f, 0.0f, 0.0f); // This Will Clear The Background Color To Black glClearDepth(1.0); // Enables Clearing Of The Depth Buffer glDepthFunc(GL_LESS); // type of depth test to do. glEnable(GL_DEPTH_TEST); // enables depth testing. glShadeModel(GL_SMOOTH); // Enables Smooth Color Shading glEnable(GL_LIGHTING); //Enable lighting glMatrixMode(GL_MODELVIEW); glEnable(GL_MULTISAMPLE); /*****************************************For Background***********************/ GLfloat ambientColor[] = {0.2f, 0.2f, 0.2f, 1.0f}; //Color (0.2, 0.2, 0.2) glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientColor); GLfloat LightAmbient[] = {0.5f, 0.5f, 0.5f, 1.0f}; GLfloat lightColor1[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Color (0.5, 0.2, 0.2) GLfloat lightPos1[] = {-1.0f, 0.5f, 0.5f, 0.0f}; glLightfv(GL_LIGHT1, GL_DIFFUSE, lightColor1); glLightfv(GL_LIGHT1, GL_POSITION, lightPos1);//*/ glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient); glEnable(GL_LIGHT1); GLfloat lightColor0[] = {0.5f, 0.5f, 0.5f, 1.0f}; //Color (0.5, 0.5, 0.5) GLfloat lightPos0[] = {4.0f, 0.0f, 8.0f, 1.0f}; //Positioned at (4, 0, 8) const GLfloat light_ambient[] = { 0.0f, 0.0f, 0.0f, 1.0f }; glLightfv(GL_LIGHT0, GL_DIFFUSE, lightColor0); glLightfv(GL_LIGHT0, GL_POSITION, lightPos0); glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient); glEnable(GL_LIGHT0); /*****************************************For Background***********************/ glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glEnable(GL_COLOR_MATERIAL); // glEnable(GL_LIGHT0); //Enable light #0 // glEnable(GL_LIGHT1); //Enable light #1 glEnable(GL_NORMALIZE); //Automatically normalize normals glEnable(GL_CULL_FACE); // glHint( GL_LINE_SMOOTH_HINT, GL_NICEST ); // glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST ); } Button *powerButton,*speedUpButton, *speedDownButton; NeoQuad *neoQuad; void keypressHandler(unsigned char key, int x, int y) { switch (key) { case 'd': neoQuad->yawQuad(2); break; case 'a': neoQuad->yawQuad(-2); break; case 's': neoQuad->rollQuad(2); break; case 'w': neoQuad->rollQuad(-2); break; case 'q': neoQuad->pitchQuad(2); break; case 'e': neoQuad->pitchQuad(-2); break; case ';': neoQuad->changePropSpeed(-0.1); break; case '\'': neoQuad->changePropSpeed(0.1); break; case 'p': neoQuad->powerToggle(); break; case 'm': neoQuad->toggleAnimate(); break; case 13: exit(0); }; CameraKeyboardFunc(key,x,y); //glutPostRedisplay(); } GLuint textures[1]; void drawHandler() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor(0.0f, 0.25f, 0.0f, 1.0f); glClearDepth(1.0); // Enables Clearing Of The Depth Buffer glPushMatrix(); // glMatrixMode(GL_MODELVIEW); glViewport(0, 0, window.size.x, window.size.y); glm::mat4 model, view, projection; camera.Update(); camera.GetMatricies(projection, view, model); glm::mat4 mvp = projection* view * model; //Compute the mvp matrix glLoadMatrixf(glm::value_ptr(mvp)); // glColor4f(1.0f,1.0f,1.0f,1.0f); //* glBindTexture(GL_TEXTURE_2D, textures[0]); neoQuad->draw(); glPopMatrix(); //should always be at the end //reset projection matrix glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f, window.size.x, 0.0f,window.size.y, 0.0f, 100000.0f); //reset Modelview matrix glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //draw all buttons Button::drawButtons(); glutSwapBuffers(); } void powerButtonCallback() { neoQuad->powerToggle(); } void speedUpCallback() { neoQuad->changePropSpeed(0.1); } void speedDownCallback() { neoQuad->changePropSpeed(-0.1); } int main(int argc, char** argv) { glutInit(&argc, argv); //initialize glut glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA| GLUT_MULTISAMPLE); //initialize display mode glutInitWindowSize(1280, 720); glutInitWindowPosition(0, 0); //loadGLTextures(); //glEnable(GL_TEXTURE_2D); //xx = xx+1; window.window_handle = glutCreateWindow("Age of Quadrones"); //create window powerButton = new Button(100,110,200,90,"PowerUP",powerButtonCallback); speedUpButton = new Button(50,90,150,70,"SpeedUP",speedUpCallback); speedDownButton = new Button(150,90,250,70,"SpeedDN",speedDownCallback); glutReshapeFunc(ReshapeFunc); glutDisplayFunc(drawHandler); glutKeyboardFunc(keypressHandler); glutMouseFunc(CallBackMouseFunc); glutMotionFunc(CallBackMotionFunc); glutTimerFunc(window.interval, TimerFunc, 0); neoQuad = new NeoQuad(); neoQuad->moveAbs(10,60,0); initializeRendering();//Setup camera //loadGLTextures(); camera.SetMode(FREE); camera.SetPosition(glm::vec3(0, 60, 100)); camera.SetLookAt(glm::vec3(0, 60, 0)); camera.SetClipping(.1, 80000); camera.SetFOV(45); //Start the glut loop! glutMainLoop(); return 0; } <file_sep>/Quadrotor.cpp /****************************************************************** * Name : Quadrotor.cpp * Purpose: Quadrotor member functions defined here * * Author: <NAME> * Email : <EMAIL> * * Creation Date: 09/19/2015 *******************************************************************/ #include<GL/gl.h> #include<GL/glu.h> #include<GL/glut.h> #include"Quadrotor.h" Quadrotor::Quadrotor() { Model = glm::mat4(1.0f); axisLength = 20; rotationSpeed = 5; quadricObj = gluNewQuadric(); gluQuadricNormals(quadricObj, GLU_SMOOTH); // Create Smooth Normals ( NEW ) gluQuadricTexture(quadricObj, GL_TRUE); // Create Texture Coords ( NEW ) pos_x = pos_y = pos_z = 0.0f; turnoff = false; isInMotion = false; } void Quadrotor::drawAxes() { glPushMatrix(); glBegin(GL_LINES); glColor3f(1.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(axisLength, 0.0f, 0.0f); glColor3f(0.0f, 1.0f, 0.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, axisLength, 0.0f); glColor3f(0.0f, 0.0f, 1.0f); glVertex3f(0.0f, 0.0f, 0.0f); glVertex3f(0.0f, 0.0f, axisLength); glEnd(); glPopMatrix(); } void Quadrotor::rollQuad(float angle) { float xx = angle * Pi/180; Model = glm::rotate(Model, xx, glm::vec3(0, 0, 1)); } void Quadrotor::pitchQuad(float angle) { float xx = angle * Pi/180; Model = glm::rotate(Model, xx, glm::vec3(1,0, 0)); } void Quadrotor::yawQuad(float angle) { float xx = angle * Pi/180; Model = glm::rotate(Model, xx, glm::vec3(0, 1, 0)); } float Quadrotor::getPitch() { return 0; } float Quadrotor::getRoll() { return 0; } float Quadrotor::getYaw() { return 0; } void Quadrotor::moveAbs(GLfloat x, GLfloat y, GLfloat z) { pos_x = x; pos_y = y; pos_z = z; } void Quadrotor::moveRel(GLfloat x, GLfloat y, GLfloat z) { pos_x += x; pos_y += y; pos_z += z; } void Quadrotor::draw() { glMatrixMode(GL_MODELVIEW); glPushMatrix(); //Main push glLoadIdentity(); //move(); glTranslatef(pos_x, pos_y, pos_z); drawQuad(); glPopMatrix(); } void Quadrotor::move() { //* if(!turnoff) { double current_time = QuadTimer::GetProcessTime(); if(!isInMotion) { if(sscanf(timeline->readNextCommand(),"%lf %lf %lf %lf",&com_time,&com_posx,&com_posy,&com_posz)==EOF) {turnoff = true; return;} isInMotion = true; quadTime.getTimeDiffSec(); // printf("\nGot command:%f %f %f %f",com_time,com_posx,com_posy,com_posz); } else if(current_time<=com_time) { glm::vec3 distance = glm::vec3(com_posx-pos_x,com_posy-pos_y,com_posz-pos_z); double delta_time = com_time-current_time; glm::vec3 dist2 = distance *(float) (quadTime.getTimeDiffSec()/ delta_time); moveRel(dist2.x,dist2.y,dist2.z); // printf("\ndelta pos:%f %f %f",dist2.x,dist2.y,dist2.z); } else isInMotion = false; // printf("\ncurrent pos:%f %f %f",pos_x, pos_y,pos_z); } //*/ } Quadrotor::~Quadrotor() { gluDeleteQuadric(quadricObj); delete timeline; }<file_sep>/ImageLoader/gifIO.h #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <setjmp.h> #include <signal.h> extern "C" { #include <gif_lib.h> } #define min(a,b) ((a) < (b) ? (a) : (b)) #define gflush return(FH_ERROR_FILE); #define grflush { DGifCloseFile(gft); return(FH_ERROR_FORMAT); } #define mgrflush { free(lb); free(slb); DGifCloseFile(gft); return(FH_ERROR_FORMAT); } #define agflush return(FH_ERROR_FORMAT); #define agrflush { DGifCloseFile(gft); return(FH_ERROR_FORMAT); } /***********************************************************/ /* GLOBAL DEFINES */ /***********************************************************/ typedef unsigned char uchar; struct formathandler { struct formathandler *next; int (*get_size)(char *, int *, int*); int (*get_pic)(char *, uchar *, int, int); int (*id_pic)(char *); }; #define FH_ERROR_OK 0 #define FH_ERROR_FILE 1 #define FH_ERROR_FORMAT 2 /***********************************************************/ /* FUNTION PROTOTYPES */ /***********************************************************/ void add_format(int (*picsize)(char *,int *,int*), int (*picread)(char *,unsigned char *,int,int), int (*id)(char*)); extern int fh_gif_getsize(char *, int *, int*); extern int fh_gif_load(char *,uchar *, int,int); extern int fh_gif_id(char *); void GIF_FILE_READ(char *FileName, uchar data[], int *color); <file_sep>/Quadrotor.h /****************************************************************** * Name : Quadrotor.h * Purpose: Header File for Quadrotor * * Author: <NAME> * Email : <EMAIL> * * Creation Date: 10/20/2015 *******************************************************************/ #ifndef QUADROTOR_H # define QUADROTOR_H #include "QuadTimer.h" #include "Timeline.h" #include <cstdio> # include<GL/glu.h> #include <glm/matrix.hpp> #include <glm/gtc/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective using namespace std; #ifndef Pi #define Pi 3.1415926535897932384626433832795 #endif // Virtual Class for use by all quadrotors. // Houses common functions that govern motion and orientation of the quadrotors class Quadrotor { protected: QuadTimer quadTime; Timeline *timeline; bool isInMotion; bool turnoff; double com_time; double com_posx,com_posy,com_posz; glm::mat4 Model; float axisLength; unsigned int rotationSpeed; GLUquadric *quadricObj; void drawAxes(); GLfloat pos_x,pos_y,pos_z; public: //Contructor Quadrotor(); //Applies Roll relative to the current orientation void rollQuad(float angle); //Applies Pitch relative to the current orientation void pitchQuad(float angle); //Applies Yaw relative to the current orientation void yawQuad(float angle); float getRoll(); float getPitch(); float getYaw(); void moveAbs(GLfloat x,GLfloat y,GLfloat z); void moveRel(GLfloat x,GLfloat y,GLfloat z); void draw(); void move(); virtual void drawQuad() = 0; ~Quadrotor(); }; #endif <file_sep>/ImageLoader/bmpIO.cpp /***********************************************************/ /* */ /* BMP */ /* */ /* Written by <NAME>. */ /***********************************************************/ #include "bmpIO.h" static unsigned short read_word(FILE *fp); static unsigned int read_dword(FILE *fp); static int read_long(FILE *fp); static int write_word(FILE *fp, unsigned short w); static int write_dword(FILE *fp, unsigned int dw); static int write_long(FILE *fp, int l); /****************************************/ /* Load a DIB/BMP file from disk. */ /****************************************/ uchar *LoadDIBitmap(char filename[], BITMAPINFO **info) { uchar *bits; /* Bitmap pixel bits */ uchar *ptr; /* Pointer into bitmap */ uchar temp; /* Temporary variable to swap red and blue */ int x, y; /* X and Y position in image */ int length; /* Line length */ int bitsize; /* Size of bitmap */ int infosize; /* Size of header information */ FILE *fp; /* Open file pointer */ BITMAPFILEHEADER header; /* File header */ if ((fp = fopen(filename, "rb")) == NULL) return NULL; header.bfType = read_word(fp); header.bfSize = read_dword(fp); header.bfReserved1 = read_word(fp); header.bfReserved2 = read_word(fp); header.bfOffBits = read_dword(fp); if (header.bfType != BF_TYPE) { fclose(fp); return NULL; } infosize = (header.bfOffBits - 18); if ((*info = (BITMAPINFO *)malloc(sizeof(BITMAPINFO))) == NULL) { fclose(fp); return NULL; } (*info)->bmiHeader.biSize = read_dword(fp); (*info)->bmiHeader.biWidth = read_long(fp); (*info)->bmiHeader.biHeight = read_long(fp); (*info)->bmiHeader.biPlanes = read_word(fp); (*info)->bmiHeader.biBitCount = read_word(fp); (*info)->bmiHeader.biCompression = read_dword(fp); (*info)->bmiHeader.biSizeImage = read_dword(fp); (*info)->bmiHeader.biXPelsPerMeter = read_long(fp); (*info)->bmiHeader.biYPelsPerMeter = read_long(fp); (*info)->bmiHeader.biClrUsed = read_dword(fp); (*info)->bmiHeader.biClrImportant = read_dword(fp); if (infosize > 40) { if (fread((*info)->bmiColors, infosize - 40, 1, fp) < 1) { free(*info); fclose(fp); return NULL; } } if ((bitsize = (*info)->bmiHeader.biSizeImage) == 0) { bitsize = ((*info)->bmiHeader.biWidth * (*info)->bmiHeader.biBitCount + 7) / 8 * abs((*info)->bmiHeader.biHeight); } if ((bits = (uchar *)calloc(bitsize, 1)) == NULL) { free(*info); fclose(fp); return NULL; } if (fread(bits, 1, bitsize, fp) < bitsize) { free(*info); free(bits); fclose(fp); return NULL; } /* Swap red and blue */ /* length = ((*info)->bmiHeader.biWidth * 3 + 3) & ~3; for (y = 0; y < (*info)->bmiHeader.biHeight; y ++) { for (ptr = bits + y * length, x = (*info)->bmiHeader.biWidth; x > 0; x --, ptr += 3) { temp = ptr[0]; ptr[0] = ptr[2]; ptr[2] = temp; } } */ fclose(fp); return bits; } /****************************************/ /* Save a DIB/BMP file to a disk. */ /****************************************/ int SaveDIBitmap(char filename[], BITMAPINFO *info, uchar *bits) { FILE *fp; /* Open file pointer */ int size, /* Size of file */ infosize, /* Size of bitmap info */ bitsize; /* Size of bitmap pixels */ if ((fp = fopen(filename, "wb")) == NULL) return (-1); if (info->bmiHeader.biSizeImage == 0) { bitsize = (info->bmiHeader.biWidth * info->bmiHeader.biBitCount + 7) / 8 * abs(info->bmiHeader.biHeight); } else { bitsize = info->bmiHeader.biSizeImage; } infosize = sizeof(BITMAPINFOHEADER); switch (info->bmiHeader.biCompression) { case BI_BITFIELDS : infosize += 12; if (info->bmiHeader.biClrUsed == 0) break; case BI_RGB : if (info->bmiHeader.biBitCount > 8 && info->bmiHeader.biClrUsed == 0) break; case BI_RLE8 : case BI_RLE4 : if (info->bmiHeader.biClrUsed == 0) { infosize += (1 << info->bmiHeader.biBitCount) * 4; } else { infosize += info->bmiHeader.biClrUsed * 4; } break; } size = sizeof(BITMAPFILEHEADER) + infosize + bitsize; write_word(fp, BF_TYPE); /* bfType */ write_dword(fp, size); /* bfSize */ write_word(fp, 0); /* bfReserved1 */ write_word(fp, 0); /* bfReserved2 */ write_dword(fp, 18 + infosize); /* bfOffBits */ write_dword(fp, info->bmiHeader.biSize); write_long(fp, info->bmiHeader.biWidth); write_long(fp, info->bmiHeader.biHeight); write_word(fp, info->bmiHeader.biPlanes); write_word(fp, info->bmiHeader.biBitCount); write_dword(fp, info->bmiHeader.biCompression); write_dword(fp, info->bmiHeader.biSizeImage); write_long(fp, info->bmiHeader.biXPelsPerMeter); write_long(fp, info->bmiHeader.biYPelsPerMeter); write_dword(fp, info->bmiHeader.biClrUsed); write_dword(fp, info->bmiHeader.biClrImportant); if (infosize > 40) { if (fwrite(info->bmiColors, infosize - 40, 1, fp) < 1) { fclose(fp); return (-1); } } if (fwrite(bits, 1, bitsize, fp) < bitsize) { fclose(fp); return (-1); } fclose(fp); return (0); } /****************************************/ /* Read a 16-bit unsigned integer. */ /****************************************/ static unsigned short read_word(FILE *fp) { uchar b0, b1; b0 = getc(fp); b1 = getc(fp); return ((b1 << 8) | b0); } /****************************************/ /* Read a 32-bit unsigned integer. */ /****************************************/ static unsigned int read_dword(FILE *fp) { uchar b0, b1, b2, b3; b0 = getc(fp); b1 = getc(fp); b2 = getc(fp); b3 = getc(fp); return ((((((b3 << 8) | b2) << 8) | b1) << 8) | b0); } /****************************************/ /* Read a 32-bit signed integer. */ /****************************************/ static int read_long(FILE *fp) { uchar b0, b1, b2, b3; b0 = getc(fp); b1 = getc(fp); b2 = getc(fp); b3 = getc(fp); return ((int)(((((b3 << 8) | b2) << 8) | b1) << 8) | b0); } /****************************************/ /* Write a 16-bit unsigned integer. */ /* O - 0 on success, -1 on error */ /****************************************/ static int write_word(FILE *fp, unsigned short w) { putc(w, fp); return (putc(w >> 8, fp)); } /****************************************/ /* Write a 32-bit unsigned integer. */ /* O - 0 on success, -1 on error */ /****************************************/ static int write_dword(FILE *fp, unsigned int dw) { putc(dw, fp); putc(dw >> 8, fp); putc(dw >> 16, fp); return (putc(dw >> 24, fp)); } /****************************************/ /* Write a 32-bit signed integer. */ /* O - 0 on success, -1 on error */ /****************************************/ static int write_long(FILE *fp, int l) { putc(l, fp); putc(l >> 8, fp); putc(l >> 16, fp); return (putc(l >> 24, fp)); } <file_sep>/ImageLoader/pgmIO.cpp #include "pgmIO.h" /***********************************************************/ /* PGM FILE IO ROUTINES */ /***********************************************************/ /****************************************/ /* Read PGM formatted image. */ /****************************************/ void pgmCommentClear(FILE *disk){ uchar ch; fpos_t *pos; fread(&ch, 1, 1, disk); if (ch != '#') { fseek(disk, -1, SEEK_CUR); return; } do { while (ch != '\n') fread(&ch, 1, 1, disk); } while (ch == '#'); pgmCommentClear(disk); } uchar *PGM_FILE_READ(char *FileName, int *Width, int *Height, int *color) { int x, y, k = 0; int pmax; char ch; char type[3]; uchar *temp; FILE *disk; if ((disk = fopen(FileName, "rb")) == NULL) { return NULL; } fscanf(disk, "%s", &type); if (!strcmp(type, "P6")) *color = 1; else *color = 0; fread(&ch, 1, 1, disk); pgmCommentClear(disk); fscanf(disk, "%d", Width); fscanf(disk, "%d", Height); fscanf(disk, "%d", &pmax); fread(&ch, 1, 1, disk); if (*color == 1) { temp = (uchar *)calloc(*Height**Width, 3); fread(temp, 1, *Height**Width*3, disk); } else { temp = (uchar *)calloc(*Height**Width, 1); fread(temp, 1, *Height**Width, disk); } fclose(disk); return temp; } /****************************************/ /* Write PGM formatted image. */ /****************************************/ void PGM_FILE_WRITE(char *FileName, uchar data[], int targetW, int targetH, int color) { int x, y, k = 0; FILE *disk; disk = fopen(FileName, "wb"); if (color == 1) fprintf(disk, "P6\n"); else fprintf(disk, "P5\n"); fprintf(disk, "%d %d\n", targetW, targetH); fprintf(disk, "255\n"); if (color == 1) fwrite(data, 1, targetH*targetW*3, disk); else fwrite(data, 1, targetH*targetW, disk); fclose(disk); } <file_sep>/Timeline.cpp #include "Timeline.h" Timeline::Timeline(char* tag) { numCommands = 0; currentCommand = 0; FILE* fin = fopen("Data/Timeline.txt","rt"); if(fin==NULL) { printf("Data/Timeline.txt not found"); exit(0); } int i; bool flag = false; double time = 0; char templine[256]; while(!feof(fin)) { fgets(templine,255,fin); if(strstr(templine,"TIM")!=NULL && templine[0]!='#') { sscanf(templine,"TIM %lf",&time); } if(strstr(templine,tag)!=NULL && templine[0]!='#') { sprintf(commands[numCommands++],"%lf %s",time,templine+4); } } fclose(fin); } char* Timeline::readNextCommand() { if(currentCommand==numCommands) return " "; return commands[currentCommand++]; } void Timeline::displayLines() { for(int i=0; i<numCommands; i++) { printf((const char*)commands);} } Timeline::~Timeline() { /* for(vector<char*>::iterator it = lines.begin(); it!=lines.end(); ++it) { delete[] *it;} */ } <file_sep>/ImageLoader/gifIO.cpp #include "gifIO.h" int fh_gif_id(char *name) { int fd; char id[4]; fd = open(name,O_RDONLY); if(fd==-1) return(0); read(fd,id,4); close(fd); if (id[0] == 'G' && id[1] == 'I' && id[2] == 'F') return(1); return(0); } inline void m_rend_gif_decodecolormap(uchar *cmb, uchar *rgbb, ColorMapObject *cm, int s, int l) { int i; GifColorType *cmentry; for (i = 0; i < l; i++) { cmentry=&cm->Colors[cmb[i]]; *(rgbb++)=cmentry->Red; *(rgbb++)=cmentry->Green; *(rgbb++)=cmentry->Blue; } } int fh_gif_load(char *name, uchar *buffer,int x,int y) { int i, j; int px, py, fby, fbx, fbl, ibxs; int eheight; int extcode; int spid; int cmaps; uchar *fbptr; uchar *lb; uchar *slb; GifFileType *gft; GifByteType *extension; GifRecordType rt; ColorMapObject *cmap; gft = DGifOpenFileName(name); if (gft == NULL) gflush; do { if (DGifGetRecordType(gft,&rt) == GIF_ERROR) grflush; switch(rt) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(gft) == GIF_ERROR) grflush; px = gft->Image.Width; py = gft->Image.Height; lb = (uchar*)malloc(px*3); slb = (uchar*) malloc(px); if (lb != NULL && slb != NULL) { cmap = (gft->Image.ColorMap ? gft->Image.ColorMap : gft->SColorMap); cmaps = cmap->ColorCount; ibxs = ibxs * 3; fbptr = buffer; if (!(gft->Image.Interlace)) { for (i = 0; i < py; i++, fbptr += px*3) { if (DGifGetLine(gft,slb,px) == GIF_ERROR) mgrflush; m_rend_gif_decodecolormap(slb,lb,cmap,cmaps,px); memcpy(fbptr,lb,px*3); } } else { for (j = 0; j < 4; j++) { fbptr = buffer; for (i = 0; i < py; i++, fbptr += px*3) { if(DGifGetLine(gft,slb,px)==GIF_ERROR) mgrflush; m_rend_gif_decodecolormap(slb,lb,cmap,cmaps,px); memcpy(fbptr,lb,px*3); } } } } if (lb) free(lb); if (slb) free(slb); break; case EXTENSION_RECORD_TYPE: if (DGifGetExtension(gft,&extcode,&extension) == GIF_ERROR) grflush; while (extension != NULL) if(DGifGetExtensionNext(gft,&extension) == GIF_ERROR) grflush; break; default: break; } } while (rt != TERMINATE_RECORD_TYPE); DGifCloseFile(gft); return(FH_ERROR_OK); } int fh_gif_getsize(char *name, int *x, int *y) { int i, j; int px, py, fby, fbx, fbl, ibxs; int eheight; int extcode; int spid; int cmaps; uchar *fbptr; uchar *lb; uchar *slb; GifFileType *gft; GifByteType *extension; GifRecordType rt; ColorMapObject *cmap; gft = DGifOpenFileName(name); if (gft == NULL) gflush; do { if (DGifGetRecordType(gft,&rt) == GIF_ERROR) grflush; switch(rt) { case IMAGE_DESC_RECORD_TYPE: if (DGifGetImageDesc(gft) == GIF_ERROR) grflush; px = gft->Image.Width; py = gft->Image.Height; *x = px; *y = py; DGifCloseFile(gft); return(FH_ERROR_OK); break; case EXTENSION_RECORD_TYPE: if (DGifGetExtension(gft,&extcode,&extension) == GIF_ERROR) grflush; while (extension != NULL) if(DGifGetExtensionNext(gft,&extension) == GIF_ERROR) grflush; break; default: break; } } while (rt != TERMINATE_RECORD_TYPE); DGifCloseFile(gft); return(FH_ERROR_FORMAT); } /***********************************************************/ /* GIF FILE IO ROUTINES */ /***********************************************************/ struct formathandler *fh_root = NULL; void add_format(int (*picsize)(char *, int *, int*), int (*picread)(char *, unsigned char *, int, int), int (*id)(char*)) { struct formathandler *fhn; fhn=(struct formathandler*) malloc(sizeof(struct formathandler)); fhn->get_size = picsize; fhn->get_pic = picread; fhn->id_pic = id; fhn->next = fh_root; fh_root = fhn; } extern int fh_gif_getsize(char *, int *, int*); extern int fh_gif_load(char *, uchar *, int, int); extern int fh_gif_id(char *); struct formathandler *fh_getsize(char *name, int *x, int *y) { struct formathandler *fh; for (fh = fh_root; fh != NULL; fh = fh->next) { if (fh->id_pic(name)) if(fh->get_size(name,x,y) == FH_ERROR_OK) return(fh); } return(NULL); } void GIF_FILE_READ(char *FileName, uchar data[], int *color) { int x, y; struct formathandler *fh; add_format(fh_gif_getsize, fh_gif_load, fh_gif_id); if (fh = fh_getsize(FileName, &x, &y)) { if (fh->get_pic(FileName, data, x, y) == FH_ERROR_OK) *color = 1; } } <file_sep>/ImageLoader/bmpIO.h /***********************************************************/ /* */ /* BMP */ /* */ /* Written by <NAME>. */ /***********************************************************/ #include <stdio.h> #include <stdlib.h> #include <errno.h> /***********************************************************/ /* GLOBAL DEFINES */ /***********************************************************/ typedef unsigned char uchar; #define BF_TYPE 0x4D42 #define BI_RGB 0 /* No compression - straight BGR data */ #define BI_RLE8 1 /* 8-bit run-length compression */ #define BI_RLE4 2 /* 4-bit run-length compression */ #define BI_BITFIELDS 3 /* RGB bitmap with RGB masks */ /***********************************************************/ /* GLOBAL CONSTANTS */ /***********************************************************/ /***********************************************************/ /* GLOBAL STRUCTURES */ /***********************************************************/ typedef struct { unsigned short bfType; unsigned int bfSize; unsigned short bfReserved1; unsigned short bfReserved2; unsigned int bfOffBits; } BITMAPFILEHEADER; typedef struct { unsigned int biSize; int biWidth; int biHeight; unsigned short biPlanes; unsigned short biBitCount; unsigned int biCompression; unsigned int biSizeImage; int biXPelsPerMeter; int biYPelsPerMeter; unsigned int biClrUsed; unsigned int biClrImportant; } BITMAPINFOHEADER; typedef struct { unsigned char rgbBlue; unsigned char rgbGreen; unsigned char rgbRed; unsigned char rgbReserved; } RGBQUAD; typedef struct { BITMAPINFOHEADER bmiHeader; RGBQUAD bmiColors[256]; } BITMAPINFO; /***********************************************************/ /* FUNTION PROTOTYPES */ /***********************************************************/ extern uchar *LoadDIBitmap(char filename[], BITMAPINFO **info); extern int SaveDIBitmap(char filename[], BITMAPINFO *info, uchar *bits); <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(NeoQuad) add_executable(NeoQuad main.cpp NeoQuad.cpp Quadrotor.cpp QuadTimer.cpp camera.cpp Timeline.cpp Button.cpp ImageLoader/bmpIO.cpp ImageLoader/pgmIO.cpp) add_subdirectory(glm/) include_directories(glm/) #copy all files form Data/ to build/Data #file(COPY Data/ DESTINATION Data/) add_custom_command(TARGET NeoQuad PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${CMAKE_SOURCE_DIR}/Data $<TARGET_FILE_DIR:NeoQuad>/Data) #install(TARGETS NeoQuad RUNTIME DESTINATION bin) find_package(OpenGL REQUIRED) find_package(GLUT REQUIRED) find_package (Threads REQUIRED) #INCLUDE(FindFreeGLUT.cmake) #set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ${CMAKE_SOURCE_DIR}) #FIND_PACKAGE(FreeGLUT REQUIRED) #ADD_DEFINITIONS(-DFREEGLUT_STATIC=1) #INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include ${FREEGLUT_INCLUDE_DIRS}) #SET(GLUT_LIB ${FREEGLUT_LIBRARIES}) set(CMAKE_CXX_FLAGS "-g -Wall") include_directories( ${OPENGL_INCLUDE_DIRS} ${GLUT_INCLUDE_DIRS} ${NeoQuad_SOURCE_DIR}) link_directories(${NeoQuad_BINARY_DIR} ) target_link_libraries(NeoQuad ${OPENGL_LIBRARIES} ${GLUT_LIBRARY} ${CMAKE_THREAD_LIBS_INIT} ${CMAKE_SOURCE_DIR}/lib/libSOIL.a) <file_sep>/Button.h /****************************************************************** * Name : Button.h * Purpose: Button class for creating buttons in opengl * Have not used any glut functions at all :) * Have implemented a system of callbacks for easy handling * of mouse clicks * * Author: <NAME> * Email : <EMAIL> * * Creation Date: 10/22/2015 *******************************************************************/ #ifndef _BUTTON_H_ #define _BUTTON_H_ #include<vector> //#include<string> using namespace std; class Button { private: int left,top,right,bottom; int state; char label[120]; //string label; //checks if boundary conditions are met inline bool bounds(int x, int y); //draws the button void draw(); //button click event callee void (*buttonClickEvent)(void); public: //Constructor Button(int left,int top,int right,int bottom,char *label /*string label*/, void(* mouseClickCallback)(void)); static vector<Button*> buttons; static Button* checkClick(int buttonState,int x,int y); static void drawButtons(); }; #endif<file_sep>/Button.cpp #include "Button.h" #include<GL/glut.h> #include <string.h> vector<Button*> Button::buttons; Button::Button(int left, int top, int right, int bottom,char*label/*string label*/, void(* mouseClickCallback)(void)) { strcpy(this->label,label); //this->label = label; this->left = left; this->top = top; this->right = right; this->bottom = bottom; state = GLUT_UP; Button:: buttons.push_back(this); this->buttonClickEvent = mouseClickCallback; } bool Button::bounds(int x, int y) { if((left<x && x<right) && (bottom<y && y<top)) return true; return false; } void Button::draw() { glDisable(GL_LIGHTING); glPushMatrix(); glTranslatef(0,0,-.1); glLineWidth(2); if(state == GLUT_UP) glColor3f(.85f,.85f,.85f); else glColor3f(.5f,.5f,.5f); glBegin(GL_LINE_STRIP); glVertex2f(right-1,top-1); glVertex2f(left+1,top-1); glVertex2f(left+1,bottom+1); glEnd(); if(state == GLUT_UP) glColor3f(.5f,.5f,.5f); else glColor3f(.85f,.85f,.85f); glBegin(GL_LINE_STRIP); glVertex2f(left+1,bottom+1); glVertex2f(right-1,bottom+1); glVertex2f(right-1,top-1); glEnd(); glColor3f(.75f,.75f,.75f); glBegin(GL_TRIANGLE_FAN); glVertex2f(left+1,top-1); glVertex2f(left+1,bottom+1); glVertex2f(right-1,bottom+1); glVertex2f(right-1,top-1); glEnd(); glLineWidth(1); glColor3f(1.0f,1.0f,1.0f); glTranslatef(left+5, bottom+5, .1); float scale = (top-bottom-10)/100.0; glScalef( scale,scale,scale); for( char* p =label; *p; p++) { glutStrokeCharacter(GLUT_STROKE_ROMAN, *p); } glPopMatrix(); glEnable(GL_LIGHTING); } Button* Button::checkClick(int buttonState, int x, int y) { for(vector<Button*>::iterator it = buttons.begin(); it!=buttons.end();it++) { if((*it)->bounds(x,y)) { (*it)->state = buttonState; if(buttonState==GLUT_DOWN) (*it)->buttonClickEvent(); return (*it); } } return NULL; } void Button::drawButtons() { for(vector<Button*>::iterator it = buttons.begin(); it!=buttons.end();it++) { (*it)->draw(); } }
fcc4414abe42de8cdbcd1917a0a16174ac771283
[ "C", "CMake", "C++" ]
13
C++
akkasuddin/NeoQuad
bf2e22a1a65790fa0625994b03b31f99be4e8990
25097dbafdcafffbe9ff20dec10600275c81bd17
refs/heads/master
<file_sep># anilogin-microapp test app to get oauth working for anilist routes: * GET / * index.html root page for project * GET /callback * callback for the anilist oauth token to exchange a code for an access_token<file_sep>const express = require('express') const path = require('path') const rp = require('request-promise') const dotenv = require("dotenv"); dotenv.config(); //env varibles const clientId = process.env.ANILIST_CLIENT_ID; const clientSecret = process.env.ANILIST_CLIENT_SECRET; const redirectUri = process.env.ANILIST_REDIRECT_URI; const PORT = process.env.PORT || 5000; const chromeCallback = process.env.chromeCallback; console.log('This is the clientId %s', clientId); express() .use(express.static(path.join(__dirname, "public"))) .get("/", (req, res) => res.render("public/index")) .get("/callback", (req, res) => { const code = req.query.code; function handleError(res, err){ console.log("This was the error %O", err); return res.json({ "error": "There was an error" }); } if(!code){ handleError(res, {"message": "there was no code"}); } const options = { uri: 'https://anilist.co/api/v2/oauth/token', method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', }, json: { 'grant_type': 'authorization_code', 'client_id': clientId, 'client_secret': clientSecret, 'redirect_uri': redirectUri, 'code': code, } }; rp(options) .then((body)=> { console.log(body); if(body.access_token){ return res.redirect(`${chromeCallback}?access_token=${body.access_token}`); } else { handleError(res, body) } }) .catch((err) => handleError(res, err)) }) .listen(PORT, () => console.log(`Listening on ${PORT}`));
da1c263c58eb099a24310d500fe496401aa5ec88
[ "Markdown", "JavaScript" ]
2
Markdown
bote795/anilogin-microapp
9c501a075443c4b6feb87e79bd313025422825cd
c4dc8cfff0666923571736be9f16a8afe2fed436
refs/heads/master
<file_sep>import time import zmq import arrow context = zmq.Context() socket = context.socket(zmq.REP) socket.bind("tcp://*:5555") while True: # Wait for next request from client print("%s: waiting" % str(arrow.get()), flush=True) message = socket.recv() print("%s: Received request: %s" % (str(arrow.get()), message), flush=True) # Do some 'work' time.sleep(1) # Send reply back to client socket.send(b"OK") <file_sep>version: '3' services: model: build: python ports: - "5555" agent: build: scala <file_sep> FROM openjdk RUN apt-get update && \ apt-get -y install libzmq-java COPY build/libs /libs WORKDIR /libs ENTRYPOINT /usr/bin/java -jar app.jar <file_sep> FROM python RUN apt-get update && \ apt-get -y install libzmq3-dev && \ pip install pyzmq arrow COPY main.py /main.py EXPOSE 5555 ENTRYPOINT /usr/local/bin/python /main.py <file_sep>/* * This file was generated by the Gradle 'init' task. * * This is a general purpose Gradle build. * Learn how to create Gradle builds at https://guides.gradle.org/creating-new-gradle-builds/ */ plugins { id 'scala' id 'idea' } idea { module.inheritOutputDirs = true } repositories { mavenCentral() } dependencies { compile group: 'org.zeromq', name: 'jzmq', version: '3.1.0' compile "org.scala-lang:scala-library:2.12.4" compile "org.scala-lang:scala-reflect:2.12.4" } jar { baseName = 'app' version = '1.0' manifest { attributes ( "Main-Class": "nl.bneijt.zerokubed.Application", "Class-Path": configurations.runtime.collect { it.getName() }.join(' ') ) } archiveName = "app.jar" } task copyLibs(type: Copy) { into "$buildDir/libs" from configurations.runtime } assemble.dependsOn "copyLibs" <file_sep>ZeroMQ network boundry between kubenernetes pods ================================================ Simple REQ/RES socket between Python and Scala to allow for a simple sidecar deployment of Python services with a Scala agent to handle the hook-up and monitoring within the full application architecture.
3011f738c196e85c17c08c967461d7161ae4ec77
[ "YAML", "Markdown", "Gradle", "Python", "Dockerfile" ]
6
Python
bneijt/zerokubed
17deff78738588de78adb98776a3749757733bd9
64605f631a8c6a8b7b194383fbf9e5a83895f4a2
refs/heads/master
<file_sep>const data = require('../data'); const User = require('../models/userModels'); const generateToken = require('../utils'); const userController = { async registerUser(req , res) { // console.log(req); const { name, email, password } = req.body; const userName = await User.findOne({name}) const userEmail = await User.findOne({email}) // console.log(userName, userEmail); if(userName || userEmail) { return res.send("User with same name/email Already exists") } else { const newUser = new User({ name, email, password }); newUser.save(); // console.log(newUser); const token = generateToken(newUser) res.send({newUser, token}) } }, async seedUsers(req, res){ console.log("seed users") const createdUsers = await User.insertMany(data.users); res.send(createdUsers); }, async signinUser(req , res) { const email = req.body.email; const user = await User.findOne({email}); if(user) { if(req.body.password == user.password) { const token = generateToken(user); return res.send( {user, token} ); } } console.log("invalid username or password"); return res.status(401).send({ message : "invalid username or password"}); } } module.exports = userController;<file_sep>const express = require('express'); const userRouter = express.Router(); const userController = require('../controllers/userController'); userRouter.get('/seed', userController.seedUsers); userRouter.post('/signin', userController.signinUser); userRouter.post('/register', userController.registerUser); // userRouter.get('/', userController.getUsers); // userRouter.get('/:id', userController.getUser); module.exports = userRouter;<file_sep>const mongoose = require('mongoose') const dotenv = require('dotenv') const userRoutes = require('./routers/userRouter') const productRoutes = require('./routers/productRouter') const express = require('express') const app = express(); const connectDB = require("./config/db") const cors = require('cors') connectDB(); app.use(cors()); app.use(express.json()); // express().use(express.json) dotenv.config(); // app.get('/api/products', (req, res) => { // console.log(data); // res.send(data.products); // }) // app.get('/api/products/:id', (req, res) => { // console.log(req.params.id ); // const product = data.products.find(p => p._id == req.params.id ) // const product = data.products.find(p => p._id == req.params.id) // console.log(product); // res.send(product); // }) app.use('/api/user', userRoutes); app.use('/api/products', productRoutes); // const port = ; app.listen(process.env.PORT, () => { console.log(`Running at port http://localhost:${process.env.PORT}`) })<file_sep>const data = require('../data'); const Product = require('../models/productModels') const productController = { createProduct(req , res) { }, async seedProducts(req, res){ // console.log(data.products); const createdProducts = await Product.insertMany(data.products); res.send(createdProducts); }, async getProducts(req , res) { let allProducts = await Product.find(); return res.status(200).json(allProducts); }, async getProduct(req , res) { const product = await Product.findOne({_id:req.params.id}) console.log(product) res.send(product); } } module.exports = productController;<file_sep>const data = { users: [ { name: 'Basir', email: '<EMAIL>', password: '<PASSWORD>', role: "Admin", }, { name: 'John', email: '<EMAIL>', password: '<PASSWORD>', role: "User", } ], products: [ { // _id: '1', name: 'Nike Slim Shirt', category: 'Shirts', image: '/images/products/belt-1.png', price: 120, countInStock : 5, brand: 'Nike', rating: 1, numReviews: 10, description: 'high quality product', }, { // _id: '2', name: 'Adidas Fit Shirt', category: 'Shirts', image: '/images/products/belt-2.png', price: 100, countInStock :10, brand: 'Adidas', rating: 1.5, numReviews: 10, description: 'high quality product', }, { // _id: '3', name: 'Lacoste Free Shirt', category: 'Shirts', image: '/images/products/belt-3.png', price: 220, countInStock :12, brand: 'Lacoste', rating: 2.0, numReviews: 17, description: 'high quality product', }, { // _id: '4', name: 'Nike Slim Pant', category: 'Pants', image: '/images/products/pant-1.png', price: 78, countInStock :5, brand: 'Nike', rating: 3.5, numReviews: 14, description: 'high quality product', }, { // _id: '5', name: 'Puma Slim Pant', category: 'Pants', image: '/images/products/shirt-1.png', price: 65, countInStock :9, brand: 'Puma', rating: 4.5, numReviews: 10, description: 'high quality product', }, { // _id: '6', name: '<NAME>', category: 'Pants', image: '/images/products/pant-2.png', price: 139, countInStock :22, brand: 'Adidas', rating: 5.0, numReviews: 15, description: 'high quality product', }, ], }; module.exports = data;
ca2624843b66ab866b80b219488333e3a0492a50
[ "JavaScript" ]
5
JavaScript
Aslam-web/Amazona-backend
00fad0b5f318cda8866213c49dceadda33c59057
b2973d3061f2279c2cdc483ed13770f7ef7837dd
refs/heads/main
<repo_name>Oppadayo/movie-app-react<file_sep>/src/components/Movie.js import React from 'react'; import './movie.css' const IMG_PATH = 'https://image.tmdb.org/t/p/w1280/' const setVoteColor = (vote) =>{ if(vote >= 8){ return 'green' } else if(vote >= 5){ return 'orange' }else{ return 'red' } } const Movie = ({poster_path, title, vote_average, overview}) => ( <div className="movie"> <img src={poster_path ? (IMG_PATH + poster_path) : 'https://images.unsplash.com/photo-1581905764498-f1b60bae941a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60'} alt={title}/> <div className="movie-info"> <h3>{title}</h3> <span className={setVoteColor(vote_average)}>{vote_average}</span> </div> <div className="overview"> <h2>Sinopse:</h2> <p>{overview}</p> </div> </div> ) export default Movie<file_sep>/src/App.js import React, { useEffect, useState } from 'react'; import Movie from './components/Movie' const API_URL = 'https://api.themoviedb.org/3/discover/movie?api_key=cec10ecab8ad0684310ec83287fe711a&language=pt-BR&sort_by=popularity.desc&page=1' const SEARCH_API = 'https://api.themoviedb.org/3/search/movie?api_key=cec10ecab8ad0684310ec83287fe711a&language=pt-BR&query=' function App() { const [ movies, setMovies ] = useState([]); const [searchItem, setSearchItem] = useState(''); useEffect(() => { getMovies(API_URL) }, []) const getMovies = (API) => { fetch(API) .then((res) => res.json()) .then((data)=> { setMovies(data.results) }) } const handleOnSubmit = (e) =>{ e.preventDefault() if(searchItem){ getMovies(SEARCH_API + searchItem) setSearchItem('') } } const handleOnChange = (e) =>{ setSearchItem(e.target.value) } return ( <> <header> <form onSubmit={handleOnSubmit}> <input className="search" id="search" type="search" value={searchItem} onChange={handleOnChange} placeholder="Pesquisar"/> </form> </header> <div className="movie-container"> {movies.length > 0 && movies.map((movie) =>( <Movie key={movie.id} {...movie}/> ))} </div>' </> ) } export default App;
ac072f9e7e8766930399e564bc09952ad9f04eee
[ "JavaScript" ]
2
JavaScript
Oppadayo/movie-app-react
0e0255dd432a012ab8967a44fb70999a548fa837
8050aef7f5a8657b1fc2cdf8f5af0875d17b89c5
refs/heads/master
<file_sep>#include <stdlib.h> #include <stdio.h> main() { char op; int opt; while (opt != 1){ system("clear"); printf(" Bem vindo ao ClearCache para linux, execute esse programa como root!!\n"); printf("Escolha uma opção: \n"); printf("[1] Limpar memoria cache.\n"); printf("[0] Sair\n"); printf("Opção: "); op=getchar(); switch(op) { case '1' : system("echo 3 > /proc/sys/vm/drop_caches"); printf("\n\nCache limpa!!\n\n"); break; case '0': system("clear"); printf("Bye!\n\n"); opt = 1; break; default : system("clear"); printf("\nOpção errada!\n\n\n\n"); system("sleep 1"); break; } } }
99537f1bd8f6e0004dd2f0b3061500e9f3ea1121
[ "C" ]
1
C
delete/C
c2b9aa22dfd658d881d19a1ced1d22ef654e9668
013bb14479b57be3178568f2a4d3528bb436a5e0
refs/heads/master
<file_sep>package problems; import java.io.BufferedInputStream; import java.math.BigInteger; import java.util.Scanner; public class Main1002 { public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc = new Scanner(new BufferedInputStream(System.in)); while(sc.hasNext()){ int t = sc.nextInt(); for(int i=0;i<t;i++){ BigInteger a = sc.nextBigInteger(); BigInteger b = sc.nextBigInteger(); if(i>0) System.out.println(); System.out.println("Case "+(i+1)+":"); System.out.println(a+" + "+b+" = "+a.add(b)); } } } } <file_sep>package problems; import java.io.BufferedInputStream; import java.util.Scanner; public class Main1001 { public static void main(String[] args){ @SuppressWarnings("resource") Scanner sc = new Scanner(new BufferedInputStream(System.in)); while(sc.hasNext()){ int a = sc.nextInt(); int b =0; for(int i=1;i<=a;i++){ b+=i; } System.out.println(b); System.out.println(); } } } <file_sep>package niuke; import java.util.ArrayList; import java.util.LinkedList; import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils.Collections; public class Main { public static void main(String[] args) { // int[][] a = { { 1, 2 }, { 2, 3 }, { 3, 4 } }; // // for (int i = 0; i < a.length; i++) { // for (int j = 0; j < a[0].length; j++) { // System.out.print(a[i][j] + " "); // } // System.out.println(); // } int[][] a = { { 1, 2, 8, 9 }, { 2, 4, 9, 12 }, { 4, 7, 10, 13 }, { 6, 8, 11, 15 } }; // System.out.println(Find(3, a)); // System.out.println(new ArrayList<Integer>()); ArrayList<Integer> arrayList = new ArrayList<>(); for(int i=0;i<100;i++){ arrayList.add(i); } } public static boolean Find(int target, int[][] array) { int lenA = array[0].length; int lenB = array.length; int j = lenA - 1; int i = 0; while (j >= 0 && i < lenB) { if (array[i][j] == target) return true; if (array[i][j] > target) j--; else i++; } return false; } } <file_sep>package problems; import java.io.BufferedInputStream; import java.math.BigInteger; import java.util.Scanner; //1000 public class Main1000{ public static void main(String[] args) { @SuppressWarnings("resource") Scanner sc = new Scanner(new BufferedInputStream(System.in)); while(sc.hasNext()){ BigInteger a = sc.nextBigInteger(); BigInteger b = sc.nextBigInteger(); System.out.println(a.add(b)); } } } <file_sep>package problems; import java.io.BufferedInputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Scanner; public class Main1004_2 { public static void main(String[] args) { int n; HashMap<String,Integer> colors = new HashMap<>(); @SuppressWarnings("resource") Scanner sc = new Scanner(new BufferedInputStream(System.in)); while ((n = sc.nextInt()) != 0) { sc.nextLine(); for (int m = 0; m < n; m++) { String color = sc.nextLine(); if(colors.containsKey(color)){ int j = colors.get(color); colors.remove(color); colors.put(color, j+1); }else{ colors.put(color, 1); } } Iterator<String> keys = colors.keySet().iterator(); String key=""; int max=0; while(keys.hasNext()){ String k = keys.next(); int number = colors.get(k); if(max<number){ max = number; key = k; } } System.out.println(key); colors.clear(); } } } <file_sep>package niuke; public class Solution6 { public static int minNumberInRotateArray(int[] array) { if (array.length == 0) return 0; if (array.length == 1) return array[0]; int i = 1; while (i < array.length) { if (array[i] < array[i - 1]) return array[i]; if (array[i] >= array[i - 1]) i++; } return array[0]; } public static void main(String[] args) { System.out.println(minNumberInRotateArray(new int[]{})); } }
d70c9aa8f4cdab74e3dff7a11c0b1ca1c67860f4
[ "Java" ]
6
Java
JimWiliam/ACM
8c3593c5f6154691651c05ae09a55d7a031306c4
0682848fad15e84bb3349c4f667eb69a980465ae
refs/heads/master
<file_sep> // -------------------------------------------------------------------------- // // GULP-MODULE // // -------------------------------------------------------------------------- // var gulp = require('gulp'); var sass = require('gulp-sass'); var autoprefixer = require('gulp-autoprefixer'); var cleancss = require('gulp-clean-css'); // -------------------------------------------------------------------------- // // STYLE // // -------------------------------------------------------------------------- // gulp.task('styles', function() { gulp.src('resources/sass/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer('last 3 versions', '> 1%', 'ie 8')) .pipe(cleancss({compatibility: 'ie8'})) .pipe(gulp.dest('dist/Themeplus/Css/')); }); // -------------------------------------------------------------------------- // // WATCH-TASK // // -------------------------------------------------------------------------- // gulp.task('default',function() { gulp.start('styles'); gulp.watch('resources/sass/**/*', ['styles']); });
6c2d47fbc261425d6dd5bc27fe0109ed68e3f1cc
[ "JavaScript" ]
1
JavaScript
phahok/kanboard-themeplus
d5ac36aaf2eb308bb139206c7e255d565722bb1d
f369674402ffeccadb1ff83e49a8c4246f5084e1
refs/heads/master
<file_sep>FIRST_PORT = 17000 PORTS = [] for P in range(2): PORTS.append(FIRST_PORT + 2*P) print(PORTS[P]) exit(0) <file_sep>import telnetlib from ciscoconfparse import CiscoConfParse ROUTERS = 2 HOST = "192.168.56.101" COMMANDS = ["\r", "enable\r", "terminal length 0\r", "config t\r"] PATH = "C:/Users/hades_000/vmmaestro/workspace/My Topologies/OSPF LAB/Ro" FIRST_PORT = 2001 TELNET = telnetlib.Telnet() CONFIG = CiscoConfParse() for I in range(ROUTERS): TELNET.open(HOST, FIRST_PORT + I) <file_sep>import getpass import sys import telnetlib ROUTERS = 2 HOST = "192.168.56.101" COMMANDS = ["\r", "enable\r", "terminal length 0\r", "show running-config\r"] PATH = "C:/Users/hades_000/vmmaestro/workspace/My Topologies/OSPF LAB/Ro" FIRST_PORT = 2001 TELNET = telnetlib.Telnet() for I in range(ROUTERS): TELNET.open(HOST, FIRST_PORT + I) TELNET.write(COMMANDS[0].encode('ascii')) TELNET.write(COMMANDS[1].encode('ascii')) TELNET.write(COMMANDS[2].encode('ascii')) TELNET.write(COMMANDS[3].encode('ascii')) TELNET.read_until("service password-encryption".encode('ascii'), 5) FILE = open(PATH + str(I + 1) + ".txt", 'w') FILE.write((TELNET.read_until("!\r\nend".encode('ascii'), 5)).decode()) FILE.close() TELNET.close() exit(0)
c610f76fd3ede42d7cfeea9e0e704e216d86ba0d
[ "Python" ]
3
Python
dcapello/Telnet
8ed3e54dad60af57f68a5c3402e31bbdcb0e79ab
e14f3f6d64050f867fb0d5329d5e9b6234ece54c
refs/heads/master
<repo_name>cordis-dev/cf-swift-test<file_sep>/sl-crash.swift /// https://github.com/realm/SwiftLint/issues/2276 switch code { case 200..<300: return "\(code) ✅" default: break <file_sep>/README.md # cf-swift-test
7f5d9567bbe59ef699559dc5557180356f9c2958
[ "Swift", "Markdown" ]
2
Swift
cordis-dev/cf-swift-test
2040169caa8c854da393811ad6c0bda204481c82
5e9d73668cfba606c3ffd83d56074c308eba80b5
refs/heads/master
<repo_name>modularwp/gutenberg-block-toolbar-control-jsx-example<file_sep>/js/block.js const { __ } = wp.i18n; const { registerBlockType, BlockControls, AlignmentToolbar } = wp.blocks; registerBlockType( 'mdlr/toolbar-control-jsx-example', { title: __( 'Toolbar Control Example with JSX' ), icon: 'admin-tools', category: 'common', attributes: { alignment: { type: 'string', }, }, edit( { attributes, className, focus, setAttributes } ) { const { alignment } = attributes; function onChangeAlignment( updatedAlignment ) { setAttributes( { alignment: updatedAlignment } ); } return ( <div className={ className }> { !! focus && ( <BlockControls> <AlignmentToolbar value={ alignment } onChange={ onChangeAlignment } /> </BlockControls> ) } <p style={ {textAlign: alignment } }>Toolbar control block example built with JSX.</p> </div> ); }, save( { attributes, className } ) { const { alignment } = attributes; return ( <div className={ className }> <p style={ {textAlign: alignment } }>Toolbar control block example built with JSX.</p> </div> ); }, } );
ac37c3c54b7b4cfa1061c38e447c12b40f059fe9
[ "JavaScript" ]
1
JavaScript
modularwp/gutenberg-block-toolbar-control-jsx-example
b91e9cff537f9a6507d075dc01690e9b6935e757
c84f6ffd4e92e342b94d74165d96383cb3f9f84f
refs/heads/master
<file_sep>'use strict' const InformesCursosModel = require('./conexion') function crearInforme(informe, next){ InformesCursosModel .query(`INSERT INTO informes_de_cursos SET ?`, informe, (error, resultado, fields) => { next(error) }) } function obtenerInformePorIdCurso(idCurso, next){ InformesCursosModel .query(`SELECT i.idCurso, c.nombre, i.participantes, i.cumplimientoObjetivos, i.participantesAprobados, i.nivelAutoFin, i.institucionesParticipantes, i.nivelVinculacion, i.evaluacionPromedioParticipantes FROM informes_de_cursos i JOIN cursos c ON c.idCurso = i.idCurso WHERE i.idCurso = ?`, idCurso, (error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function obtenerDescripcionInformePorIdCurso(idCurso, next){ InformesCursosModel .query(`SELECT i.idCurso, c.nombre nombreCurso, c.departamento, CONCAT(u.nombre, ' ', u.apellido ) nombreRepresentante, i.nivelAutoFin, i.participantes, i.cumplimientoObjetivos, i.participantesAprobados, i.institucionesParticipantes, i.nivelVinculacion, i.evaluacionPromedioParticipantes FROM informes_de_cursos i JOIN cursos c ON c.idCurso = i.idCurso JOIN cursos_usuarios CU on CU.idCurso = i.idCurso AND cu.tipo = 3 JOIN usuarios u ON u.idUsuario = cu.idUsuario WHERE i.idCurso = ?`, idCurso, (error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function actualizarInforme(informe, next){ InformesCursosModel .query(`UPDATE informes_de_cursos SET ? WHERE idCurso = ?`, [informe, informe.idCurso], (error, resultado, fields) => { next(error) }) } module.exports = { crearInforme, obtenerInformePorIdCurso, obtenerDescripcionInformePorIdCurso, actualizarInforme }<file_sep>'use strict' const express = require("express"), CursoController = require('../controllers/curso'), curso = express.Router() // cursos-unison/curso/inscribirse/:idCurso curso .route("/inscribirse/:idCurso") .get( CursoController.inscribirseGet ) .post( CursoController.inscribirsePost ) // cursos-unison/curso/inscribirse/:idCurso curso .route("/cancelar/:idCurso") .post( CursoController.cancelarPost ) // cursos-unison/curso/asistencia/:idCurso curso .route("/asistencia/:idCurso") .get( CursoController.asistenciaGet ) // cursos-unison/curso/asistencia/:idCurso/:idUsuario curso .route("/asistencia/:idCurso/:idUsuario") .post( CursoController.asistenciaPost ) // cursos-unison/curso/evaluacion-curso/:idCurso curso .route("/evaluacion-curso/:idCurso") .get( CursoController.evaluacionCursoGet ) .post( CursoController.evaluacionCursoPost ) // cursos-unison/curso/evaluacion-curso/:idCurso curso .route("/evaluacion-instructor/:idCurso") .get( CursoController.evaluacionInstructorGet ) .post( CursoController.evaluacionInstructorPost ) // cursos-unison/curso/evaluacion-participantes/:idCurso curso .route("/evaluacion-participantes/:idCurso") .get( CursoController.evaluacionParticipantesGet ) // cursos-unison/curso/evaluacion-participantes/:idCurso/:idUsuario curso .route("/evaluacion-participantes/:idCurso/:idUsuario") .post( CursoController.evaluacionParticipantesPost ) // cursos-unison/curso/enviar-aprobados/:idCurso curso .route("/enviar-aprobados/:idCurso") .post( CursoController.enviarAprobadosPost ) module.exports = curso<file_sep>'use strict' const express = require("express"), InformeController = require('../controllers/informe'), informe = express.Router() // cursos-unison/informe/editar-informe/:idCurso informe .route("/editar-informe/:idCurso") .get( InformeController.editarInformeGet ) .post( InformeController.editarInformePost ) // cursos-unison/informe/enviar-informe/:idCurso informe .route("/enviar-informe/:idCurso") .post( InformeController.enviarInformePost ) // cursos-unison/informe/enviar-descripcion/:idCurso informe .route("/enviar-descripcion/:idCurso") .post( InformeController.enviarDescripcionInformePost ) // cursos-unison/informe/ver-informes/:idCurso informe .route("/ver-informes") .get( InformeController.verInformesGet ) // cursos-unison/informe/aprobar/:idCurso informe .route("/aprobar/:idCurso") .get( InformeController.aprobarGet ) // cursos-unison/informe/no-aprobar/:idCurso informe .route("/no-aprobar/:idCurso") .post( InformeController.noAprobarPost ) module.exports = informe<file_sep>/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE */; /*!40101 SET SQL_MODE='NO_ENGINE_SUBSTITUTION' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES */; /*!40103 SET SQL_NOTES='ON' */; DROP DATABASE IF EXISTS `cursos_unison`; CREATE DATABASE `cursos_unison` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `cursos_unison`; CREATE TABLE `usuarios` ( `idUsuario` int(10) unsigned NOT NULL AUTO_INCREMENT, `nombre` varchar(50) NOT NULL, `apellido` varchar(50) NOT NULL, `correo` varchar(50) NOT NULL, `password` varchar(255) NOT NULL, `expediente` varchar(50) NULL, `codigoVerificacion` varchar(20) NOT NULL, `institucion` varchar(255) NOT NULL, `tipo` int(10) unsigned NOT NULL, `estado` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`idUsuario`), UNIQUE KEY `correo` (`correo`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `cursos` ( `idCurso` int(10) unsigned NOT NULL AUTO_INCREMENT, `nombre` varchar(255) NULL, `division` varchar(50) NOT NULL DEFAULT 'División de Ciencias Exactas y Naturales', `departamento` varchar(50) NULL, `caracter` varchar(80) NULL, `objetivoGeneral` TEXT NULL, `objetivosEspecificos` TEXT NULL, `contenidoSintetico` TEXT NULL, `formaEnsenanza` TEXT NULL, `requisitosDeEvaluacion` TEXT NULL, `bibliografia` TEXT NULL, `perfilAcademico` TEXT NULL, `capacidadAutoFin` TEXT NULL, `utilidad` TEXT NULL, `antecedentesAlumnos` TEXT NULL, `duracion` int(10) unsigned, `cupoMaximo` int(10) unsigned NULL, `cupoMinimo` int(10) unsigned NULL, `numeroDeParticipantes` int(10) unsigned NOT NULL DEFAULT '0', `reqIdioma` varchar(70) NULL, `infraestructuraNecesaria` TEXT NULL, `cargoInstructor` TEXT NULL, `dependencia` varchar(50) NULL, `telefono` varchar(20) NULL, `fechaInicio` date NULL, `fechaFinal` date NULL, `estado` int(10) unsigned NOT NULL DEFAULT '1', PRIMARY KEY (`idCurso`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `informes_de_cursos`( `idCurso` int(10) unsigned NOT NULL, `nivelAutoFin` TEXT NULL, `participantes` int(10) unsigned NULL, `participantesAprobados` int(10) unsigned NULL, `cumplimientoObjetivos` TEXT NULL, `institucionesParticipantes` TEXT NULL, `evaluacionPromedioParticipantes` TEXT NULL, `nivelVinculacion` TEXT NULL, KEY `idCurso` (`idCurso`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `cursos_usuarios` ( `idUsuario` int(10) unsigned NOT NULL, `idCurso` int(10) unsigned NOT NULL, `tipo` int(10) unsigned NOT NULL, KEY `idUsuario` (`idUsuario`), KEY `idCurso` (`idCurso`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `cursos_usuarios_asistencia` ( `idUsuario` int(10) unsigned NOT NULL, `idCurso` int(10) unsigned NOT NULL, `fecha` date NULL, `asistio` tinyint(1) NOT NULL DEFAULT '0', KEY `idUsuario` (`idUsuario`), KEY `idCurso` (`idCurso`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `cursos_usuarios_evaluacion_curso` ( `idCurso` int(10) unsigned NOT NULL, `expectativas` int(3) unsigned NOT NULL, `pertinencia` int(3) unsigned NOT NULL, `topicos` int(3) unsigned NOT NULL, `tiempos` int(3) unsigned NOT NULL, `objetivos` int(3) unsigned NOT NULL, `materiales` int(3) unsigned NOT NULL, `aplicacion` int(3) unsigned NOT NULL, `medios` int(3) unsigned NOT NULL, `informacion` int(3) unsigned NOT NULL, `programa` int(3) unsigned NOT NULL, `sugerencias` TEXT NULL, KEY `idCurso` (`idCurso`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `cursos_usuarios_evaluacion_instructor` ( `idCurso` int(10) unsigned NOT NULL, `dominio` int(3) unsigned NOT NULL, `presentacionDeConceptos` int(3) unsigned NOT NULL, `interaccionYmotivacion` int(3) unsigned NOT NULL, `usoDeRecursosDidacticos` int(3) unsigned NOT NULL, `comunicacionConElGrupo` int(3) unsigned NOT NULL, `tutoria` int(3) unsigned NOT NULL, `laExtensionDeLaInformacion` int(3) unsigned NOT NULL, `estrategias` int(3) unsigned NOT NULL, `desempeno` int(3) unsigned NOT NULL, `sugerencias` TEXT NULL, KEY `idCurso` (`idCurso`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; CREATE TABLE `cursos_usuarios_evaluacion_participantes` ( `idUsuario` int(10) unsigned NOT NULL, `idCurso` int(10) unsigned NOT NULL, `aprobo` tinyint(1) NOT NULL DEFAULT '0', `calificado` tinyint(1) NOT NULL DEFAULT '0', `evaluacion_curso` tinyint(1) NOT NULL DEFAULT '0', `evaluacion_instructor` tinyint(1) NOT NULL DEFAULT '0', KEY `idUsuario` (`idUsuario`), KEY `idCurso` (`idCurso`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; ALTER TABLE `informes_de_cursos` ADD FOREIGN KEY (`idCurso`) REFERENCES `cursos` (`idCurso`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `cursos_usuarios` ADD FOREIGN KEY (`idUsuario`) REFERENCES `usuarios` (`idUsuario`) ON DELETE CASCADE ON UPDATE NO ACTION, ADD FOREIGN KEY (`idCurso`) REFERENCES `cursos` (`idCurso`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `cursos_usuarios_asistencia` ADD FOREIGN KEY (`idUsuario`) REFERENCES `usuarios` (`idUsuario`) ON DELETE CASCADE ON UPDATE NO ACTION, ADD FOREIGN KEY (`idCurso`) REFERENCES `cursos` (`idCurso`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `cursos_usuarios_evaluacion_curso` ADD FOREIGN KEY (`idCurso`) REFERENCES `cursos` (`idCurso`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `cursos_usuarios_evaluacion_instructor` ADD FOREIGN KEY (`idCurso`) REFERENCES `cursos` (`idCurso`) ON DELETE CASCADE ON UPDATE NO ACTION; ALTER TABLE `cursos_usuarios_evaluacion_participantes` ADD FOREIGN KEY (`idUsuario`) REFERENCES `usuarios` (`idUsuario`) ON DELETE CASCADE ON UPDATE NO ACTION, ADD FOREIGN KEY (`idCurso`) REFERENCES `cursos` (`idCurso`) ON DELETE CASCADE ON UPDATE NO ACTION; <file_sep>'use strict' const UsuarioModel = require('../models/usuario'), CursoModel = require('../models/curso'), CursosUsuariosModel = require('../models/cursos_usuarios'), CursosUsuariosEvaluacionParticipantesModel = require('../models/cursos_usuarios_evaluacion_participantes'), InformesCursosModel = require('../models/informes_de_cursos'), EvaluacionCursoModel = require('../models/cursos_usuarios_evaluacion_curso'), EvaluacionInstructorModel = require('../models/cursos_usuarios_evaluacion_instructor'), enviarCorreo = require('./correo') function editarInformeGet(req, res){ let usuario = req.session.user, idCurso = req.params.idCurso if(usuario.tipo == 2){ res.redirect('/solicitud/ver-solicitudes') return; } CursosUsuariosModel.obtenerResponsableYintructorPorIdCurso(idCurso, (error, curso) => { if(error || curso.length < 2 || curso[0].idUsuario != usuario.idUsuario){ // si no es el responsable o hubo algun error res.redirect('/usuario/mis-cursos') }else{ InformesCursosModel.obtenerInformePorIdCurso(idCurso, (error, informe) => { if(error || typeof informe == 'undefined'){ // creo el informe CursosUsuariosEvaluacionParticipantesModel .obtenerAprobadosPoridCurso(idCurso, (error, aprobados) => { if(error){ res.redirect('/usuario/mis-cursos') }else{ // creo el informe let nuevo_informe = { idCurso, participantes: aprobados.numeroDeParticipantes, participantesAprobados: aprobados.num_aprobados } InformesCursosModel .crearInforme(nuevo_informe, (error) => { if(error) console.log(error) res.redirect('/informe/editar-informe/'+idCurso) }) } }) }else{ res.render('./informe/editar_informe', {usuario, informe}) } }) } }) } function editarInformePost(req, res){ let usuario = req.session.user, idCurso = req.params.idCurso, informe = req.body informe.idCurso = idCurso InformesCursosModel.actualizarInforme(informe, (error) => { if(error) console.log(error) res.redirect('/usuario/mis-cursos') }) } function enviarInformePost(req, res){ let usuario = req.session.user, idCurso = req.params.idCurso InformesCursosModel.obtenerInformePorIdCurso(idCurso, (error, informe) => { if(error || typeof informe == 'undefined' || comprobarInforme(informe)){ req.session.enviarInformeError = true; res.redirect('/usuario/mis-cursos') }else{ // cambio el estado del curso let cursoUp = {idCurso, estado:5} CursoModel.actualizarCurso(cursoUp, (error) => { if(error){ req.session.enviarInformeError = true; res.redirect('/usuario/mis-cursos') }else{ req.session.enviarInformeCorrecto = true; res.redirect('/usuario/mis-cursos') } }) } }) } function comprobarInforme(informe){ for(let llave in informe){ let atributo = informe[llave] if(atributo == '' || atributo == null) return true } return false; } function enviarDescripcionInformePost(req, res){ // carta // nombre del representante y el nombre del curso // informe // nombre del curso y informe // evaluaciones // evaluaciones curso, evaluaciones instructor let idCurso = req.params.idCurso try{ // obtengo el informe InformesCursosModel .obtenerDescripcionInformePorIdCurso(idCurso, (error, informe) => { if(error) throw error // obtengo los participantes (nombreU) CursosUsuariosModel.obtenerParticipantesPorIdCurso(idCurso, (error, participantes) => { if(error) throw error // obtengo los que aprobaron (nombre U) CursosUsuariosEvaluacionParticipantesModel .obtenerNombreAprobadosPoridCurso(idCurso, (error, aprobados) => { if(error) throw error // obtengo las evaluaciones del curso EvaluacionCursoModel.obtenerEvaluacionesPorIdCurso(idCurso, (error, evaluacionesCurso) =>{ if(error) throw error // obtengo las evaluaciones del instructor EvaluacionInstructorModel.obtenerEvaluacionesPorIdCurso(idCurso, (error, evaluacionesInstructor) => { if(error) throw error res.json({informe, participantes, aprobados, evaluacionesCurso, evaluacionesInstructor, error: 0}) }) }) }) }) }) }catch(error){ console.log(error) res.json({error: 1}) } } function verInformesGet(req, res){ let usuario = req.session.user if(usuario.tipo < 2){ res.redirect('/usuario/mis-cursos') return; } CursosUsuariosModel.obtenerInformes((error, informes) => { if(error){ informes = [] res.render('./informe/ver_informes', {informes, usuario}) }else{ informes = obtenerInformesOrdenados(informes) res.render('./informe/ver_informes', {informes, usuario}) } }) } function obtenerInformesOrdenados(informes){ let informesOrdenados = [] for(let i=0 ; i<informes.length ; i+=2){ let informe = {} informe.idCurso = informes[i].idCurso informe.nombreC = informes[i].nombreC informe.nombreR = informes[i].nombreU informe.nombreI = informes[i+1].nombreU informesOrdenados.push(informe) } return informesOrdenados } function aprobarGet(req, res){ let usuario = req.session.user, idCurso = req.params.idCurso if(usuario.tipo < 2){ res.redirect('/usuario/mis-cursos') return; } CursosUsuariosModel.obtenerResponsableYintructorPorIdCurso(idCurso, (error, curso) => { if(error || curso.length < 2){ res.redirect('/informe/ver-informes') }else{ // cambio el estado del curso let cursoUp = {idCurso, estado:6} CursoModel.actualizarCurso(cursoUp, (error) => { if(error){ res.redirect('/informe/ver-informes') }else{ // mandar correo al responsable let asunto = 'Se a aprobado el informe del curso!', mensaje = `<p>El H. Consejo Divisional ha aprobado el informe del curso "${curso[0].nombreC}".</p>` enviarCorreo(curso[0].correo, asunto, mensaje) res.redirect('/informe/ver-informes') } }) } }) } function noAprobarPost(req, res){ let usuario = req.session.user, idCurso = req.params.idCurso, correccion = req.body.correccion CursosUsuariosModel.obtenerResponsableYintructorPorIdCurso(idCurso, (error, curso) => { if(error || curso.length == 0){ res.redirect('/informe/ver-informes') }else{ // cambio el estado del curso let cursoUp = {idCurso, estado:5} CursoModel.actualizarCurso(cursoUp, (error) => { if(error){ res.redirect('/informe/ver-informes') }else{ // mandar correo al responsable let asunto = 'No se aprobo el informe del curso...', mensaje = `<p>El H. Consejo Divisional no ha aprobado el informe del curso "${curso[0].nombreC}", por las siguientes razones:</p> <p>${correccion}</p> ` enviarCorreo(curso[0].correo, asunto, mensaje) res.redirect('/informe/ver-informes') } }) } }) } module.exports = { editarInformeGet, editarInformePost, enviarInformePost, enviarDescripcionInformePost, verInformesGet, aprobarGet, noAprobarPost }<file_sep>'use strict' const CursosUsuariosEvaluacionParticipantesModel = require('./conexion') function obtenerSiEvaluo(idCurso, idUsuario, next){ CursosUsuariosEvaluacionParticipantesModel .query(`SELECT evaluacion_curso, evaluacion_instructor FROM cursos_usuarios_evaluacion_participantes WHERE idCurso = ? AND idUsuario = ?`, [idCurso, idUsuario], (error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function obtenerEvaluacion(idCurso, idsUsuario, next){ CursosUsuariosEvaluacionParticipantesModel .query(`SELECT cuep.idUsuario, cuep.idCurso, u.nombre, u.apellido, cuep.aprobo FROM cursos_usuarios_evaluacion_participantes cuep JOIN usuarios u ON cuep.idUsuario = u.idUsuario WHERE cuep.idCurso = ? AND cuep.idUsuario IN (?)`, [idCurso, idsUsuario] ,(error, resultado, fields) => { next(error, resultado) }) } function obtenerCursoCalificado(idCurso, idsUsuario, next){ CursosUsuariosEvaluacionParticipantesModel .query(`SELECT COUNT(cuep.calificado) calificado FROM cursos_usuarios_evaluacion_participantes cuep WHERE cuep.idCurso = ? AND cuep.idUsuario IN (?) AND cuep.calificado = 0`, [idCurso, idsUsuario] ,(error, resultado, fields) => { try{ next(error, resultado[0].calificado) }catch(error){ next(error, null) } }) } function obtenerAprobadosPoridCurso(idCurso, next){ CursosUsuariosEvaluacionParticipantesModel .query(`SELECT c.numeroDeParticipantes, COUNT(cuep.aprobo) num_aprobados FROM cursos_usuarios_evaluacion_participantes cuep JOIN cursos c ON c.idCurso = cuep.idCurso WHERE cuep.idCurso = ? AND cuep.aprobo = 1`, idCurso, (error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function obtenerNombreAprobadosPoridCurso(idCurso, next){ CursosUsuariosEvaluacionParticipantesModel .query(`SELECT CONCAT(u.nombre, ' ', u.apellido) nombreCompleto FROM cursos_usuarios_evaluacion_participantes cuep JOIN usuarios u ON u.idUsuario = cuep.idUsuario WHERE cuep.idCurso = ? AND cuep.aprobo = 1`, idCurso, (error, resultado, fields) => { next(error, resultado) }) } function crearEvaluacion(evaluacion, next){ CursosUsuariosEvaluacionParticipantesModel .query(`INSERT INTO cursos_usuarios_evaluacion_participantes SET ?`, evaluacion, (error, resultado, fields) => { next(error) }) } function actualizarEvaluacion(evaluacion, next){ CursosUsuariosEvaluacionParticipantesModel .query(`UPDATE cursos_usuarios_evaluacion_participantes SET ? WHERE idCurso = ? AND idUsuario = ?`, [evaluacion, evaluacion.idCurso, evaluacion.idUsuario], (error, resultado, fields) => { next(error) }) } module.exports = { obtenerSiEvaluo, obtenerEvaluacion, obtenerCursoCalificado, crearEvaluacion, actualizarEvaluacion, obtenerNombreAprobadosPoridCurso, obtenerAprobadosPoridCurso }<file_sep>'use strict' const express = require("express"), SolicitudController = require('../controllers/solicitud'), solicitud = express.Router() // cursos-unison/solicitud/crear-solicitud solicitud .route("/crear-solicitud") .get( SolicitudController.crearSolicitudGet ) .post( SolicitudController.crearSolicitudPost ) // cursos-unison/solicitud/editar-registro/:idCurso solicitud .route("/editar-registro/:idCurso") .get( SolicitudController.editarRegistroGet ) .post( SolicitudController.editarRegistroPost ) // cursos-unison/solicitud/cancelar-registro/:idCurso solicitud .route("/cancelar-registro/:idCurso") .get( SolicitudController.cancelarRegistroGet ) // cursos-unison/solicitud/enviar-registro/:idCurso solicitud .route("/enviar-registro/:idCurso") .post( SolicitudController.enviarRegistroPost ) solicitud .route("/enviar-descripcion/:idCurso") .post( SolicitudController.enviarDescripcionCursoPost ) // cursos-unison/solicitud/enviar-registro/:idCurso solicitud .route("/ver-solicitudes") .get( SolicitudController.verSolicitudesGet ) // cursos-unison/solicitud/aprobar/:idCurso solicitud .route("/aprobar/:idCurso") .get( SolicitudController.aprobarGet ) // cursos-unison/solicitud/no-aprobar/:idCurso solicitud .route("/no-aprobar/:idCurso") .post( SolicitudController.noAprobarPost ) module.exports = solicitud<file_sep>'use strict' const UsuarioModel = require('./conexion') function obtenerUsuarioPorCorreo(correo, next) { UsuarioModel .query(`SELECT u.idUsuario, u.correo, u.password, u.estado, u.nombre, u.apellido, u.tipo, u.expediente, u.institucion FROM usuarios u WHERE u.correo = ? `, correo ,(error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function comprobarEstadoPorId(idUsuario, next){ UsuarioModel .query(`SELECT u.estado FROM usuarios u WHERE u.idUsuario = ? `, idUsuario ,(error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function obtenerUsuarioPorId(idUsuario, next) { UsuarioModel .query(`SELECT * FROM usuarios u WHERE u.idUsuario = ? `, idUsuario ,(error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function cambiarPasswordPorCorreo(usuario, next){ UsuarioModel .query(`UPDATE usuarios SET ? WHERE correo = ?`, [usuario, usuario.correo], (error, resultado, fields) => { (resultado.affectedRows == 0) ? next(error, -1) : next(error, 1) }) } function crearUsuario(usuario, next) { UsuarioModel .query(`INSERT INTO usuarios SET ?`, usuario, (error, resultado, fields) => { try{ next(error, resultado.insertId) }catch(error){ next(error, null) } }) } function actualizarUsuario(usuario, next) { UsuarioModel .query(`UPDATE usuarios SET ? WHERE idUsuario = ?`, [usuario, usuario.idUsuario], (error, resultado, fields) => { next(error) }) } module.exports = { obtenerUsuarioPorCorreo, comprobarEstadoPorId, obtenerUsuarioPorId, cambiarPasswordPorCorreo, crearUsuario, actualizarUsuario } <file_sep>'use strict' const app = require('./app') // servidor ejecutandose app.listen(app.get('port'), () => { console.log(`Aplicacion corriendo en el puerto ${app.get('port')}`) })<file_sep>'use strict' const express = require("express"), UsuarioController = require('../controllers/usuario'), usuario = express.Router() // cursos-unison/usuario/mi-perfil usuario .route("/mi-perfil") .get( UsuarioController.miPerfilGet ) .post( UsuarioController.miPerfilPost ) // cursos-unison/usuario/mis-cursos usuario .route("/mis-cursos") .get( UsuarioController.misCursosGet ) // cursos-unison/usuario/ver-cursos usuario .route("/ver-cursos") .get( UsuarioController.verCursosGet ) module.exports = usuario<file_sep>var datosFormulario; //lo que se va a enviar var correo,name,last,pass,pass2,ocupacion, institucion; $(function(){ $("input:submit").click(function() { datosFormulario= $('#formNew'); correo = document.getElementById('correo').value; name = document.getElementById('nombre').value; last = document.getElementById('apellido').value; pass = document.getElementById('pass').value; pass2 = document.getElementById('pass2').value; institucion = document.getElementById('seleccion').value; ocupacion = document.getElementById('ocupacion').value; exp = document.getElementById('exp').value; //validan si hay campos vacios if(correo== "" || name=="" || last=="" || pass=="" || pass2==""){ mostrarAviso(2); return false; } //valida si es correo electronico if(!correo.match('[a-z0-9._%+-]+@[a-z0-9.-]+\.+[a-z]{2,3}$')) { mostrarAviso(11); return false; } if(pass!=pass2){ mostrarAviso(10); return false; } //validar lo de si es maestro de la uni sea con el correo de la uni if(institucion=='Universidad de Sonora'){ if(exp=="") { mostrarAviso(14); return false; } if(!exp.match(/^(\d+)$/)) { mostrarAviso(12); return false; } if(ocupacion==1){ if(!correo.match('[a-z0-9._%+-]+@(mat|fisica|geologia)+\.uson\.mx$')) { mostrarAviso(13); return false; } } } obtenerMensaje(); return false; }); }); function mostrarAviso(error){ switch(error) { case 1: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡Usuario repetido!</div>"); break; case 2: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡Faltan datos por llenar!</div>"); break; case 10: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡Las contraseñas deben coincidir!</div>"); break; case 11: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡Ingrese el correo electronico valido!</div>"); break; case 12: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡El expediente es numerico!</div>"); break; case 13: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡Se requiere correo institucional si se es Profesor de la UNISON!</div>"); break; case 14: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡Se requiere expediente si se pertenece a la UNISON!</div>"); break; } } function obtenerMensaje() { $.ajax({ url: '/cuenta/registrar', type: 'POST', data: datosFormulario.serialize(), success : function(data) { var arreglo=Object.values(data); if(arreglo[1]==3){ $('#registroModal').modal('show') } mostrarAviso(arreglo[1]); } }); }<file_sep>'use strict' const express = require("express"), CuentaController = require('../controllers/cuenta'), cuenta = express.Router() // cursos-unison/cuenta/login cuenta .route("/login") .get( CuentaController.loginGet ) .post( CuentaController.loginPost ) // cursos-unison/cuenta/olvidar-contraseña cuenta .route("/olvidar-contrasena") .get( CuentaController.olvidarContrasenaGet ) .post( CuentaController.olvidarContrasenaPost ) // cursos-unison/cuenta/registro cuenta .route("/registrar") .get( CuentaController.registrarGet ) .post( CuentaController.registrarPost ) // cursos-unison/cuenta/verificar-codigo/:idUsuario cuenta .route("/verificar-correo/:idUsuario") .get( CuentaController.verificarCorreoGet ) .post( CuentaController.verificarCorreoPost ) // cursos-unison/cuenta/logout cuenta.get('/logout', CuentaController.logout ) module.exports = cuenta<file_sep>'use strict' const mysql = require('mysql'), dbOptions = require('./config'), myConnection = mysql.createConnection(dbOptions) myConnection.connect( err => { return (err) ? console.log('Error al conectarse a mysql: '+err.stack) : console.log('Conexion establecida con mysql') }) module.exports = myConnection<file_sep>document.write("<"+"script type='text/javascript' src='../../public/js/documentos/imagen.js'><"+"/script>") $(function(){ $('.pdf').click(function(){ var clases = $(this).attr("class"); var listaDeClases = clases.split(' '); var idCurso = listaDeClases[3] obtenerMensaje(idCurso) }); $('.pdf2').click(function(){ var clases = $(this).attr("class"); var listaDeClases = clases.split(' '); var idCurso = listaDeClases[3] obtenerMensaje2(idCurso) }); $('.pdf3').click(function(){ var clases = $(this).attr("class"); var listaDeClases = clases.split(' '); var idCurso = listaDeClases[3] obtenerMensaje3(idCurso) }); }); function obtenerMensaje(idCurso) { $.ajax({ url: '/solicitud/enviar-descripcion/'+idCurso, type: 'POST', success : function(data) { var curso = data.curso var representante = data.representante generarRegistro(curso, representante.correo) generarSolicitudCurso(representante.nombreU, curso.nombre, curso.departamento) } }); } function obtenerMensaje2(idCurso) { $.ajax({ url: '/informe/enviar-descripcion/'+idCurso, type: 'POST', success : function(data) { if(data.error != 1){ var informe = data.informe var evaluacionesCurso = data.evaluacionesCurso var evaluacionesInstructor = data.evaluacionesInstructor var participantes = data.participantes // nombreU var aprobados = data.aprobados // nombreCompleto generarEvaluacionInstructor(informe.nombreCurso, evaluacionesInstructor) generarEvaluacionCurso(informe.nombreCurso, evaluacionesCurso) generarInforme(informe,participantes, aprobados) generarSolicitudInforme(informe.nombreRepresentante, informe.nombreCurso,informe.departamento) } } }); } function obtenerMensaje3(idCurso) { $.ajax({ url: '/curso/enviar-aprobados/'+idCurso, type: 'POST', success : function(data) { if(data.error != 1){ var curso = data.curso var aprobados = data.aprobados // curso { nombre, duracion, fechaInicial, fechaFinal } // aprobados { [{nombreCompleto},{nombreCompleto}, .....]} generarConstancia(curso, aprobados) } } }); } //la funcion que genera la carta para solicitud de evaluacion del curso esos serian de inicio los parametros que ocupa function generarSolicitudCurso(nombreRepresentante,nombreCurso,departamento) { var hoy = new Date(); var dd = hoy.getDate(); var mm = hoy.getMonth()+1; //hoy es 0! var yyyy = hoy.getFullYear(); if(dd<10) dd='0'+dd; switch(mm) { case 1: mm='Enero'; break; case 2: mm='Febrero'; break; case 3: mm='Marzo'; break; case 4: mm='Abril'; break; case 5: mm='Mayo'; break; case 6: mm='Junio'; break; case 7: mm='Julio'; break; case 8: mm='Agosto'; break; case 9: mm='Septiembre'; break; case 10: mm='Octubre'; break; case 11: mm='Noviembre'; break; case 12: mm='Diciembre'; break; } var docDefinition = { content: [ { text: 'Hermosillo, Son. '+dd+' de '+mm+' del '+yyyy+'\n\n\n\n\n', style: 'derecha' }, { text: 'Dra. Rosa <NAME>', style: 'resaltar' }, 'Directora de la División de Ciencias Exactas y Naturales', 'P r e s e n t e\n\n\n\n', 'Solicito, a través de su conducto, que el proyecto de curso intitulado:', { text: nombreCurso, style: [ 'resaltar'],margin: [ 10, 5, 5, 5 ] }, { text: 'sea presentado ante el H. Consejo Divisional que Usted preside para su valoración, y si es el caso, para su aprobación.\n\n\n', style: 'justificado' }, 'Agradezco su atención y estoy a sus órdenes para cualquier aclaración al respecto.\n\n\n\n\n\n', { text: nombreRepresentante, style: 'resaltar' }, 'MTC del '+departamento ], styles: { justificado:{ alignment: 'justify' }, derecha: { italic: true, alignment: 'right' }, resaltar: { bold: true }, centrar: { alignment: 'center' } }, pageMargins: [ 80,80,80,60 ], pageSize: 'LETTER', }; pdfMake.createPdf(docDefinition).open(); //pdfMake.createPdf(docDefinition).download('Constancia.pdf'); } function generarRegistro(curso, correo) { //obtener en formato bien la fecha inicial y la fecha final del curso var fechaI=curso.fechaInicio; var fechaF=curso.fechaFinal; var elem = fechaI.split('-'); anoI = elem[0]; mesI = obtenerMes(elem[1]); aux=elem[2].split('T'); diaI = aux[0]; var elem = fechaF.split('-'); anoF = elem[0]; mesF = obtenerMes(elem[1]); console.log(mesF); aux=elem[2].split('T'); diaF = aux[0]; //Aqui ya tengo las fechas var docDefinition = { content: [ { style: 'tableExample', color: '#444', table: { widths: [75,'*'], //headerRows: 1, // keepWithHeaderRows: 1, body: [ [{text: 'Registro de curso',style:['titulo'], colSpan: 2, alignment: 'center',color: 'white'}, {}], [{text: 'Nombre del curso:',style: [ 'campo']}, {text: curso.nombre,style:['texto']}], [{text: 'División:',style: [ 'campo']}, {text: curso.division,style:['texto']}], [{text: 'Departamento:',style: [ 'campo']}, {text: curso.departamento,style:['texto']}], [{text: 'Carácter:',style: [ 'campo']}, {text: curso.caracter,style:['texto']}], [{text: 'Objetivo General:',style: [ 'campo']}, {text: curso.objetivoGeneral,style:['texto']}], [{text: 'Objetivos Específicos:',style: [ 'campo']}, {text: curso.objetivosEspecificos,style:['texto']}], [{text: 'Contenido sintético:',style: [ 'campo']}, {text: curso.contenidoSintetico,style:['texto']}], [{text: 'Forma de conducción del proceso enseñanza-aprendizaje:',style: [ 'campo']}, {text: curso.formaEnsenanza,style:['texto']}], [{text: 'Requisitos de evaluación:',style: [ 'campo']}, {text: curso.requisitosDeEvaluacion,style:['texto']}], [{text: 'Bibliografía:',style: [ 'campo']}, {text: curso.bibliografia,style:['texto']}], [{text: 'Perfil académico deseable del responsable de la materia:',style: [ 'campo']}, {text: curso.perfilAcademico,style:['texto']}], [{text: 'Capacidad de autofinanciamiento:',style: [ 'campo']}, {text: curso.capacidadAutoFin,style:['texto']}], [{text: 'Utilidad y oportunidad en funcion del programa:',style: [ 'campo']}, {text: curso.utilidad,style:['texto']}], [{text: 'Experiencia, calidad profesional y academica del instructor:',style: [ 'campo']}, {text: 'Se adjunta',style:['texto']}], [{text: 'Antecedentes o habilidades necesarias de los alumnos:',style: [ 'campo']}, {text: curso.antecedentesAlumnos,style:['texto']}], [{text: 'Duración del programa:',style: [ 'campo']}, {text: curso.duracion,style:['texto']}], [{text: 'Cupo mínimo y máximo:',style: [ 'campo']}, {text: 'de '+curso.cupoMinimo+' a '+curso.cupoMaximo+' participantes',style:['texto']}], [{text: 'Requisitos de idioma:',style: [ 'campo']}, {text: curso.reqIdioma,style:['texto']}], [{text: 'Fecha de inicio y terminación:',style: [ 'campo']}, {text: 'Iniciará el '+diaI+' de '+mesI+ ' del '+anoI+' y terminará el '+diaF+' de '+mesF+ ' del '+anoF,style:['texto']}], [{text: 'Infraestructura necesaria para ofrecer el curso:',style: [ 'campo']}, {text: curso.infraestructuraNecesaria,style:['texto']}], [{text: 'Cargo del instructor:',style: [ 'campo']}, {text: curso.cargoInstructor,style:['texto']}], [{text: 'Dependecia:',style: [ 'campo']}, {text: curso.dependencia,style:['texto']}], [{text: 'Teléfono/Fax:',style: [ 'campo']}, {text: curso.telefono,style:['texto']}], [{text: 'Correo electronico:',style: [ 'campo']}, {text: correo,style:['texto']}], ] }, layout: { fillColor: function (i, node) { //pinta el titulo de azul mas oscuro if(i==0)return '#2E64FE'; //auqi pinta cebra las filas return (i % 2 === 0) ? null : '#CED8F6'; } } } ], styles: { titulo: { fontSize: 16, bold: true, margin: [0, 5, 0, 5] }, campo: { alignment: 'right', bold: true }, texto: { margin: [0, 8, 0, 8] } }, defaultStyle: { fontSize: 10, alignment: 'justify' }, pageMargins: [ 80,80,80,60 ], pageSize: 'LETTER', }; pdfMake.createPdf(docDefinition).open(); //pdfMake.createPdf(docDefinition).download('Constancia.pdf'); } //funcion para obtener en letra el mes obtenido function obtenerMes(mes){ switch(mes) { case '01': mes='Enero'; break; case '02': mes='Febrero'; break; case '03': mes='Marzo'; break; case '04': mes='Abril'; break; case '05': mes='Mayo'; break; case '06': mes='Junio'; break; case '07': mes='Julio'; break; case '08': mes='Agosto'; break; case '09': mes='Septiembre'; break; case '10': mes='Octubre'; break; case '11': mes='Noviembre'; break; case '12': mes='Diciembre'; break; } return mes; } //la funcion que genera la carta para solicitud de evaluacion del informe del curso esos serian de inicio los parametros que ocupa function generarSolicitudInforme(nombreRepresentante,nombreCurso,departamento) { var hoy = new Date(); var dd = hoy.getDate(); var mm = hoy.getMonth()+1; //hoy es 0! var yyyy = hoy.getFullYear(); if(dd<10) dd='0'+dd; switch(mm) { case 1: mm='Enero'; break; case 2: mm='Febrero'; break; case 3: mm='Marzo'; break; case 4: mm='Abril'; break; case 5: mm='Mayo'; break; case 6: mm='Junio'; break; case 7: mm='Julio'; break; case 8: mm='Agosto'; break; case 9: mm='Septiembre'; break; case 10: mm='Octubre'; break; case 11: mm='Noviembre'; break; case 12: mm='Diciembre'; break; } var docDefinition = { content: [ { text: 'Hermosillo, Son. '+dd+' de '+mm+' del '+yyyy+'\n\n\n\n\n', style: 'derecha' }, { text: 'Dra. Rosa <NAME>', style: 'resaltar' }, 'Directora de la División de Ciencias Exactas y Naturales', 'P r e s e n t e\n\n\n\n', 'Solicito, a través de su conducto, que el informe del curso intitulado:', { text: nombreCurso, style: [ 'resaltar'],margin: [ 10, 5, 5, 5 ] }, { text: 'sea presentado ante el H. Consejo Divisional que Usted preside para su valoración, y si es el caso, para su aprobación.\n\n\n', style: 'justificado' }, 'Agradezco su atención y estoy a sus órdenes para cualquier aclaración al respecto.\n\n\n\n\n\n', { text: nombreRepresentante, style: 'resaltar' }, 'MTC del '+departamento ], styles: { justificado:{ alignment: 'justify' }, derecha: { italic: true, alignment: 'right' }, resaltar: { bold: true }, centrar: { alignment: 'center' } }, pageMargins: [ 80,80,80,60 ], pageSize: 'LETTER', }; pdfMake.createPdf(docDefinition).open(); } function generarInforme(informe,participantes,aprobados) { //obtener participantes para la lista var ulParticipantes=[]; for (var i=0; i < participantes.length; i++) { //GENERAR UNA PAGINA ulParticipantes.push(''+participantes[i].nombreU); } //obtener aprobados para la lista var ulAprobados=[]; for (var i=0; i < aprobados.length; i++) { //GENERAR UNA PAGINA ulAprobados.push(''+aprobados[i].nombreCompleto); } var docDefinition = { content: [ { style: 'tableExample', color: '#444', table: { widths: [150,'*'], //headerRows: 1, // keepWithHeaderRows: 1, body: [ [{text: 'Informe de curso',style:['titulo'], colSpan: 2, alignment: 'center',color: 'white'}, {}], [{text: 'Nombre del curso:',style: [ 'campo']}, {text: informe.nombreCurso,style:['texto']}], [{text: 'I. Nivel de autofinanciamiento',style: [ 'campo']}, {text: informe.nivelAutoFin,style:['texto']}], [{text: 'II. Número de participantes',style: [ 'campo']}, { stack: [ {text: informe.participantes,style:['texto']}, { ul: ulParticipantes, style: 'margenLista' } ] }], [{text: 'III. Número de asistentes que cubrieron los requisitos de egreso',style: [ 'campo']}, { stack: [ {text: informe.participantesAprobados,style:['texto']}, { ul: ulAprobados, style: 'margenLista' } ] }], [{text: 'IV. Cumplimineto de los objetivos del programa',style: [ 'campo']}, {text: informe.cumplimientoObjetivos,style:['texto']}], [{text: 'V. Número y tipo de instituciones participantes',style: [ 'campo']}, {text: informe.institucionesParticipantes,style:['texto']}], [{text: 'VI. Evaluación del desempeño de los instructores por los participantes y el responsable',style: [ 'campo']}, {text: 'Se adjunta',style:['texto']}], [{text: 'VII. Evaluación del desempeño promedio de los participantes por los instructores y el responsable',style: [ 'campo']}, {text: informe.evaluacionPromedioParticipantes,style:['texto']}], [{text: 'VIII. Evaluación del programa por los participantes',style: [ 'campo']}, {text: 'Se adjunta',style:['texto']}], [{text: 'IX. Autoevaluación de los participantes en relación al cumplimiento de los objetivos propuestos',style: [ 'campo']}, {text: 'Se adjunta',style:['texto']}], [{text: 'X. Nivel de vinculación del programa con las necesidades del mercado laboral o de formación profesional',style: [ 'campo']}, {text: informe.nivelVinculacion,style:['texto']}], ] }, layout: { fillColor: function (i, node) { //pinta el titulo de azul mas oscuro if(i==0)return '#2E64FE'; //auqi pinta cebra las filas return (i % 2 === 0) ? null : '#CED8F6'; } } } ], styles: { titulo: { fontSize: 16, bold: true, margin: [0, 5, 0, 5] }, campo: { alignment: 'right', bold: true }, texto: { margin: [0, 8, 0, 8] }, margenLista: { margin: [0, 0, 0, 8] } }, defaultStyle: { fontSize: 10, alignment: 'justify' }, pageMargins: [ 80,80,80,60 ], pageSize: 'LETTER', }; pdfMake.createPdf(docDefinition).open(); } function generarEvaluacionCurso(nombreCurso, evaluacion){ //var nombreCurso='Elaboración de revisiones sistemáticas de literatura en el área de calidad del software'; //var sugerencias='el final que pedo'; var contenido=[]; for (var i=0; i < evaluacion.length; i++) { //GENERAR UNA PAGINA contenido.push({ text: '*EVALUACIÓN Y AUTOEVALUACIÓN de los participantes.', style: 'titulo'}); contenido.push({text:'CURSO/TALLER/ NOMBRE: '+nombreCurso+'\n\n',fontSize: 13}); contenido.push({ style: 'tableExample', color: '#444', table: { widths: ['*',100], //headerRows: 1, // keepWithHeaderRows: 1, body: [ //[{text: 'Registro de curso',style:['titulo'], colSpan: 2, alignment: 'center',color: 'white'}, {}], [{text: 'El curso',bold: true}, {text:'Calificación',alignment: 'center'}], [{text: '1. De acuerdo a sus expectativas'}, getCalif(evaluacion[i].expectativas)], [{text: '2. La pertinencia de los contenidos fue'}, getCalif(evaluacion[i].pertinencia)], [{text: '3. Los topicos tratados'}, getCalif(evaluacion[i].topicos)], [{text: '4. Los tiempos de presentación'}, getCalif(evaluacion[i].tiempos)], [{text: '5. El logro de los objetivos planteados fue'}, getCalif(evaluacion[i].objetivos)], [{text: '6. Los materiales de apoyo fueron'}, getCalif(evaluacion[i].materiales)], [{text: '7. La aplicación de los conocimientos adquiridos es'}, getCalif(evaluacion[i].aplicacion)], [{text: '8. Los medios tecnológicos usados fueron'}, getCalif(evaluacion[i].medios)], [{text: '9. La cantidad de información fue'}, getCalif(evaluacion[i].informacion)], [{text: '10. En general el programa fue'}, getCalif(evaluacion[i].programa)], [{text: 'Sugerencias para mejorar:\n'+evaluacion[i].sugerencias, colSpan: 2}, {}], ] } }); if(i<evaluacion.length-1)contenido.push({ text: '', pageBreak:'after'}); //HASTA AQUi GENERE UNA PAGINA } var docDefinition = { content: contenido, styles: { titulo: { fontSize: 16, bold: true, margin: [0, 5, 0, 5] } }, resaltar: { bold: true }, defaultStyle: { fontSize: 14, alignment: 'left' }, pageMargins: [ 80,80,80,60 ], pageSize: 'LETTER', }; pdfMake.createPdf(docDefinition).open(); } function generarEvaluacionInstructor(nombreCurso, evaluacion) { //var nombreCurso='Elaboración de revisiones sistemáticas de literatura en el área de calidad del software'; //var sugerencias='el final que pedo'; var contenido=[]; for (var i = 0; i < evaluacion.length; i++) { //GENERAR UNA PAGINA contenido.push({ text: '*EVALUACIÓN Y AUTOEVALUACIÓN de los participantes.', style: 'titulo'}); contenido.push({text:'CURSO/TALLER/ NOMBRE: '+nombreCurso+'\n\n',fontSize: 13}); contenido.push({ style: 'tableExample', color: '#444', table: { widths: ['*',100], //headerRows: 1, // keepWithHeaderRows: 1, body: [ //[{text: 'Registro de curso',style:['titulo'], colSpan: 2, alignment: 'center',color: 'white'}, {}], [{text: 'El instructor',bold: true}, {text:'Calificación',alignment: 'center'}], [{text: '1. Dominio del tema'}, getCalif(evaluacion[i].dominio)], [{text: '2. Presentación de conceptos'}, getCalif(evaluacion[i].presentacionDeConceptos)], [{text: '3. Interacción y motivación'}, getCalif(evaluacion[i].interaccionYmotivacion)], [{text: '4. Uso de recursos didácticos y tecnológicos'}, getCalif(evaluacion[i].usoDeRecursosDidacticos)], [{text: '5. Comunicación con el grupo'}, getCalif(evaluacion[i].comunicacionConElGrupo)], [{text: '6. Tutoria'}, getCalif(evaluacion[i].tutoria)], [{text: '7. La extensión de la información (otras fuentes: libros,www,revistas,etc.)'}, getCalif(evaluacion[i].laExtensionDeLaInformacion)], [{text: '8. Estrategias para facilitar el aprendizaje'}, getCalif(evaluacion[i].estrategias)], [{text: '9. En general el desempeño del instructor fue'}, getCalif(evaluacion[i].desempeno)], [{text: 'Sugerencias para mejorar:\n'+evaluacion[i].sugerencias, colSpan: 2}, {}], ] } }); if(i<evaluacion.length-1)contenido.push({ text: '', pageBreak:'after'}); //HASTA AQUi GENERE UNA PAGINA } var docDefinition = { content: contenido, styles: { titulo: { fontSize: 16, bold: true, margin: [0, 5, 0, 5] } }, resaltar: { bold: true }, defaultStyle: { fontSize: 14, alignment: 'left' }, pageMargins: [ 80,80,80,60 ], pageSize: 'LETTER', }; pdfMake.createPdf(docDefinition).open(); //pdfMake.createPdf(docDefinition).download('Constancia.pdf'); } function getCalif(calificacion){ switch(calificacion) { case 0: calificacion='Malo'; break; case 1: calificacion='Regular'; break; case 2: calificacion='Bueno'; break; case 3: calificacion='Excelente'; break; } return calificacion; } //constancias function generarConstancia(curso, aprobados) { //obtener en formato bien la fecha inicial y la fecha final del curso var fechaI=curso.fechaInicio; var fechaF=curso.fechaFinal; var elem = fechaI.split('-'); anoI = elem[0]; mesI = obtenerMes(elem[1]); aux=elem[2].split('T'); diaI = aux[0]; var elem = fechaF.split('-'); anoF = elem[0]; mesF = obtenerMes(elem[1]); console.log(mesF); aux=elem[2].split('T'); diaF = aux[0]; //Aqui ya tengo las fechas var hoy = new Date(); var dd = hoy.getDate(); var mm = hoy.getMonth()+1; //hoy es 0! var yyyy = hoy.getFullYear(); if(dd<10) dd='0'+dd; switch(mm) { case 1: mm='Enero'; break; case 2: mm='Febrero'; break; case 3: mm='Marzo'; break; case 4: mm='Abril'; break; case 5: mm='Mayo'; break; case 6: mm='Junio'; break; case 7: mm='Julio'; break; case 8: mm='Agosto'; break; case 9: mm='Septiembre'; break; case 10: mm='Octubre'; break; case 11: mm='Noviembre'; break; case 12: mm='Diciembre'; break; } //var url; var url=regresarImagen(); var jefeDepartamento=obtenerJefe(curso.departamento); var contenido=[]; for (i = 0; i < aprobados.length; i++) { //GENERAR UNA PAGINA contenido.push({ text: 'Universidad de Sonora',margin: [ 80,0,0,0 ],bold: true,fontSize: 28}); contenido.push({ text: 'División de Ciencias Exactas y Naturales',margin: [ 80,0,0,0 ],fontSize: 20 }); contenido.push({ text: curso.departamento+'\n\n\n',margin: [ 80,0,0,0 ],fontSize: 16 }); contenido.push({ text: 'Otorga la presente\n\n',style:'centrar',fontSize: 12 }); contenido.push({ text: 'CONSTANCIA\n\n',style:'centrar',fontSize: 16 }); contenido.push({ text: 'a\n\n',style:'centrar',fontSize: 12 }); contenido.push({ text: ''+aprobados[i].nombreCompleto+'\n\n\n',style:'centrar',fontSize: 14,bold:true }); contenido.push({ text: 'por su asistencia y acreditación del curso intitulado '+curso.nombre+'. El curso, con una duración de '+curso.duracion+' horas, se impartió del '+diaI+' de '+mesI+ ' del '+anoI+' al '+diaF+' de '+mesF+ ' del '+anoF+'.\n\n\n\n'}); contenido.push({ text: '<NAME> '+dd+' de '+mm+' del '+yyyy+'\n\n\n\n\n\n', style: 'centrar' }); contenido.push({ alignment: 'center', columns: [ { decoration: 'overline', text: ' '+jefeDepartamento+' ' }, { decoration: 'overline', text: ' Dra. <NAME> ' } ] }); contenido.push({ alignment: 'center', columns: [ { text: 'Jefe del '+curso.departamento }, { text: 'Directora de la División de Ciencias Exactas y Naturales' } ] }); if(i<aprobados.length-1)contenido.push({ text: '', pageBreak:'after'}); //HASTA AQUi GENERE UNA PAGINA } var docDefinition = { header: { margin: [ 40,70,10,70 ], columns: [ { // usually you would use a dataUri instead of the name for client-side printing // sampleImage.jpg however works inside playground so you can play with it image: url, width: 100, height: 100 }, { } ] }, content: contenido, styles: { centrar: { alignment: 'center' } }, defaultStyle: { fontSize: 10, alignment: 'justify' }, pageMargins: [ 80,80,80,60 ], pageSize: 'LETTER', }; pdfMake.createPdf(docDefinition).open(); //pdfMake.createPdf(docDefinition).download('Constancia.pdf'); } function obtenerJefe(departamento){ console.log(departamento); switch(departamento) { case 'Departamento de Matemáticas': departamento='Dr. <NAME>'; break; case 'Departamento de Física': departamento='Dr. <NAME>'; break; case 'Departamento de Geología': departamento='Dr. Inocente Guadal<NAME>ado'; break; } return departamento; }<file_sep>'use strict' const CursosUsuariosModel = require('./conexion') function obtenerCursosUsuariosPorIdUsuario(id, next) { CursosUsuariosModel .query(`SELECT cu.idCurso, cu.tipo FROM cursos_usuarios cu WHERE cu.idUsuario = ? ORDER BY cu.tipo DESC`, id ,(error, resultado, fields) => { next(error, resultado) }) } function siCurso(idUsuario, idCurso, next){ CursosUsuariosModel .query(`SELECT * FROM cursos_usuarios cu WHERE cu.idUsuario = ? AND cu.idCurso = ?`, [idUsuario, idCurso] ,(error, resultado, fields) => { next(error, resultado.length) }) } function obtenerParticipantesPorIdCurso(idCurso, next){ CursosUsuariosModel .query(`SELECT u.idUsuario, CONCAT(u.nombre, ' ', u.apellido) nombreU, u.correo, c.nombre nombreC, c.cupoMinimo FROM cursos_usuarios cu JOIN usuarios u ON u.idUsuario = cu.idUsuario JOIN cursos c ON c.idCurso = cu.idCurso WHERE cu.idCurso = ? AND cu.tipo = 1`, idCurso, (error, resultado, fields) => { next(error, resultado) }) } function obtenerResponsableYintructorPorIdCurso(idCurso, next){ CursosUsuariosModel .query(`SELECT u.idUsuario, u.correo, c.nombre nombreC, cu.tipo FROM cursos_usuarios cu JOIN usuarios u ON u.idUsuario = cu.idUsuario JOIN cursos c ON c.idCurso = cu.idCurso WHERE cu.idCurso = ? AND (cu.tipo = 2 OR cu.tipo = 3) ORDER BY cu.tipo DESC`, idCurso, (error, resultado, fields) => { next(error, resultado) }) } function obtenerCursosUsuariosPorIdCurso(idsCurso, next) { CursosUsuariosModel .query(`SELECT cu.idCurso, u.correo, c.nombre nombreC, concat(u.nombre, ' ', u.apellido) nombreU, c.estado, cu.tipo, c.fechaInicio, c.fechaFinal FROM cursos_usuarios cu JOIN usuarios u ON cu.idUsuario = u.idUsuario JOIN cursos c ON cu.idCurso = c.idCurso WHERE ( cu.tipo = 3 OR cu.tipo = 2 ) AND cu.idCurso IN (?)`, [idsCurso] ,(error, resultado, fields) => { next(error, resultado) }) } function obtenerDescripcionCursoPorId(idCurso, next) { CursosUsuariosModel .query(`SELECT c.idCurso, c.nombre, concat(u.nombre, ' ', u.apellido) nombreI, c.departamento, c.contenidoSintetico, c.requisitosDeEvaluacion, c.antecedentesAlumnos, c.cupoMaximo, c.numeroDeParticipantes, c.fechaInicio, c.fechaFinal, c.duracion FROM cursos_usuarios cu JOIN cursos c ON c.idCurso = cu.idCurso JOIN usuarios u ON u.idUsuario = cu.idUsuario WHERE cu.idCurso = ? AND cu.tipo = 2`, idCurso ,(error, resultado, fields) => { try{ next(error, resultado[0]) }catch(error){ next(error, null) } }) } function obtenerTipoPorIdCursoYidUsuario(idCurso, idUsuario, next){ CursosUsuariosModel .query(`SELECT cu.tipo FROM cursos_usuarios cu WHERE cu.idUsuario = ? AND cu.idCurso = ? ORDER BY cu.tipo DESC`, [idUsuario, idCurso] ,(error, resultado, fields) => { try{ next(error, resultado[0].tipo) }catch(error){ next(error, null) } }) } function obtenerSolicitudes(next) { CursosUsuariosModel .query(`SELECT cu.idCurso, c.nombre nombreC, concat(u.nombre, ' ', u.apellido) nombreU, cu.tipo FROM cursos_usuarios cu JOIN usuarios u ON cu.idUsuario = u.idUsuario JOIN cursos c ON cu.idCurso = c.idCurso WHERE ( cu.tipo = 3 OR cu.tipo = 2 ) AND c.estado = 2 ORDER BY cu.tipo DESC`,(error, resultado, fields) => { next(error, resultado) }) } function obtenerInformes(next) { CursosUsuariosModel .query(`SELECT cu.idCurso, c.nombre nombreC, concat(u.nombre, ' ', u.apellido) nombreU, cu.tipo FROM cursos_usuarios cu JOIN usuarios u ON cu.idUsuario = u.idUsuario JOIN cursos c ON cu.idCurso = c.idCurso WHERE ( cu.tipo = 3 OR cu.tipo = 2 ) AND c.estado = 5 ORDER BY cu.tipo DESC`,(error, resultado, fields) => { next(error, resultado) }) } function crearCursosUsuarios(cursosUsuarios, next){ CursosUsuariosModel .query(`INSERT INTO cursos_usuarios ( idUsuario, idCurso, tipo ) VALUES ?`, [cursosUsuarios], (error, resultado, fields) => { next(error) }) } module.exports = { obtenerCursosUsuariosPorIdUsuario, siCurso, obtenerResponsableYintructorPorIdCurso, obtenerParticipantesPorIdCurso, obtenerCursosUsuariosPorIdCurso, obtenerTipoPorIdCursoYidUsuario, obtenerDescripcionCursoPorId, obtenerSolicitudes, obtenerInformes, crearCursosUsuarios }<file_sep>var datosFormulario; //lo que se va a enviar var nombre, correo; $(function(){ $("input:submit").click(function() { datosFormulario= $('#formCS'); nombre = document.getElementById('nombre').value; correo = document.getElementById('correo').value; if(nombre == "" || correo ==""){ mostrarAviso(1); return false; } //valida si es correo electronico if(!correo.match('[a-z0-9._%+-]+@[a-z0-9.-]+\.+[a-z]{2,3}$')) { mostrarAviso(10); return false; } obtenerMensaje(); return false; }); }); function mostrarAviso(error){ switch(error) { case 1: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡Todos los campos son necesarios!</div>"); break; case 2: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>¡No existe un usuario con ese correo!</div>"); break; case 10: $("#aviso").html("<div class='alert alert-danger alert-dismissable'><button type='button' class='close'" +"data-dismiss='alert' aria-hidden='true'>&times;</button>?Ingrese el correo electrónico valido!</div>"); break; } } function obtenerMensaje() { $.ajax({ url: '/solicitud/crear-solicitud', type: 'POST', data: datosFormulario.serialize(), success : function(data) { var arreglo=Object.values(data); if(arreglo[1] == 3){ $('#crearSolicitudModal').modal('show') } mostrarAviso(arreglo[1]); } }); }<file_sep>var datosFormulario; $(function(){ $("input:submit").click(function() { datosFormulario= $('#editForm'); obtenerMensaje(); return false; }); }); function obtenerMensaje() { $.ajax({ url: datosFormulario.attr('action'), type: 'POST', data: datosFormulario.serialize(), success : function(data) { console.log(data) var arreglo=Object.values(data); if(arreglo[1] == 0){ $('#editarModel').modal('show') }else if(arreglo[1] == 1){ $('#error1Model').modal('show') }else if(arreglo[1] == 2){ $('#error2Model').modal('show') } } }); }
59daa005e6810e831b3a7e5d554319db80bf2f35
[ "JavaScript", "SQL" ]
17
JavaScript
raulperod/cursos-unison
b9e7b64bc927be78ce857d66957dc3a537022586
f2e7ac5c27406607125bac68d4e752b0bbaf06ea
refs/heads/master
<file_sep>#<NAME> | 1301168560 #Kelas: IFX-40-01 setwd("E:/PCAP/Adaboost/Latihan") #====================pre-processing #load Dataset datatraining <- read.csv('datatraining.csv', header = TRUE, sep = ';') datatesting <- read.csv('datatesting.csv', header = TRUE, sep = ';') #random index set.seed(9850) gp <- runif(nrow(datatraining)) data_train <- datatraining[order(gp),] View(data_train) data_trains <- data_train[, -1] #menghilangkan variabel nama datatrain_target <- data_trains[1:3500, 1:5] datatest_target <- data_trains[3501:4000, 1:5] summary(data_trains) #normalisasi train_datanorm <- as.data.frame(lapply(data_trains[,c("Like","Provokasi","Komentar", "Emosi")], normalisasi)) summary(train_datanorm) train_datatr <- train_datanorm[1:3500, ] train_datats <- train_datanorm[3501:4000,] sqrt(3500) #KNN #library(class) datatr_predict <- knn(train_datatr, train_datats, datatrain_target$Hoax, k = 81) table(datatr_predict, datatest_target$Hoax) mean(datatr_predict == datatest_target$Hoax) datatrpredict <- cbind(data_train[3501:4000, ], datatr_predict) View(datatrpredict) #===========Function KNN function (train, test, cl, k = 1, l = 0, prob = FALSE, use.all = TRUE) { train <- as.matrix(train) if (is.null(dim(test))) dim(test) <- c(1, length(test)) test <- as.matrix(test) if (any(is.na(train)) || any(is.na(test)) || any(is.na(cl))) stop("no missing values are allowed") p <- ncol(train) ntr <- nrow(train) if (length(cl) != ntr) stop("'train' and 'class' have different lengths") if (ntr < k) { warning(gettextf("k = %d exceeds number %d of patterns", k, ntr), domain = NA) k <- ntr } if (k < 1) stop(gettextf("k = %d must be at least 1", k), domain = NA) nte <- nrow(test) if (ncol(test) != p) stop("dims of 'test' and 'train' differ") clf <- as.factor(cl) nc <- max(unclass(clf)) Z <- .C(VR_knn, as.integer(k), as.integer(l), as.integer(ntr), as.integer(nte), as.integer(p), as.double(train), as.integer(unclass(clf)), as.double(test), res = integer(nte), pr = double(nte), integer(nc + 1), as.integer(nc), as.integer(FALSE), as.integer(use.all)) res <- factor(Z$res, levels = seq_along(levels(clf)), labels = levels(clf)) if (prob) attr(res, "prob") <- Z$pr res } accuracy <- function(test_data){ correct = 0 for(i in c(1:nrow(test_data))){ if(test_data[i,6] == test_data[i,7]){ correct = correct+1 } } accu = correct/nrow(test_data) * 100 return(accu) } #=========================================== data_training <- datatraining[, -1] View(data_training) data_testing <- datatesting[, -1] View(data_testing) #Fungsi Normalisasi normalisasi <- function(x) { return((x - min(x)) / (max(x) - min(x) ) ) } normalisasi(c(1,2,3,4,5)) #memasukan fungsi normalisasi pada data train_datanorm <- as.data.frame(lapply(data_training[,c("Like","Provokasi","Komentar","Emosi")], normalisasi)) summary(train_datanorm) test_datanorm <- as.data.frame(lapply(data_testing[,c("Like","Provokasi","Komentar","Emosi")], normalisasi)) summary(test_datanorm) #=================Perhitungan KNN library(class) data_predict <- knn(train_datanorm, test_datanorm, data_training$Hoax, k = 81) View(data_predict) datapredict <- cbind(datatesting, data_predict) str(datapredict) summary(datapredict) #=================export ke xlsx library(xlsx) write.xlsx(datapredict, file = "Data_prediksi.xls", sheetName = "Sheet1", col.names = TRUE, row.names = TRUE, append = FALSE) library(ggvis) datatraining %>% ggvis(~Like, ~Provokasi, fill = ~Hoax) %>% layer_points() datatraining %>% ggvis(~Like, ~Emosi, fill = ~Hoax) %>% layer_points() datatraining %>% ggvis(~Like, ~Komentar, fill = ~Hoax) %>% layer_points() datatraining %>% ggvis(~Provokasi, ~Emosi, fill = ~Hoax) %>% layer_points() datatraining %>% ggvis(~Provokasi, ~Komentar, fill = ~Hoax) %>% layer_points() datatraining %>% ggvis(~Emosi, ~Komentar, fill = ~Hoax) %>% layer_points() #============Fungsi perhitungan Euclidean Distance euclideanDist <- function(a, b){ d = 0 for(i in c(1:(length(a)-1) )) { d = d + (a[[i]]-b[[i]])^2 } d = sqrt(d) return(d) } <file_sep>data_training <- as.data.frame(lapply(datatraining[,c("Like","Provokasi","Komentar","Emosi")], normalisasi)) data_testing <- as.data.frame(lapply(datatesting[,c("Like","Provokasi","Komentar","Emosi")], normalisasi)) uji1 <- knn(train = data_training, test = data_testing, cl = datatraining$Hoax, k=5) dim(data_training) dim(data_testing) dim(datatraining) table(datatraining$Hoax, uji1) View(uji1) write.xlsx(uji1, file = "uji1.xls", sheetName = "Sheet1", col.names = TRUE, row.names = TRUE, append = FALSE)<file_sep>str(dataset_hoax) set.seed(9850) gp <- runif(nrow(dataset_hoax)) dataset <- dataset_hoax[order(gp),] str(dataset) dim(dataset) summary(dataset[,c("Like","Provokasi","Komentar","Emosi")]) normalisasi <- function(x) { return((x - min(x)) / (max(x) - min(x) ) ) } normalisasi(c(1,2,3,4,5)) dataset_n <- as.data.frame(lapply(dataset[,c("Like","Provokasi","Komentar","Emosi","Hoax")], normalisasi)) View(dataset_n) str(dataset_n) summary(dataset_n) hoax_training <- dataset_n[1:3000, ] hoax_testing <- dataset_n[3001:4000, ] hoax_training_target <- dataset[1:3000, 2:6] hoax_testing_target <- dataset[3001:4000, 2:6] data_testing <- datatesting require(class) sqrt(4000) c1 <- hoax_training_target m1 <- knn(train = hoax_training, test = hoax_testing, cl = hoax_training_target$Hoax, k=5) m1 plot(m1) table(m1) View(m1) table(hoax_testing_target$Hoax, m1) dim(hoax_training) dim(hoax_testing) dim(hoax_training_target)
2be01ef4a038b149be286fdb2dc25f0471d4cc26
[ "R" ]
3
R
devarify/KNN
71f33499cc95476f6397cf14552fa4a35f5937de
fa29d595217bcdaa5a2b564b16facf580d74e5c2
refs/heads/master
<repo_name>mountainousjourney/SmartIrrigationSystem<file_sep>/docs/pages/Scripts/Py_Requests.md --- title: "Python3 - Requests Library" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Py-Requests-Library.html folder: Scripts --- ## Basic requests - Importing the 'requests' library ```python import requests ``` - GET request ```python requests.get(<URI>) ``` - POST request ```python requests.post(<URI>,<DATA>) ``` - PUT request ```python requests.put(<URI>,<DATA>) ``` - DELETE request ```python requests.delete(<URI>) ``` --- ## Adding custom parameters - GET request with custom parameters ```python payload = {'key1': 'value1', 'key2': 'value2'} r = requests.get(<URI>, params=payload) ``` --- ## Adding custom headers - GET request with custom headers ```python url = 'https://api.github.com/some/endpoint' customHeaders = {'user-agent': 'my-app/0.0.1'} r = requests.get(<URI>, headers = customHeaders) ``` --- ## Read received data - GET request with a JSON response ```python r = requests.get('https://api.github.com/events') jsonResponse = r.json() print(jsonResponse[<JSONFIELD>]) ``` ## Source - [Official Request Library documentation](https://requests.readthedocs.io/en/latest/user/quickstart/#make-a-request) <file_sep>/docs/pages/LoRa-LoRaWAN-Module/LoRa-LoRaWAN-Overview.md --- title: "Overview of LoRa & LoRaWAN Technologies" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: overview-lora-lorawan.html folder: LoRa-LoRaWAN-Module --- **Disclaimer** : This page gives an overview of the LoRa and LoRaWAN technology. Most of the information here comes from the [Official LoRa Alliance](https://lora-alliance.org/sites/default/files/2018-04/what-is-lorawan.pdf) website. # What is LoRa ? - LoRa is a technology providing the wireless modulation/physical layer used to create a long range communication link. It is based on chirp-spread spectrum modulation. - LoRa is a LPWAN (i.e. Low Power Wide Area) technology, mainly used with IoT devices. Compared to other Cellular Networks standards (i.e. GSM, 3G, 4G...) and LAN standards (i.e. Wi-Fi and Bluetooth), it is a relatively new standard and does not support high data rates, however it offers low power consumption and can function at longer ranges (i.e. more than 1KM). - LoRa wireless modulation respects regional standards, and can be set-up to operate in the appropriate ISM bands (EU 868, EU 433, US 915, AS 430...). Lebanese laws allow us to operate in the EU868 and EU 433 bands. For more information on identifying the appropriate channels per country, please see [this document](https://link.springer.com/content/pdf/bbm%3A978-1-4842-4357-2%2F1.pdf). # What is LoRaWAN ? - As mentioned previously, LoRa defines the wireless modulation used, and enables long-range communication links. The LoRaWAN standard is built on top of LoRa, and defines the communication protocol and system architecture of the network. LoRaWAN gateways, or base stations, are deployed to receive data from LoRa modules and can cover large zones (i.e. hundreds of square kilometres) depending on the area. ![LoRa & LoRaWAN layers](../../images/LoRa-LoRaWAN-Layers.PNG) ### Network Architecture - A simple architecture is recommended for LoRaWAN networks. Having a complex network may risk straining network capacity or reduce battery life of autonomous LoRaWAN network nodes. - LoRaWAN network nodes are not associated with a specific gateway, instead we should expect each node to transmit to all gateways in proximity. Each gateway will forward the received packet to the cloud based network server, which will filter redundant packet and schedule acknowledgments for received packets. - LoRaWAN nodes follow the Aloha protocol. It means that each nodes are asynchronous and communicate when they have data ready to sent, which can be either event-driven or scheduled. Not needing each node to "wake-up" to synchronize with the network and check for messages (like in mobile networks for example), allows us to be more battery-efficient. ![LoRa & LoRaWAN layers](../../images/LoRa-network-architecture.png) ### Network Capacity - LoRaWAN allows for high network capacity by utilizing adaptive data rate and multichannel multi-mode transceiver in the gateway, so that simultaneous messages can be received on multiple channels. A network can be deployed with a minimal amount of infrastructure, and as capacity is needed, more gateways can be added, shifting up the data rates, reducing the amount of overhearing to other gateways, and scaling the capacity by 6-8x. - The ISM band at which the LoRaWAN network operates dictates the maximum data-rate and amount of simultaneous channels. For example, ISM band EU-686 allows for 10 channels and up-to 50kbps data rate, and ISM band US-915 allows for 64 channels and up-to 22kbps data rate. ### Network Security - LoRaWAN uses two layers of security : one for the network and one for the application. The network security ensures authenticity of the node in the network while the application layer of security ensures the network operator does not have access to the end user's application data. AES encryption is used with the key exchange utilizing an IEEE EUI64 identifier. ### Device Classes - LoRaWAN uses different device classes to serve different types of end-devices, each with trade-offs related to battery lifetime and downlink communication latency. ![LoRaWAN classes](../../images/LoRaWAN-classes.PNG) # Source - [LoRa-Alliance Official Documentation](https://lora-alliance.org/sites/default/files/2018-04/what-is-lorawan.pdf)<file_sep>/docs/pages/Unused-Documentation/Wireless-Certifications.md # Wi-Fi Standards Evolution - - 802.11b - *1999* - 2.4 GHz frequency - Bandwidth rate of 11 Mbps - Range of 45 meters - 802.11a - *1999* - 5 GHz frequency - Bandwidth rate of 54 Mbps - Range of 30 meters - 802.11g - *2003* - 2.4 GHz frequency - Bandwidth rate of 54 Mbps - Range of 45 meters - 802.11n - *2009* - 2.4/5 GHz frequency - Bandwidth rate of 300 Mbps - Range of 50 meters - 802.11ac - *2014* - 5 GHz frequency - Bandwidth rate of 433 Mbps and up - Range of 50 meters<file_sep>/docs/pages/Meetings/Meeting-29thJuly.md --- title: "Meeting #8 - July 29th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-29thJuly.html folder: meetings --- ### Work Completed during this Week - PCB Development - Developed a prototype PCB which connects to the Raspberry-Pi's 40-pin GPIO header, allowing it to interface with a LoRa Transceiver or a GSM module, their compatible antennas, and offering a practical interface to the Raspberry-Pi's available GPIO pins. - The prototype PCB supports UART-Compatible LoRa OR GSM module. - Work Report Available [here](PCB-Schematic-Layout-V01.html). - Low-Power Mode for the Raspberry-Pi - Research about the estimated power consumption of the Raspberry-Pi 3 Model B and Raspberry-Pi Zero under minimum and maximum load. - Research more about a developing a 'Low-Power Mode' for the Raspberry-Pi, which will use a combination of CRON jobs, Web interface, and interfacing with the LoRa & GSM modules. - Research Report Available [here](Overview-Power-Usage.html). - Miscellaneous changes - Added hyperlinks in previous meetings page, as requested. - Added GPIO pins reference in the Raspberry-Pi Diagram, as requested.<file_sep>/docs/scripts/LatLon_ETRequest.py #Import the RPi.GPIO library import RPi.GPIO as GPIO #Import the time library import time #Import the requests library import requests #Import the JSON library import json #Initializing GPIO ports #GPIO Pin 2 is assigned as output (Red LED on circuit) #GPIO Pin 3 is assigned as output (Green LED on circuit) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(2,GPIO.OUT) GPIO.setup(3,GPIO.OUT) GPIO.output(2,GPIO.LOW) GPIO.output(3,GPIO.LOW) #Defining the API-endpoint API_ENDPOINT = "<BACKEND_URL>/tiff/coordinates_to_et?latitude=<LAT>&longitude=<LON>" #Defining Headers headers = {'Content-Type' : 'application/json'} #Sending Get request and saving response as response object r = requests.get(url = API_ENDPOINT, headers=headers) #Extracting text response textresponse = r.json() #Check if the response contains a valid ET value #If the ET value is valid, flash the Green LED according to the ET value #If the ET value is invalid, flash the Red LED once if textresponse.get('et_value') is None: print("No ET value for this field!") GPIO.output(2,GPIO.HIGH) time.sleep(3) else : Et_Value = float(textresponse.get('et_value')) Et_Value = int(Et_Value) print(Et_Value) for x in range(5): GPIO.output(3,GPIO.HIGH) time.sleep(0.5) GPIO.output(3,GPIO.LOW) time.sleep(0.5) <file_sep>/docs/pages/Back-End-Server/Tracked-Events.md --- title: "Analytics" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: back-end-analytics.html folder: Back-End-Server --- **Disclaimer :** - Back-End System has been fully designed by *<NAME>* - Back-end is still under testing. As such, an URI will not be made publicly available until our back-end has been fully tested and deployed on a cloud platform. All events we want to track in the back-end server and the front-end mobile application/web interface for analytics are displayed here ## Back-end Events | API | Testcase | | ------------------- | ------------------------------------------------------------ | | Signup | invalid mobile number syntax | | Signup | using a mobile number associated with another account | | Create field | missing one of the fields / invalid value type | | Create field | missing/invalid header for authentication (authorization token) | | Update field | invalid field id | | Update field | missing/invalid header for authentication (authorization token) | | Update field | trying to update a field for another user (unauthenticated) | | Update field | missing one of the fields / invalid value type | | Get field | invalid field id | | Get field | trying to read a field for another user (unauthenticated) | | Get field | missing/invalid header for authentication (authorization token) | | Get all fields | missing/invalid header for authentication (authorization token) | | Delete field | invalid field id | | Delete field | missing/invalid header for authentication (authorization token) | | Delete field | trying to delete a field for another user (unauthenticated) | | Delete field | missing one of the fields / invalid value type | | Create irrigation | invalid field id | | Create irrigation | missing one of the fields / invalid value type | | Create irrigation | missing actual irrigation attributes when &quot;watered&quot; is true | | Update irrigation | invalid field id | | Update irrigation | missing one of the fields / invalid value type | | Update irrigation | missing actual irrigation attributes when &quot;watered&quot; is true | | Get irrigation | invalid irrigation id | | Get all irrigations | invalid field id | | ET of coordinates | invalid or missing latitude or longitude | | ET of coordinates | latitude or longitude outside of range of tiff file | ## Front-end Events | API | Testcases | | ----------------- | ------------------------------------------------------------ | | Registration | user enters invalid mobile number/doesn&#39;t enter mobile number | | Registration | user enters mobile number that belongs to another account | | Registration | user enters name of town that is not available | | Create field | user enters invalid values/missing values | | Create field | user attempts to create more than one field on registration | | ET of coordinates | user presses outside the area covered by the tiff file | | Arabization | test all pages and functionalities in app in Arabic | | Homepage | user wants to add a new field |<file_sep>/docs/pages/Back-End-Server/API-Calls.md --- title: "API Calls" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: back-end-api-calls.html folder: Back-End-Server --- **Disclaimer :** - Back-End System has been fully designed by *Roaa Al-Feel* - Back-end is still under testing. As such, an URI will not be made publicly available until our back-end has been fully tested and deployed on a cloud platform. ## POST ```/signup ``` - **Description:** Call allowing new users to sign-up and receive an authentication token/user-id. - **Request body** (in *JSON* format) : ```json { mobile_number: "+961<phoneNumber>", town_id: "<townID>" } ``` **Response body** (in *JSON* format) : ```json { user_id: "<userID>", auth_token: :"<auth_token>" } ``` --- ## POST ```/login``` - **Description:** Allows users to log-in based on a verification code. *Currently not included in features*. - **Request body** (in *JSON* format) : ```json { mobile_number: "<mobileNumber>", verification_code: "<verificationCode>" } ``` - **Response body** (in *JSON* format) : ```json { user_id: "<userID>", auth_token: "<authToken>" } ``` --- ## POST ```/fields``` - **Description**: Call for users to create a new field - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { name: "<fieldName>", area: "<areaID>", latitude: <number>, longitude: <number>, irrigation_system_id: "<irrigationSystemID", crop_type_id: "<cropTypeID>", town_id: "<townID>" } ``` - **Response body** (in *JSON* format) : ```json { field_id: "<fieldID>" } ``` --- ## GET ```/fields``` - **Description**: Returns all fields registered by a specific user - **Required Header :** ``` auth_token ``` - **Response body** (in *JSON* format) : ```json { fields: [ { name: "<fieldID>", area: <number>, latitude: <number>, longitude: <number>, crop_type_id: "<cropTypeID>", Irrigation_system_id: "<irrigationSystemID>", town_id: "<townID>", user_id: "<userID>", created_at: <timestamp>, updated_at: <timestamp> } ] } ``` --- ## GET ```/fields/<id>``` - **Description:** Returns a specific field which belong to the current user - **Required Header :** ``` auth_token ``` - **Response body** (in *JSON* format) : ```json { name: "<fieldID>", area: <number>, latitude: <number>, longitude: <number>, crop_type_id: "<cropTypeID>", Irrigation_system_id: "<irrigationSystemID>", town_id: "<townID>", user_id: "<userID>", created_at: <timestamp>, updated_at: <timestamp> } ``` --- ## PUT ```/fields/<id>``` - **Description:** Updates a field created by the current user - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { name: "<fieldID>", area: <number>, latitude: <number>, longitude: <number>, crop_type_id: "<cropTypeID>", Irrigation_system_id: "<irrigationSystemID>", town_id: "<townID>", user_id: "<userID>", created_at: <timestamp>, updated_at: <timestamp> } ``` --- ## GET ```/irrigation``` - **Description:** Returns the irrigation schedule/history for a field - **Request body** (in *JSON* format) : ```json { field_id: "<fieldID>", scheduled: <boolean> } ``` - **Response body** (in *JSON* format) : ```json { field_id: "<fieldID>", watered: <boolean>, duration_needed: <number>, actual_duration: <number>, water_needed: <number>, actual_water_used: <number>, scheduler_irrigation_time: <timestamp>, actual_irrigation_time: <number>, current_fuel_price: <number>, actual_fuel_cost: <int>, emissions: <int>, created_at: <timestamp>, updated_at: <timestamp> } ``` ## GET ```/irrigation/<irrigation_id>``` - **Description:** Returns the irrigation schedule/history for a field - **Response body** (in *JSON* format) : ```json { field_id: "<fieldID>", watered: <boolean>, duration_needed: <number>, actual_duration: <number>, water_needed: <number>, actual_water_used: <number>, scheduler_irrigation_time: <timestamp>, actual_irrigation_time: <number>, current_fuel_price: <number>, actual_fuel_cost: <number>, emissions: <number>, created_at: <timestamp>, updated_at: <timestamp> } ``` --- ## PUT ```/irrigation/<irrigation_id>``` - **Description:** Call which allows the user to notify that he irrigated one of his fields - **Request body** (in *JSON* format) : ```json { field_id: "<fieldID>", watered: <boolean>, actual_duration: <number>, actual_water_used: <number>, actual_irrigation_time: <number>, actual_fuel_cost: <number>, emissions: <number>, created_at: <timestamp>, updated_at: <timestamp> } ``` --- ## GET ```/tiff/last_updated``` - **Description :** Call to get the time at which the TIFF map was last updated - **Response body** (in *JSON* format) : ```json { last_updated: <Datestring> } ``` --- ## POST ```/app_logs/device``` - **Description:** Get user device model. This will be stored for each user, overwritten at each request - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { device_model: "<deviceModel>" } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/app_lang``` - **Description:** Get language to which the application is currently set. This will be stored for each user, overwritten at each request - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { app_lang: "<appLanguage>" } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/device_lang``` - **Description:** Get language to which the user device is currently set. This will be stored for each user, overwritten at each request - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { device_lang: "<deviceLanguage>" } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/region``` - **Description:** Get the current region of the user. This will be stored for each user, overwritten at each request - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { region: "<regionName>" } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/exit_screen``` - **Description:** Get the screen from where the user exits the application the most frequently. This will be stored for each user, overwritten at each request - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { screen_name: "<screenName>" } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/ui_errors``` - **Description:** Periodically check if any UI error occurred when using the application. This will be stored on a system-level. Contents of this list will be added to the list of errors already stored in database - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { ui_errors: [ { "error_msg": "<errorMsg>", "time": <timestamp> } ] } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/server_errors``` - **Description:** Periodically check if any server error occurred when using the application. This will be stored on a system-level. Contents of this list will be added to the list of errors already stored in database - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { server_errors: [ { "error_msg": "<errorMsg>", "time": <timestamp> } ] } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/lang_change``` - **Description:** Check if the user has changed the application language manually. This will be stored on a user-level. It will be added to the stored total value, please reset to zero locally after sending request - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { lang_change: <number> } ``` - **Response:** ```status 204 [NO_CONTENT]``` --- ## POST ```/app_logs/ui_response``` - **Description:** Get the average UI response time for each user. This will be stored on a user-level. It will be added to the stored total value and a counter of total numbers this response time has been logged will be incremented. Therefore calculating average response time per user. - **Required Header :** ``` auth_token ``` - **Request body** (in *JSON* format) : ```json { response_time: <number> } ``` - **Response:** ```status 204 [NO_CONTENT]``` <file_sep>/docs/pages/PCB-Design/PCB-Components-V01.md --- title: "BOM for our PCB Design (V01)" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: PCB-BOM-v01.html folder: PCB-Design --- - LoRaWAN Gateway System, operating on EU868 ISM Band (2pc) - LoRa Transceiver, UART Compatible & operating on EU868 ISM Band (3pc) - 868MHz U.FL Antenna for the LoRa Transceiver (3pc) - GSM Module, UART Compatible & operating on Lebanese 2G/GSM (i.e frequency 900MHz) (3pc) - 900MHz U.FL Antenna for the GSM Module (3pc) - Demultiplexer (2:1) (2pc) - 40 Pins Male Connector (3pc) - 40 Pins Female Connector (3pc) ## LoRa UART\SPI Transceiver - Name : MTXDOT-EU1-A00-1 - Dimensions : 23.62 x 23.62 x 3.51 mm ( Length x Width x Height ) - Operating Frequency : 868MHz - Serial Interfaces : UART, SPI and I2C - Operating Voltage : 2.4 to 3.57 V ( We can use a 3V3 pin on the Pi) - DigiKey Store [Link](https://www.digikey.com/product-detail/en/multi-tech-systems-inc/MTXDOT-EU1-A00-1/591-1292-ND/6237035) - Datasheet [Link](https://www.multitech.com/documents/publications/manuals/s000645.pdf) ## Antenna Connector for LoRa 868MHz - Name : ANT-868-SP - Dimensions : 27.94 x 13.7 x 1.5 mm ( Length x Width x Height ) - DigiKey Store [Link](https://www.digikey.com/product-detail/en/linx-technologies-inc/ANT-868-SP/ANT-868-SP-ND/340128) - Datasheet [Link](https://linxtechnologies.com/wp/wp-content/uploads/ant-868-sp.pdf) --- ## GSM UART Module - Name : NL-SW-GPRS - Protocol : 2G/3G GPRS/GSM - Frequencies : 850MHz, 900MHz, 1.8GHz, 1.9GHz - Dimensions : 29.0 x 33.60 x 6.63 mm - Serial Interface : UART - Antenna included ? : No - Operating Votage : 3.5V ~ 4.3V - Current - Receiving : 330mA - Current - Transmitting : 330mA - DigiKey Store [Link](https://www.digikey.com/product-detail/en/nimbelink-llc/NL-SW-GPRS/1477-1003-ND/4573470) - Datasheet [Link](https://nimbelink.com/Documentation/Skywire/2G_GPRS/30007_NL-SW-GPRS_Datasheet.pdf) ## Antenna Connector for GSM Module - Name : TG.30.8113 - DigiKey Store [Link](https://www.digikey.com/product-detail/en/taoglas-limited/TG.30.8113/931-1213-ND/3724547) - Datasheet [Link](https://cdn.taoglas.com/datasheets/TG.30.8113.pdf) --- ## Demultiplexer - Name : 74LVC1G18GW,125 - Dimensions : 2.2 x 2.2 x 1.1 mm ( Length x Width x Height ) - Operating Voltage : 1.65V ~ 5.5V - DigiKey Store [Link](https://www.digikey.com/product-detail/en/nexperia-usa-inc/74LVC1G18GW-125/1727-6071-1-ND/2753907) - Datasheet [Link](https://assets.nexperia.com/documents/data-sheet/74LVC1G18.pdf) --- ## Connector Pin Female 40-Pins - Name : PPTC202LFBN-RC - DigiKey Store [Link](https://www.digikey.com/product-detail/en/sullins-connector-solutions/PPTC202LFBN-RC/S6104-ND/807240) - Datasheet [Link](https://media.digikey.com/pdf/Data%20Sheets/Sullins%20PDFs/Female_Headers.100_DS.pdf) --- ## Connector Pin Socket 40-Pins - Name : PPTC202LFBN-RC - DigiKey Store [Link](https://www.digikey.com/product-detail/en/sullins-connector-solutions/PPTC202LFBN-RC/S6104-ND/807240) - Datasheet [Link](https://media.digikey.com/pdf/Data%20Sheets/Sullins%20PDFs/Female_Headers.100_DS.pdf) --- # TBD - Connector Header with 40-pins - Current Limiting Resistors (Must account for 3V3 and 5V supplies on the Raspberry-Pi GPIO header). - Battery\Solar Panel system connected to the PCB - EEPROM memory, so it has an ID to identify the board.<file_sep>/docs/pages/Raspberry-Pi-Model-Information/Pi-Hat-Specifications.md --- title: "Pi-Hat Official Specifications" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Pi-Hat-Specifications.html folder: Raspberry-Pi-Model-Information --- **Disclaimer** : This page gives an overview of the Pi-HAT standards recommended by the Raspberry-Pi foundation. Most of the information here comes from the [Raspberry-Pi GitHub Documentation](https://github.com/raspberrypi/hats). # Official Pi-Hat Specifications - Most Raspberry-Pi boards (Raspberry-Pi Model B+ and onwards) have been designed to support add-on boards, or 'HATs' (Hardware Attached on Top). ### HAT General Requirements 1. The HAT must have a full-size 40W GPIO connector, which spaces it at least 8mm from the Pi. It should also be taken into consideration when designing a HAT that the Raspberry-Pi 3 Model B+ has a 4-pin PoE (i.e. Power-Over-Ethernet) header near the top-right corner mounting hole. It should also not connect with the "RUN" or "PEN" header pins on the Raspberry-Pi. 2. 40W header on compatible Raspberry-Pi boards have 2 special pins (ID_SC and ID_SD) that are reserved for attachment to an ID EEPROM, which includes vendor information, GPIO map, and valid device tree information, that allows the Pi to set-up the required software for the HAT at boot time. 3. If our HAT offers Back-Powering through the 5V GPIO header pins, an ideal diode must be added for safety, in case the Pi 5V supply is also connected. The HAT should also be able to supply of 1.3A continuously to the Pi board, with 2A being the recommended value. 4. On older firmware, the GPIO pins #6, #14 and #16 might be accidentally driven at boot time. We should ensure that the HAT protects itself if this was to occur. 5. The HAT design must take into consideration the existence of display/camera flex. It can still be considered a HAT even if the design cut-out does not allow for a display/camera flex, but it is not recommended. - The Raspberry-Pi HAT Board Mechanical Specifications can be found [here](https://github.com/raspberrypi/hats/blob/master/hat-board-mechanical.pdf). ### Design Guide - The design guide for Pi-HAT boards can be found [here](https://github.com/raspberrypi/hats/blob/master/designguide.md). ### Flashing the ID EEPROM - ID EEPROM data format spec. sheet can be found [here](https://github.com/raspberrypi/hats/blob/master/eeprom-format.md). - Tools and Documentation on how to flash ID EEPROMs is available [here](https://github.com/raspberrypi/hats/blob/master/eepromutils). ### Source - [Raspberry-Pi, Github - Pi-HATs documentation](https://github.com/raspberrypi/hats) <file_sep>/docs/index.md --- title: "Documentation Overview" keywords: tags: sidebar : documentation_sidebar permalink: index.html summary: --- ![SIC Diagram](images/Diagram-SmartIrrigationSystem.png) - The *Smart Irrigation System*'s objective is to 'enhance' the irrigation process on agricultural fields. It does so by scheduling optimal irrigation cycles, which aim to reduce water wastage and maximize crop yield. - It has three main components : 1. Smart Irrigation Controller 2. Back-End Server 3. Mobile Application & Web Interface ### Smart Irrigation Controller - **Controller** : - The Smart Irrigation Controller is based on a Raspberry-Pi 3 Model B board (Raspberry-Pi model is subject to change, although they all share a similar structure, operating system, and interfaces). - **Operating System** : - It will be fitted with a pre-configured micro-SD card containing *Raspbian* (recently renamed *Raspberry-Pi OS*), and all required packages & software. - **Custom Add-on PCB** : - To function as intended, the Smart Irrigation Controller requires modules and interfaces not present on the stock Raspberry-Pi. As such, we have designed a PCB which offers support for these requirements, and which can be connected to the Raspberry-Pi through its GPIO interface. - These include (1) a LoRa Transceiver, (2) a GSM Module, (3) and additional interfaces so the Raspberry-Pi can physically communicate with Irrigation Systems. - **Power System** : - The Smart Irrigation Controller being based on Raspberry-Pi board, it must follow its requirements, and be powered constantly at a recommended 5V@2A. We can power it either through the Raspberry-Pi's micro-USB port, or through specific pins on its GPIO interface. - To ensure that our Smart Irrigation Controller is portable & self-sufficient, it remains connected to a power system, using solar power to recharge its batteries. - **Software** : - An *Apache* web server will be running constantly on the Raspberry-Pi. This web server will host the web interface, which allows farmers to control irrigation routines & receive information. - A *Python* script will be running constantly on the Raspberry-Pi. This script will execute irrigation routines, periodically poll the flow meter for changes, and handle all traffic sent/received through the external wireless modules (i.e. LoRa and GSM modules). ![SIC Diagram](images/Diagram-SmartIrrigationController.png) ### Back-End Server - **Cloud-Based** : - Back-End Server and Database are hosted on the Google Cloud IoT platform, which allows for automatic scaling & load-balancing, as well as database redundancy. - **Database** : - Stores all necessary information on users and their agricultural fields. - **Supports HTTP Requests** : - Offers a RESTful API, which facilitates requests from all devices involved in the Smart Irrigation System - Receives data from users to keep track of completed irrigation cycles - Sends recommended irrigation routines to users with registered agricultural fields ### Mobile Application & Web Interface - **Mobile Application** : - Android-based mobile application which allows user to directly configure the Irrigation Schedule on their agricultural fields (assuming they have a Smart Irrigation Controller installed), or simply keep track of recommendations concerning their agricultural fields. - **Web Interface** - Web-based Interface which runs directly on the Smart Irrigation Controller, and allows us to configure its on-board modules, set the irrigation schedule, and check Irrigation logs/history.<file_sep>/docs/pages/Meetings/Meeting-26thAugust.md --- title: "Meeting #8 - August 26th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-26thAugust.html folder: meetings --- ### Work Completed this week - Updated Documentation Website - More Research related to PCB Design - Continuing Work on the Final Report ### Topics to Discuss - Check Pi-Hat official specification - EEPROM for Device ID - Back-Power Protection ? - Boost-Converter System ? - More about Hardware (EECE 473) - Fix PCB male/female pins + Re-route and add silkscreen for each pins - Issue : Ordering Multiplexer<file_sep>/docs/pages/Scripts/Py_RPI.GPIO.md --- title: "Python3 - RPI.GPIO Library" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Py-RPI-GPIO-Library.html folder: Scripts --- ## Initialization - Importing the 'RPI.GPIO' library ```python import RPi.GPIO ``` - Select a pin numbering system ```python #BOARD numbering system GPIO.setmode(GPIO.BOARD) #BCM numbering system GPIO.setmode(GPIO.BCM) ``` - Configure channel as an input: ```python #With Pull-up resistor GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_UP) #With Pull-down resistor GPIO.setup(channel, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) ``` - Configure channel as an output: ```python GPIO.setup(channel, GPIO.OUT) ``` --- ## I/O configuration - Poll GPIO pins ```python if GPIO.input(channel): print('Input was HIGH') else: print('Input was LOW') ``` - Input detection using Wait_for_edge() function ```python GPIO.wait_for_edge(channel, GPIO.RISING) ``` - Set GPIO pin as high/low ```python #Set output as high GPIO.output(<CHANNEL>, GPIO.HIGH) #Set output as low GPIO.output(<CHANNEL>, GPIO.LOW) ``` --- ## Clean-up To clean-up any used resources, you can call the following : ```python GPIO.cleanup() ``` ## Source - [Official RPI.GPIO Documentation](https://sourceforge.net/p/raspberry-gpio-python/wiki) <file_sep>/docs/pages/Powering-The-System/Lowering-The-System-Power-Consumption.md --- title: "Reducing the System's Power Usage" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Lowering-The-System-Power-Consumption.html folder: Powering-The-System --- - The Raspberry-Pi does not offer a '*stand-by*' mode. We will need to manually manage the board's components and any running software to achieve the lowest power consumption when the Pi is idle or under use. ### Software running on the *Smart Irrigation Controller* We will be using *'Lite'* OS on our Raspberry-Pi, with contains only the daemons & user processes necessary for the *Smart Irrigation Controller* to operate : - Essential Raspbian daemons (like *CRON*). - *Apache Web Server*, to have the Web Interface up-and-running. - Irrigation Control Script (Python-based) - *INCRON*, which is a similar program to *CRON* but instead of running commands based on time, it triggers commands based on file/directory events. We will use it in the *Smart Irrigation Controller* to modify *CRON* jobs according to user preferences on the Web interface. ### Handling Hardware Required by the *Smart Irrigation Controller* The following components are required for the *Smart Irrigation Controller* to operate properly. These components will be turned on/off to conserver power, depending on the needs of the *Smart Irrigation Controller* : - LoRa Transceiver OR GSM Module - Any additional device connected to the GPIO interface for Irrigation control (i.e. flow meters, actuators...). ### Disabling Raspberry-Pi On-Board Components Some of the components present on the Raspberry-Pi are not necessary to the functioning of the *Smart Irrigation Controller*, and as such it is preferable to disable them. Raspbian-OS allows us to disable most of these components through software : - On-Board HDMI Port - On-Board USB Ports - On-Board Wi-Fi Module - On-Board Bluetooth Module - On-Board CSI Camera Port - On-Board DSI Display Port - On-Board 4-Poles Stereo Output and Composite Video Port - On-Board LEDs ### Source - [HowToForge - What is Incron ?](https://www.howtoforge.com/tutorial/trigger-commands-on-file-or-directory-changes-with-incron/)<file_sep>/docs/pages/LoRa-LoRaWAN-Module/LoRaWAN-Gateways.md --- title: "Selecting a LoRaWAN Gateway" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: selecting-lorawan-gateway.html folder: LoRa-LoRaWAN-Module --- - To give internet access to our LoRaWAN nodes, we need them to connect to a main gateway. - **IMPORTANT :** Our gateway should operate on the ISM band EU433\EU868, as it is not legal to operate on other LoRaWAN ISM bands in Lebanon (such as US915). --- ### **Type-1, Carrier-grade LoRaWAN Gateways** : - These models are intended for use with large-scale, commercial systems. - They require minimal set-up and can support large amounts of LoRaWAN nodes, but they are also the most expensive. | Company | Model | # of Channels | Operating Frequency | Wi-Fi & Bluetooth | Price | | -------------- | --------- | --------------------- | ------------------------------- | ----------------- | ------------- | | Laird | [Laird RG1xx Series](https://eu.mouser.com/new/laird-connectivity/laird-sentrius-rg1-lora-gateway/) | Up-to 8 channels | 868/915MHz Support | Supported | Not specified | | Kerlink | [Kerlink iBTS](http://www.kerlink.com/en/products/lora-iot-station-2/wirnet-ibts) | Up-to 8 channels |868/915MHz Support | Supported | Not specified | | Lorix | [LORIX One](http://lorixone.io) | Up-to 8 channels |868/915MHz Support | Supported | 500 USD | | AAEON | [Aaeon UP](http://industrialgateways.eu/docs/) | Up-to 8 channels |868/915MHz Support | Supported | 550 USD | | Cisco | [Cisco LoRaWAN Gateway](https://www.cisco.com/c/en/us/products/routers/wireless-gateway-lorawan/index.html) | Up-to 16 channels | 868/915MHz Support | Supported | 500 USD | | Gemtek | All Gemtek models available [here](https://www.gemteks.com/en/products/lora-iot/gateway) | Up-to 8 channels | 868/915MHz Support | Supported | Not specified | | Tekletic | All Tektelic models available [here](https://tektelic.com/iot/lorawan-gateways/) | Up-to 8 channels | 868/915MHz Support | Supported | Not specified | | Ursalink | [UG87 Outdoor Gateway](https://www.ursalink.com/en/ug87-lorawan-gateway/) | Up-to 8 channels | 868/915MHz Support | Supported | Not specified | --- ### **Type-2, Pi-Hats** - Pi-Hats modules are designed to be compatible with the GPIO interface of the Raspberry-Pi. - There are LoRaWAN Gateway Pi-Hats models available commercially. They are not sold bundled with Raspberry-Pi boards. - This approach would offer a good compromise between price and setup complexity. | Company | Model | # of Channels | Operating Frequency | Price | | ------- | ----- | -------- | ---------- | ------| | Pi-Supply | [LoRa Gateway HAT for Raspberry Pi](https://uk.pi-supply.com/products/iot-lora-gateway-hat-for-raspberry-pi) | Up-to 8 channels | 868\915MHz Support | Around 160 USD| | Adafruit | [LoRa Gateway Hat - SX1301 Based](https://www.adafruit.com/product/4284) | Up-to 8 channels | 915MHz Support | 150 USD | | RAK-Wireless | [RAK2245 RPi HAT Edition](https://store.rakwireless.com/products/rak2245-pi-hat?variant=26653392502884)| Up-to 8 channels | 868MHz Support | 120 USD | --- ### **Type-3, Full-Enclosed Raspberry-Pi systems** - Fully-Enclosed systems, containing a Raspberry-Pi board and LoRaWAN gateway module, along with additional accessories. - Good compromise between price and setup complexity, if we account that it comes bundled with a pre-configured Raspberry-Pi board. | Company | Model | # of Channels | Operating Frequency | Price | | -------------- | --------- | --------------------- | ------------------------------- | ----------------- | | Sparkfun | [LoRa Raspberry-Pi Gateway with Enclosure](https://www.sparkfun.com/products/15336) | Up-to 8 channels | 915MHz support | 200 USD | | IMST | [LoRaWAN Gateway Platform](https://shop.imst.de/wireless-modules/lora-products/36/lite-gateway-demonstration-platform-for-lora-technology) | Up-to 8 channels | 868MHz | Around 230 USD | --- ### **Type-4, Custom LoRaWAN gateway** - Cheapest option, but also the most complex. - We could order LoRaWAN gateway modules, such as the *IC880A-SPI*, which has an operating frequency of 868MHz and supports 8 channels. Extensive documentation is also available online. - We would have to tinker with the hardware, and write code to configure how the Raspberry-Pi and the module communicate using the *UART* \ *SPI* \ *I2C* interface. - Guide on setting up a LoRaWAN gateway using a Raspberry-Pi and a IC880A-SPI concentrator board is available [here](https://github.com/ttn-zh/ic880a-gateway/wiki). - Expected total price (Raspberry-Pi + IC880A-SPI) is 170 USD. - Open-source *C* code, which we could use to configure the LoRaWAN gateway module, has been made available by Semtech [here](https://github.com/Lora-net/lora_gateway). Semtech designs almost all commercially available LoRaWAN gateway modules. # Source : [The Things Network - Commercially Available LoRaWAN Gateways ](https://www.thethingsnetwork.org/docs/gateways/start/list.html)<file_sep>/docs/pages/Raspberry-Pi-Model-Information/RaspberryPi-3-Model-B.md --- title: "Raspberry-Pi 3 Model B" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Raspberry-Pi-3-Model-B.html folder: Raspberry-Pi-Model-Information --- **Disclaimer** : This page gives an overview of the Raspberry-Pi 3 Model B. Most of the information here comes from the official [Raspberry-Pi 3B Product Page](https://www.raspberrypi.org/products/raspberry-pi-3-model-b-plus/). ![Image of Rasp3 modelB](https://images-na.ssl-images-amazon.com/images/I/71EPckcD8ZL._AC_SL1244_.jpg) - **Processor :** - Broadcom BCM2837B0, Cortex-A53 (ARMv8) 64-bit SoC @ 1.4GHz (Quad-core processor). - **Networking :** - Dual-band wireless LAN / 2.4GHz and 5GHz IEEE 802.11.b/g/n/ac Wireless LAN - Bluetooth 4.2/BLE (Bluetooth Low-Energy) - Ethernet port - Power-over-Ethernet support (Needs separate module) - **RAM :** - 1GB LPDDR2 SDRAM - **GPIO Interface :** - Extended 40-pin GPIO header - GPIO output pins can set to high (3.3V) or low (0V) \ GPIO input pins can be read as high (3.3V) or low (0V). - Internal pull-up or pull-down resistors are present on each pins. Pins GPIO2-GPIO3 have fixed pull-up resistors, but other pins can be configured in software. - Raspberry-Pi supports Pulse-Width modulation - Software Pulse-Width Modulation is available on all GPIO pins. - Hardware Pulse-Width Modulation is available on pins GPIO12, GPIO13, GPIO18, GPIO19. - Raspberry-Pi supports UART with the following pin configuration : - RX(GPIO15), TX (GPIO16) - Raspberry-Pi supports SPI with the following pin configuration : - SPI0: MOSI (GPIO10); MISO (GPIO9); SCLK (GPIO11); CE0 (GPIO8), CE1 (GPIO7) - SPI1: MOSI (GPIO20); MISO (GPIO19); SCLK (GPIO21); CE0 (GPIO18); CE1 (GPIO17); CE2 (GPIO16) - Raspberry-Pi supports I2C with the following pin configuration : - EEPROM Data: (GPIO0); EEPROM Clock (GPIO1); Data: (GPIO2); Clock (GPIO3) ![Raspberry-Pi 3 GPIO Interface](https://www.raspberrypi.org/documentation/usage/gpio/images/gpiozero-pinout.png) - **Other Interfaces :** - 4x USB 2.0 ports - CSI camera port for connecting a Raspberry Pi camera - DSI display port for connecting a Raspberry Pi touchscreen display - 4-pole stereo output and composite video port - Micro SD port for loading your operating system and storing data. - 1x Full-size HDMI port - **Required Power :** - Typical PSU current capacity is 2.5A - Typical bare-board active current consumption is 400mA - Maximum total USB peripheral current draw is 1.2A - Recommended micro-USB connector : 5 V/2.5 A DC - **Miscellaneous Information :** - The Raspberry-Pi 3 Model B will remain in production until January 2026. - Global compliance and safety certificates [here](https://www.raspberrypi.org/documentation/hardware/raspberrypi/conformity.md) - Operating temperature : 0-50°C - Raspberry-Pi 3 Model B mechanical drawing available [here](https://github.com/raspberrypi/documentation/raw/master/hardware/raspberrypi/mechanical/rpi_MECH_3bplus.pdf) - Raspberry-Pi 3 Model B schematic diagrams available [here](https://www.raspberrypi.org/documentation/hardware/raspberrypi/schematics/rpi_SCH_3bplus_1p0_reduced.pdf) ## Resources - [Raspberry-Pi 3 Model B, Official Page](https://www.raspberrypi.org/products/raspberry-pi-3-model-b-plus/)<file_sep>/docs/pages/Meetings/Meeting-30thJune.md --- title: "Meeting #4 - June 30th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-30thJune.html folder: meetings --- ### Work Completed during this Week - Web Interface update : - Removed 'Rain Fed' option from possible Irrigation Systems in both the Mobile Application and Web Interface - Revamped the registration process as we've discussed last week. - Added a "Scheduling" page, which allows to set intervals for the irrigation routine - Added a "History" page, which allows the user to check their fields irrigation history ### Updated documentation : - Irrigation Systems - Drip Irrigation system - Sprinkler Irrigation system - Surface Irrigation system - Back-End System - Back-end API Calls - Analytics cases on both the Front-End and Back-End - Raspberry-Pi hardware - Raspberry-Pi 3 Model B overview (Model I have borrowed from AUB Labs) - Raspberry-Pi Zero overview - LoRa & LoRaWAN - Overview of LoRa & LoRaWAN technology - Portable Power Supply - Using a solar energy supply with the Raspberry-Pi ### Smart Irrigation Controller - Web Interface - Registration Process in the Web Interface - Allow user to select a field directly on the map, just like the Mobile Application - Allow user to enable/disable notifications - Allow user to select what type or Irrigation schedule they need (i.e. Manual / Automatic) - History/Log Tab in the Web Interface - Provide analytics/logs related to previous irrigation data. - Scheduler Tab in the Web Interface (only available in "Manual Irrigation" mode) - Let the user set an irrigation schedule on a weekly basis - Offer recommendations to the for the irrigation schedule<file_sep>/docs/pages/PCB-Design/Schematic-and-PCB Layout-v02.md --- title: "Schematic and PCB Layout (V02)" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: PCB-Schematic-Layout-V02.html folder: PCB-Design --- - Complete KiCad project (including schematics, footprints and layouts) is available [here](../../zip/SmartIrrigationController-V2.zip). - For this implementation, we've used the UART interface of the Raspberry-Pi (GPIO Pins #14 and #15), two additional GPIO Pins to control elements of the circuit ( GPIO Pins #22 and #23 ), a 3v3 output power pin, and a ground pin. - There are still 24 available GPIO pins, which can be used to control additional modules. The SPI & I2C interfaces are also fully available, if we'd like to use them with other modules. # Schematic Circuit ![Schematic](../../images/PCB-Diagram-V2.PNG) # PCB Layout Front Layer : ![Front Layer PCB](../../images/PCB-Layout-Front-v2.png) Back Layer : ![Back Layer PCB](../../images/PCB-Layout-Back-v2.png) 3D View : ![3D View #1](../../images/PCB-3D-V2-1.png)<file_sep>/docs/pages/PCB-Design/PCB-Components-V02.md --- title: "BOM for our PCB Design (V02)" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: PCB-BOM-v02.html folder: PCB-Design --- - LoRaWAN Gateway System, operating on EU868 ISM Band (2pc) - LoRa Transceiver, UART Compatible & operating on EU868 ISM Band (3pc) - 868MHz U.FL Antenna for the LoRa Transceiver (3pc) - GSM Module, UART Compatible & operating on Lebanese 2G/GSM (i.e frequency 900MHz) (3pc) - 900MHz U.FL Antenna for the GSM Module (3pc) - Demultiplexer (2:1) (2pc) - 40 Pins Male Connector (3pc) - 40 Pins Female Connector (3pc) *Table of components can be downloaded in spreadsheet format [here](../../zip/OrderComponentsV02.zip)* ### LoRaWAN Gateway Module - Number of supported channels : Up-to 8 channels - Frequency Supported : Should operate on the same ISM band as our selected LoRa transceiver, in this case ISM band EU868. - **OPTION 1** : Buy an additional Raspberry-Pi, and a PI-HAT LoRaWAN Gateway module (sold separately). - *Proposed Model* : Pi-Supply (868MHz Support) (https://uk.pi-supply.com/products/iot-lora-gateway-hat-for-raspberry-pi) - **OPTION 2**: Buy a Fully Enclosed System, which includes a Raspberry-Pi board and a LoRaWAN Gateway module - *Proposed Model*: IMST (868 MHz Support) (https://shop.imst.de/wireless-modules/lora-products/36/lite-gateway-demonstration-platform-for-lora-technology). Requires additional accessories : Antenna (https://shop.imst.de/wireless-modules/accessories/19/sma-antenna-for-ic880a-spi-wsa01-im880b-and-lite-gateway) and Power Supply (https://shop.imst.de/wireless-modules/accessories/37/power-supply-unit-for-lite-gateway) ### LoRa Transceiver - Serial Interface Support : UART - Frequency Supported : Should operate on the same ISM band as our selected LoRaWAN Gateway, in this case ISM band EU868. - *Proposed Model* : Digikey (868MHz Support) (https://www.digikey.com/product-detail/en/multi-tech-systems-inc/MTXDOT-EU1-A00-1/591-1292-ND/6237035). This module is compatible with an U.FL antenna, which must be bought separately. ### 868MHz U.FL Antenna for the LoRa Transceiver - No specific request for this component. - No Proposed Model ### GSM Module - Serial Interface Support : UART - Technology Support : E-GSM, which operates at 900MHz frequency in Lebanon - *Proposed Model* : Digikey (2G) (https://www.digikey.com/product-detail/en/nimbelink-llc/NL-SW-GPRS/1477-1003-ND/4573470). This module is compatible with an U.FL antenna, which must be bought separately. Our antenna should support the 900MHz frequency, which is related to 2G/EDGE technology for data services. ### 900MHz U.FL Antenna for the GSM Module - No specific request for this component. - No Proposed Model ### 40 Pins Male Connector - No specific request for this component. - No Proposed Model ### 40 Pins Female Connector - Should be compatible with the Raspberry-Pi's GPIO Interface - No Proposed Model <file_sep>/docs/pages/EECE-500-Deliverables/Final-Report-Presentation.md --- title: "Final Report & Presentation" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: final-report-presentation.html folder: EECE-500-Deliverables --- We were tasked in EECE-500, upon completion of our Internship, to provide a Final Report summarizing what tasks we've completed and what skills we've learned. You can download the Final Report associated with my Internship [here](../../zip/FReport-EECE500-Hsandid.zip) (*Student : <NAME>*).<file_sep>/docs/pages/Meetings/Meeting-22thJuly.md --- title: "Meeting #6 - July 22th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-22thJuly.html folder: meetings --- ### Work Completed during this Week - Research on GSM module compatible with the Raspberry-Pi. Available [here](selecting-a-gsm-module.html) - Smart Irrigation Controller Diagram. Available [here](index.html). ### Flow meters - Discuss the usage of flow meter with the *Smart Irrigation Controller*. <file_sep>/docs/pages/LoRa-LoRaWAN-Module/LoRa-Transceivers.md --- title: "Selecting a LoRa Transceiver" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: selecting-lora-transceiver.html folder: LoRa-LoRaWAN-Module --- - To allow our Raspberry-Pi board to receive\transmit data in a LoRaWAN network, we must equip it with a LoRa transceiver - **IMPORTANT :** Our transceiver should operate on the ISM band EU433\EU868, as it is not legal to operate on other LoRaWAN ISM bands in Lebanon (such as US915). --- ### **Type-1, Pi-Hat LoRa Transceivers** : - Pi-Hats modules are designed to be compatible with the GPIO interface of the Raspberry-Pi. - **IMPORTANT** : How many pins does each Pi-Hat model require ? If the Pi-Hat uses too much pins, we might not be able to connect the Raspberry-Pi to other components (i.e. flow meters, GSM modules...). | Manufacturer | Operating Frequency | Price | Store Link | | ------- | -------- | ----- | ----- | | Pi Supply | 868MHz & 915MHz versions available | 150 USD | [Link](https://uk.pi-supply.com/products/iot-lora-node-phat-for-raspberry-pi?_pos=41&_sid=30d832a4c&_ss=r)| | IoT Store | 433MHz & 915MHz versions available | 60 USD | [Link](https://www.iot-store.com.au/products/lora-and-gps-hat-for-raspberry-pi-long-range-transceiver) | | Waveshare | 915MHz version available | 35 USD | [Link](https://www.amazon.com/SX1262-LoRa-HAT-Transmission-Communication/dp/B07W83FCCZ) | | Dragino | 868MHz version available | 30 USD | [Link](https://www.antratek.com/raspberry-pi-lora-gps-hat-868mhz) | | Turta | 433MHz & 868MHZ & 915MHz versions available | 60 USD | [Link](https://turta.io/collections/raspberry-pi-hats/products/lora-hat?variant=12549674958895) | --- ### **Type-2, LoRa Transceivers Modules** - LoRa modules which can interface with the Raspberry-Pi board through UART\I2C\SPI | Manufacturer | Operating Frequency | Price | Store Link | | ------- | -------- | ----- | ----- | | RAK-Wireless | 868MHz & 915MHz versions available | 25 USD | [Link](https://uk.pi-supply.com/products/rak813-lorab-ble5-and-lora-module-based-on-nrf52832-and-sx127x?_pos=15&_sid=30d832a4c&_ss=r)| | RAK-Wireless | 433MHz & 868MHz & 915MHz versions available | 15 USD | [Link](https://uk.pi-supply.com/products/rak811-lora-lorawan-module?_pos=18&_sid=30d832a4c&_ss=r) | | REYAX | 868MHz & 915MHz versions available | 20 USD | [Link](https://www.amazon.com/RYLR896-Module-SX1276-Antenna-Command/dp/B07NB3BK5H/ref=sr_1_1?dchild=1&keywords=LoRa&qid=1594195384&rnid=2941120011&s=pc&sr=1-1) | | HopeRF | 915MHz version available | 15 USD | [Link](https://www.amazon.com/RFM95W-915Mhz-Transceiver-SX1276-compatible/dp/B01F6HPWMC)| | Aptinex | 433MHz & 868MHz versions available | 35 USD | [Link](https://www.amazon.com/Aptinex-LoRaNode-RN2483A-Microchip-LoRaWAN/dp/B01N2RJPMJ/ref=sr_1_4?dchild=1&keywords=LoRa&qid=1594195384&rnid=2941120011&s=pc&sr=1-4) |<file_sep>/docs/pages/Powering-The-System/Using-Solar-Power.md --- title: "Using Solar Power" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Using-Solar-Power.html folder: Powering-The-System --- - We'd like to develop a portable power solution using solar energy to power our *Smart Irrigation Controller*. - We intend for the *Smart Irrigation Controller* to be connected to a rechargeable battery, which would supply it with 5V. The rechargeable battery will be in turn connected to a portable solar panel, which would provide it with enough electrical energy to run our *Smart Irrigation Controller*. - **Important** : The Pi supports a 5V@2A input power. If our battery supplies more than 5V input voltage, we might have to use additional circuitry (i.e. Voltage Divider Circuit, DC/DC Power Converter, Linear Voltage Regulator) to reduce its input power to the Pi. Also, we might want to include a Current Regulator circuit to control the input current based on the boards' needs. ![Solar Energy Solution Diagram](../../images/Diagram-Solar-Energy.PNG) # Selecting components - **Solar Panel** : We need a solar panel able to support a battery outputting 5V @ 2A. A close match would be this [model](https://www.adafruit.com/product/2747) from Adafruit. - **Battery** : We'd like to provide an input power of 5V @ 2A to the Raspberry-Pi. There are many battery models available, but we'd likely have to add some voltage/current limiting circuits in-between the battery and the Raspberry-Pi. - **Interface with the Raspberry-Pi** : To power the Pi, we can connect our battery to either the Micro-USB port , or through specific pins of its GPIO interface. We need to see what interfaces is more suitable to our implementation.<file_sep>/docs/pages/Scripts/Requesting-ET-Value-From-LatLon.md --- title: "Python - Requesting ET Value from Latitude & Longitude Info" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Requesting-ET-Value-From-LatLon.html folder: Scripts --- - Script can be downloaded [here](../../scripts/LatLon_ETRequest.py). - `BACKEND_URL` must be modified to match the current URL the server is assigned to. - `LAT` and `LON` must be valid latitude and longitude coordinates which are located in Lebanon. ```python #Import the RPi.GPIO library import RPi.GPIO as GPIO #Import the time library import time #Import the requests library import requests #Import the JSON library import json #Initializing GPIO ports #GPIO Pin 2 is assigned as output (Red LED on circuit) #GPIO Pin 3 is assigned as output (Green LED on circuit) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(2,GPIO.OUT) GPIO.setup(3,GPIO.OUT) GPIO.output(2,GPIO.LOW) GPIO.output(3,GPIO.LOW) #Defining the API-endpoint API_ENDPOINT = "<BACKEND_URL>/tiff/coordinates_to_et?latitude=<LAT>&longitude=<LON>" #Defining Headers headers = {'Content-Type' : 'application/json'} #Sending Get request and saving response as response object r = requests.get(url = API_ENDPOINT, headers=headers) #Extracting text response textresponse = r.json() #Check if the response contains a valid ET value #If the ET value is valid, flash the Green LED according to the ET value #If the ET value is invalid, flash the Red LED once if textresponse.get('et_value') is None: print("No ET value for this field!") GPIO.output(2,GPIO.HIGH) time.sleep(3) else : Et_Value = float(textresponse.get('et_value')) Et_Value = int(Et_Value) print(Et_Value) for x in range(5): GPIO.output(3,GPIO.HIGH) time.sleep(0.5) GPIO.output(3,GPIO.LOW) time.sleep(0.5) ```<file_sep>/docs/pages/Meetings/Meeting-19thAugust.md --- title: "Meeting #7 - August 19th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-19thAugust.html folder: meetings --- ### Work Completed during this Week - Selecting PCB components to order - List of components is available [here](PCB-BOM-v02.html) - Final Deliverable for the Internship - I have started writing a design document summarizing my work on the Smart Irrigation Controller. It is still largely incomplete - Redesigning the PCB board - There doesn't to be a common pattern amongst breakout board for LoRa transceivers and GSM modules, so I based my design on the following components : - LoRa Transceiver : *MTXDOT-EU1-A00-1* - GSM Module : *NL-SW-GPRS* - Updated version of the PCB design can be found [here](PCB-Schematic-Layout-V02.html) ### PCB Board Re-design - Almost all modules and breakout boards found on the market for LoRa and GSM include some sort of direct antenna connector. I did not look into the RF side of things, especially when it comes to PCB traces. ### Final Deliverable for the Internship - This design document follows the Standard IEEE requirement document outline, which I have added [here](ieee-document-template.html) (*Credits : Dr. <NAME>, EECE425 - Embedded Microprocessor Systems Design*) - Topics I have started covering : - Performance and expected power usage of the Raspberry-Pi model we are using in our prototype (Raspberry-Pi 3 Model B). - Specify all open-source and licensed software we are using, and which we will package into a standalone image to use with our *Smart Irrigation Controller*. - PCB Interface we've designed for the *Smart Irrigation Controller*, with a mention of what CAD tool we've used, any additional Symbols & Footprints we had to design ourselves, and which specific or general modules our PCB targets. - Compatibility issues & region our *Smart Irrigation Controller* is targeted at. - Web Interface for the *Smart Irrigation Controller*. - Planned use of the Levantine Mobile Application to control the *Smart Irrigation Controller*. - Add diagrams representing the systems and how its different components communicate. - Talk about the back-end system, explain its API calls and talk about analytics. ### (Personal Questions) Further Career & Education related to Embedded Systems - What should I expect if I went into the field of Embedded Systems (Hardware & Software aspects). - What are the current 'hot' topics in Embedded Systems ? ( IoT Systems, Networking, Machine Learning, 3d Applications and Virtual Reality...)<file_sep>/docs/pages/Powering-The-System/Overview-Power-Requirements.md --- title: "Overview" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Overview-Power-Usage.html folder: Powering-The-System --- The Raspberry-Pi can be powered in two ways : - **(1)** Through its Micro-USB port, with a recommended input voltage of 5V input current of 2A. ![Micro-USB Power](../../images/Pi-Micro-USB.PNG) - **(2)** Through it's GPIO interface by plugging a 5V source to Pin #2 on the GPIO header, and the ground of this 5V source to Pin #6 on the GPIO header. ![GPIO Power](../../images/Diagram-Powering-The-Pi-Through-GPIO.PNG) - **Warning** : The recommended method of powering the Raspberry-Pi is through its Micro-USB port, as it offers regulation and fuse protection to protect from over-voltage and current spikes. **There is no regulation and fuse protection on the GPIO Interface** meaning that any over-voltage, current spikes, or reverse polarization might fry the GPIO interface, or worse, the Pi itself. # Power Consumption Benchmarks We know that the Raspberry-Pi requires an input voltage of 5V. We will now see how much current (and coincidentally power) the Raspberry-Pi draws under different load conditions. All the benchmarks will be taken from the [PidRamble](https://www.pidramble.com/wiki/benchmarks/power-consumption) website. The boards are running stock Raspbian Lite, with no additional software installed and only running basic daemons. There are no additional peripherals connected to the Pi boards. | Raspberry-Pi Model | Pi State | Power Consumption | | ---------------------------- | ----------------| -------------| | Raspberry-Pi 3 B+ | Idle | 350 mA (1.9 W) | | Raspberry-Pi 3 B+ | Maximum CPU Load | 980 mA (5.1 W) | | Raspberry-Pi 3 B+ | Minimal CPU Load with HDMI & LEDs disabled | 350 mA (1.7 W) | | Raspberry-Pi 3 B | Idle | 260 mA (1.4 W) | | Raspberry-Pi 3 B | Maximum CPU Load | 730 mA (3.7 W) | | Raspberry-Pi 3 B | Minimal CPU Load with HDMI & LEDs disabled | 230 mA (1.2 W) | | Raspberry-Pi 2 B | Idle | 220 mA (1.1 W) | | Raspberry-Pi 2 B | Maximum CPU Load | 400 mA (2.1 W) | | Raspberry-Pi 2 B | Minimal CPU Load with HDMI & LEDs disabled | 200 mA (1.0 W) | | Raspberry-Pi Zero | Idle | 80 mA (0.4 W) | | Raspberry-Pi Zero | Maximum CPU Load | 240 mA (1.2 W) | | Raspberry-Pi Zero | Minimal CPU Load | 40 mA (0.2 W) | **Note** : All Raspberry-Pi models consume around 0.1W when powered off, until they are disconnected from their power source. # Source - [PiHut - How do I power my Raspberry Pi?](https://thepihut.com/blogs/raspberry-pi-tutorials/how-do-i-power-my-raspberry-pi) - [PidRamble - Raspberry-Pi Power Consumption Benchmarks](https://www.pidramble.com/wiki/benchmarks/power-consumption)<file_sep>/docs/pages/Meetings/Meeting-23thJune.md --- title: "Meeting #3 - June 23th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-23thJune.html folder: meetings --- ### Work Completed during this Week - Added map interface to the web interface. - Added registration process to the S.I.C. web interface. - Set-up a web server on the Raspberry-Pi board, using *Apache*. ### Smart Irrigation Controller - Web Interface - Discuss the newly-added map interface - Discuss the newly-added registration process - Current Python scripts are redundant with the web interface. Implement python scripts which runs continually in the background - Re-discuss the "Irrigation Control Method" from last meeting, and clarify how it should be implemented. How much will we rely on algorithms to control the irrigation routine ? How much control should we give to the user ? ### Upcoming Report - Raspberry-Pi 3 Model B Hardware \ Interfaces \ Power & Voltage & Current Limitations. - Raspberry-Pi Zero Hardware \ Interfaces \ Power & Voltage & Current Limitations. - Linux distribution to use, if we are going to ship a product out commercially (i.e. Legal Issues, and lightweight distribution). - Power supply solutions to make the Rasp. Pi portable using external batteries and solar power. - Requirements of the LoRa interface, especially when connected with a Raspberry-Pi. ### Post-Meeting Decisions - Add a history/logs page to the web interface - Add a scheduling page on the web interface - Set-up an alternative to host documentations related to the *Smart Irrigation Controller* <file_sep>/docs/pages/GSM-Module/GSM-Module.md --- title: "Selecting a GSM Module" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: selecting-a-gsm-module.html folder: GSM-Module --- - To allow our Raspberry-Pi board to receive\transmit data over cellular network, we must equip it with a GSM transceiver. - All models listed here require a SIM card with an active mobile broadband subscription. - A reference to the Lebanese National Frequency allocation Table can be found [here](http://www.tra.gov.lb/Library/Files/Uploaded%20files/LNFT_TRA_Final%20Version%20for%20publication_24062008.pdf). It contains all information related to the bands occupied by mobile traffic & data services in Lebanon. - Here is a reference of cellular network technologies and their associated bandwidth speed (*Image Source: KensTechTips.com*) : ![Cellular Technologies](../../images/Table-Cellular-Technology-Speed.PNG) --- ### **Type-1, Pi-Hat GSM Module:** - Pi-Hats modules are designed to be compatible with the GPIO interface of the Raspberry-Pi. - **IMPORTANT** : How many pins does each Pi-Hat model require ? If the Pi-Hat uses too much pins, we might not be able to connect the Raspberry-Pi to other components (i.e. flow meters, LoRa modules...). | Manufacturer | Price | Store Link | | ------------ | ----------| ------------------------------------------------------------ | | WaveShare | 23 USD | [Link](https://www.waveshare.com/sim800c-gsm-gprs-hat.htm)| | Adafruit | 40 USD | [Link](https://learn.adafruit.com/fona-tethering-to-raspberry-pi-or-beaglebone-black) | --- ### **Type-2, GSM Module** - General purpose modules that communicate over UART\I2C\SPI | Manufacturer | Price | Store Link | | ------------ | ----------| ------------------------------------------------------------ | | SIMCOM | 15 USD (Module Only) | [Link](https://www.amazon.com/SIM800L-Wireless-Module-Quad-Band-Antenna/dp/B07SY9QVRT) | |SIMCOM | 20 USD | [Link](https://www.amazon.com/Nobrand-Development-Module-Suitable-Antenna/dp/B085MQGD64/ref=sr_1_8?dchild=1&keywords=sim900&qid=1595387285&s=electronics&sr=1-8)| --- ### **Type-3, 4G USB Dongle** - The Raspberry-Pi supports USB dongle. We can buy one locally from the main telecommunications companies (i.e. Alfa\MTC). - Prices of dongles are ambiguous due to them being listed in dollars (Do Alfa & MTC respect the 1515LBP\USD rate ?). Full list available here : [Alfa Store](https://www.alfa.com.lb/en/devices-accessories/dongles-routers/about) - [MTC Store](https://www.touch.com.lb/autoforms/portal/touch/personal/internet-offers/highspeedinternet/4g-devices) - Mobile Broadband bundles - All Alfa Mobile Broadband plans are available [here](https://www.alfa.com.lb/en/mobile-broadband/about) - All MTC Mobile Broadband plans are available [here](https://www.touch.com.lb/autoforms/portal/touch/personal/internet-offers/residentialbroadband/tariffs) # Source - [Ken's Tech Tips - Cellular Networks Technologies](https://kenstechtips.com/index.php/download-speeds-2g-3g-and-4g-actual-meaning)<file_sep>/docs/pages/Meetings/Meeting-8thJune.md --- title: "Meeting #1 - June 8th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-8thJune.html folder: meetings --- ### Work Completed during this Week - No work related to the internship done before the first meeting ### Internship Logistics - Considering the current situation, we need to discuss the logistics of some aspects (i.e. Meeting with agriculture experts, work in the field, ordering required hardware like the LoRa interface...). ### Post-Meeting Decisions - During this first meeting, we have discussed the scope of my work on the *Smart Irrigation Controller* for the duration of the internship - Developing a working prototype for the *Smart Irrigation Controller*, targeted to run on a Raspberry-Pi. - Maintaining the Mobile Application tied to the *Smart Irrigation Controller*, and add any features if considered necessary. <file_sep>/docs/pages/Scripts/Requesting-ET-Value-From-FieldID.md --- title: "Python - Requesting ET Value from Field ID" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Requesting-ET-Value-From-FieldID.html folder: Scripts --- - Script can be downloaded [here](../../scripts/FieldID_ETRequest.py). - `BACKEND_URL` must be modified to match the current URL the server is assigned to. - `FIELD_ID` must match an existing Field ID on the back-end's database ```python #Import the RPi.GPIO library import RPi.GPIO as GPIO #Import the time library import time #Import the requests library import requests #Import the JSON library import json #Initializing GPIO ports #GPIO Pin 2 is assigned as output (Red LED on circuit) #GPIO Pin 3 is assigned as output (Green LED on circuit) GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(2,GPIO.OUT) GPIO.setup(3,GPIO.OUT) GPIO.output(2,GPIO.LOW) GPIO.output(3,GPIO.LOW) #Defining the API-endpoint API_ENDPOINT = "<BACKEND_URL>/tiff/coordinates_to_et/<FIELD_ID>" #Defining Headers headers = {'Content-Type' : 'application/json'} #Sending Get request and saving response as response object r = requests.get(url = API_ENDPOINT, headers=headers) #Extracting text response textresponse = r.json() #Check if the response contains a valid ET value #If the ET value is valid, flash the Green LED according to the ET value #If the ET value is invalid, flash the Red LED once if textresponse.get('et_value') is None: print("No ET value for this field!") GPIO.output(2,GPIO.HIGH) time.sleep(3) else : Et_Value = float(textresponse.get('et_value')) Et_Value = int(Et_Value) print(Et_Value) for x in range(5): GPIO.output(3,GPIO.HIGH) time.sleep(0.5) GPIO.output(3,GPIO.LOW) time.sleep(0.5) ```<file_sep>/docs/pages/Meetings/Meeting-15thJune.md --- title: "Meeting #2 - June 15th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-15thJune.html folder: meetings --- ### Work Completed during this Week - Web Interface prototype, for the Raspberry-Pi ### Deploying a Raspberry-Pi prototype in the field I need to conduct a feasibility study before moving on to the implementation. - Enclosure for the Raspberry-Pi to protect it when deployed outdoors on agricultural fields (i.e. bad weather, physical shock...). - Find a way to power the Raspberry-Pi device efficiently in the field. ( Portable battery pack ? Solar Power ? ) - Meeting with experts from the agriculture department - What irrigation systems (i.e. pumps, actuators...) should I expect the *Smart Irrigation Controller* to interact with ? Is it possible to design a universal system which is compatible with all common irrigation systems (both hardware/software) ? ### Code Review We must agree on a time to conduct a code review for the Raspberry-Pi scripts and web interface, and also the Mobile application. ### Post-Meeting Decisions - Add a map to the web interface, so the user can see his field(s). - Add a registration process to the S.I.C. web interface - Set-up a lightweight web-server to host the web irrigation interface on the Raspberry-Pi - Re-discuss the irrigation control methods, and how we should approach a manual/automatic scheduling.<file_sep>/docs/pages/EECE-500-Deliverables/Standard-IEEE-Document-Template.md --- title: "IEEE Design Document Template" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: ieee-document-template.html folder: EECE-500-Deliverables --- **Source** : *Embedded Microprocessor Systems Design* Course, supervised by Dr. <NAME>. --- ## (1) Overview 1. **Objectives** : Why are we doing this project? What is its purpose? 2. **Process** : How will the process be developed? 3. **Roles and Responsibilities** : Who will do what? Who are the clients? 4. **Interactions with Existing Systems** : How will it fit in? 5. **Terminology** : Define terms used in the document. 6. **Security** : How will the intellectual property be managed? ## (2) Functional Description 1. **Functionality** : What will the system do precisely? 2. **Scope** : What are the project phases, and what will be delivered in each phase? 3. **Prototypes** : How will intermediate progress be demonstrated? 4. **Performance** : Define the measures and described how they will be determined. 5. **Usability** : Described the interfaces, quantitatively if possible. 6. **Safety** : Explain any safety requirements and how they will be measured. ## (3) Deliverables 1. **Reports** : How will the system be described? 2. **Audits** : How will clients evaluate progress? 3. **Outcomes** : What are the deliverables? How do we know when the project is done? <file_sep>/docs/pages/Meetings/Meeting-15thJuly.md --- title: "Meeting #5 - July 15th" keywords: last_updated: tags: sidebar: meetings_sidebar permalink: Meeting-15thJuly.html folder: Project_Meetings --- ### Work Completed during this Week - Setting up a LoRaWAN network - Researching possible LoRa transceivers to use with our Raspberry-Pi. Research available [here](selecting-lora-transceiver.html). - Researching possible LoRaWAN gateways, either stand-alone or using the Raspberry-Pi. Research available [here](selecting-lorawan-gateway.html). - Web Interface - Minor changes made to the UI for a better experience - UI now scales properly on mobile ### LoRa Transceivers and LoRaWAN modules - We need to order these modules ASAP to be able to have a working prototype before the end of summer. - Any preferred retailer we should order from ? ### Compatibility with Irrigation Systems on the Field - We want our Smart Irrigation Controller to be compatible with a selection of irrigation systems. - This should be discussed with agriculture experts of the Levantine team. ### Using QR code to add fields from the web interface to the Raspberry-Pi - Discussion around the concept. Maybe it could be added later after we are done with the basic design of the *Smart Irrigation Controller* ?<file_sep>/docs/pages/Unused-Documentation/32bit-vs-64bit.md # 32-bit CPU vs 64-bit CPU - 32-bit processors support up to <img src="https://render.githubusercontent.com/render/math?math=2^{32} "> bytes of memory, or around <img src="https://render.githubusercontent.com/render/math?math=4">GB of memory. - 64-bit processors support up to <img src="https://render.githubusercontent.com/render/math?math=2^{64} "> bytes of memory, or around <img src="https://render.githubusercontent.com/render/math?math=17*10^{9}"> GB of memory. - Raspberry-Pi OS (*a.k.a.* Raspbian OS) only has a 32-bit version. It is designed to run on all Raspberry-Pi boards, including earlier versions which had a 32-bit processors only. - 64-bit processors support both 32-bit and 64-bit OSes. - 32-bit processors support only 32-bit OSes. - 32-bit support is being slowly dropped. We may have to migrate our system to a 64-bit system, and 64-bit software.<file_sep>/docs/pages/PCB-Design/Schematic-and-PCB Layout-v01.md --- title: "Schematic and PCB Layout (V01)" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: PCB-Schematic-Layout-V01.html folder: PCB-Design --- - Complete KiCad project (including schematics, footprints and layouts) is available [here](../../zip/SmartIrrigationController-V1.zip). - For this implementation, we've used the UART interface of the Raspberry-Pi (GPIO Pins #14 and #15), two additional GPIO Pins to control elements of the circuit ( GPIO Pins #22 and #23 ), a 3v3 output power pin, and a ground pin. - There are still 24 available GPIO pins, which can be used to control additional modules. The SPI & I2C interfaces are also fully available, if we'd like to use them with other modules. # Schematic Circuit ![Schematic](../../images/PCB-Diagram.svg) # PCB Layout Front Layer : ![Front Layer PCB](../../images/PCB-Layout-Front.PNG) Back Layer : ![Back Layer PCB](../../images/PCB-Layout-Back.PNG) 3D View : ![3D View #1](../../images/PCB-3D-1.png) ![3D View #2](../../images/PCB-3D-3.png) ![3D View #3](../../images/PCB-3D-2.png)<file_sep>/docs/pages/Raspberry-Pi-Model-Information/RaspberryPI-Zero.md --- title: "Raspberry-Pi Zero" keywords: last_updated: tags: sidebar: documentation_sidebar permalink: Raspberry-Pi-Zero.html folder: Raspberry-Pi-Model-Information --- **Disclaimer** : This page gives an overview of the Raspberry-Pi Zero. Most of the information here comes from the official [Raspberry-Pi Zero Product Page](https://www.raspberrypi.org/products/raspberry-pi-zero/). ![Raspberry-Pi Zero ](https://images-na.ssl-images-amazon.com/images/I/61WK8C9pz8L._AC_SY355_.jpg) - **Processor :** - Broadcom BCM2835, ARM11-76JZF-S @ 1GHz (Single-core processor). - **RAM :** - 512MB LPDDR2 SDRAM - **Interface :** - HAT-compatible 40-pin header (*Sold separately*) - GPIO Interface is similar to the Raspberry-Pi 3 Model-B (Picture Attached for Reference) ![Raspberry-Pi 3 GPIO Interface](https://www.raspberrypi.org/documentation/usage/gpio/images/gpiozero-pinout.png) - CSI camera connector (v1.3 only) - Mini HDMI port - Micro USB OTG port - Micro USB power - Composite video and reset headers - CSI camera connector (v1.3 only) - **Required Power :** - Typical PSU current capacity is 1.2A - Typical bare-board active current consumption is 100mA - Recommended micro-USB connector : 5 V/2.5 A DC - **Miscellaneous Information :** - The Raspberry-Pi Zero will remain in production until January 2026. - Global compliance and safety certificates [here](https://www.raspberrypi.org/documentation/hardware/raspberrypi/conformity.md) - Operating temperature : 0-50°C - Raspberry-Pi Zero mechanical drawing available [here](https://www.raspberrypi.org/documentation/hardware/raspberrypi/mechanical/rpi_MECH_Zero_1p3.pdf) - Raspberry-Pi Zero schematic diagrams available [here](https://www.raspberrypi.org/documentation/hardware/raspberrypi/schematics/rpi_SCH_Zero_1p3_reduced.pdf) ## Resources - [Raspberry-Pi Zero, Official Page](https://www.raspberrypi.org/products/raspberry-pi-zero/)
bde6d63d32a46f5eb5e8d52c6ce5a545bb136a0c
[ "Markdown", "Python" ]
35
Markdown
mountainousjourney/SmartIrrigationSystem
c9a43745f0c1807948a08d007ee04fa9eede615a
0ff2a540a4ec0e4e67655349f897bd6be3d88405
refs/heads/master
<repo_name>jaismith/euler<file_sep>/problems/4/4.py import sys def checkPalindrome(test): for i in range(0,int(len(test)/2)): if test[i] != test[len(test)-1-i]: return(0) return(1) #print(checkPalindrome(str(input("provide number to test ")))) for num2 in range (999,900,-1): num1 = 999 for num1 in range (999,900,-1): if checkPalindrome(str(num1*num2)): print(num1,"*",num2,"equals palindrome",num1*num2) sys.exit() num1 += -1 print("checking",num1,"times",num2) num2 += -1 <file_sep>/problems/25/25.py # main file for euler 25 # imports from math import ceil # variables found = False prev = 1 prev2 = 1 index = 2 # main while not found: current = prev + prev2 prev2 = prev prev = current index += 1 # print('F{0} = {1}'.format(index, current)) length = len(str(current)) if length == 1000: found = True if length % 5 == 0: print('\rProgress: [', end='') for i in range(ceil((length / 1000) * 50)): print('#', end='') print(']', end='') print('\nF{0} = {1}'.format(index, current)) <file_sep>/problems/9/9.py import sys for a in range(1,999): for b in range(1,999): for c in range(1,999): # print("checking",a,",",b,",",c) if a**2 + b**2 == c**2: if a + b + c == 1000: print("found",a * b * c) sys.exit() <file_sep>/problems/22/Test.java class Test { public static void main(String[] args) { String a = "aniston"; String b = "berkeley"; System.out.println("b.compareTo(a) returns " + b.compareTo(a)); } } <file_sep>/problems/16/16.py num = 2 ** 1000 print(num) conv = str(num) sum = 0 for ch in conv: sum += int(ch) print(sum) <file_sep>/problems/7/7.py primes = [] def sift(bound): primeList = [1] * bound primeList[0] = 0 primeList[1] = 0 for i in range(4,bound,2): primeList[i] = 0 for i in range(3,bound,2): if primeList[i] == 1: for j in range(2 * i,bound,i): primeList[j] = 0 for i in range(0,bound): if primeList[i] == 1: primes.append(int(i)) sift(int(input("specify upper bound "))) print(primes[10000]) <file_sep>/problems/14/14.py import sys chain = [] def checkCollatz(num): chain.append(num) while (num != 1): if num % 2 == 0: num = num/2 else: num = (3 * num) + 1 chain.append(int(num)) count = 0 cache = 0 max = 0 percent = 0 for i in range(999999,599999,-1): if i % 1999 == 0: percent += .5 print("\r",percent,cache) chain = [] checkCollatz(i) if len(chain) > cache: max = i cache = len(chain) print(max) <file_sep>/problems/12/Main.java //main class for problem 12 class Main { public static void main(String[] args) { int current = 28; int add = 8; int max = 0; while(true) { //create Candidate object Candidate test = new Candidate(current); //check if found, if so break while loop. if(test.divisorCount() > 500) { break; } //keep track of highest found if(test.divisorCount() > max) { max = test.divisorCount(); System.out.printf("\r%d has %d factors, this is the highest known candidate.", current, max); } //calculate next triangular number current += add; add++; } System.out.printf("\n%d is the first triangular number to have over 500 divisors.\n", current); } } <file_sep>/problems/15/15.py import itertools import math #array = list(itertools.product([0,1], repeat=40)) #countGlob = 0 #for i in range(0,math.factorial(20)): # countLoc = 0 # for j in range(0,20): # if array[i][j] == 1: # print("item",i,"of attempt",i,"is 'down'") # countLoc += 1 # if countLoc == 5: # countGlob += 1 #print(countGlob) print(math.factorial(40)/(math.factorial(20)*math.factorial(20))) <file_sep>/problems/12/12.py import math import sys triList = [] for i in range(1,int(input("provide upper range "))): candidate = 0 for j in range(i,0,-1): # print("adding",j,"to candidate") candidate += j triList.append(candidate) #print(triList) for i in range(len(triList)): divisors = [] for j in range(1,math.ceil(math.sqrt(triList[i]))): # print("testing",j) if triList[i] % j == 0: divisors.append(j) divisors.append(int(triList[i] / j)) # print(triList[i],"has divisors: ",divisors) if len(divisors) >= 500: sys.exit() print("answer not found") <file_sep>/problems/3/3.py primes = [] def sift(bound): primeList = [1] * bound primeList[0] = 0 primeList[1] = 0 for i in range(4,bound,2): primeList[i] = 0 for i in range(3,bound,2): if primeList[i] == 1: for j in range(2 * i,bound,i): primeList[j] = 0 for i in range(0,bound): if primeList[i] == 1: primes.append(int(i)) sift(int(input("specify upper bound "))) #for i in primes: # print(i) factors = [] checking = 1 target = 600851475143 i = 1 while target not in primes: i = 1 checking = 1 while checking: print("checking",primes[i]) if target % primes[i] == 0: factors.append(primes[i]) print("dividing",target,"by",primes[i]) target = target / primes[i] print("target is now",target) checking = 0 i += 1 factors.append(target) for i in factors: print(i) <file_sep>/problems/22/Name.java //euler 22 name class public class Name implements Comparable<Name> { //instantiate variables String name; //constructor public Name(String name) { this.name = name.toUpperCase(); } public int getScore() { //initialize score variable int score = 0; //add up score of each letter for(char c : name.toCharArray()) { //int = char returns ascii value of char. uppercase letters in ascii start with a at 97, so by subtracting 64, we aare left with the characters place in the alphabet score += c - 64; } //return score return score; } @Override public String toString() { return name; } @Override public int compareTo(Name n) { return(name.compareTo(n.toString())); } } <file_sep>/problems/19/Main.java //euler 19 class Main { public static void main(String[] args) { int daysElapsed = 0; int sundaysElapsed = 0; //iterate through all 36525 days in 20th century //iterate years for(int year = 1901; year <= 2000; year++) { /*debugging step System.out.print("1 Jan " + year + " is"); if((daysElapsed + 2) % 7 != 0) { System.out.print(" not"); } System.out.println(" a Sunday."); */ //iterate months for(int month = 1; month <= 12; month++) { //leap year if(month == 2 && year % 4 == 0) { //check for sunday on 1st if((daysElapsed + 2) % 7 == 0) { sundaysElapsed++; } daysElapsed += 29; //normal february } else if (month == 2) { //check for sunday on 1st if((daysElapsed + 2) % 7 == 0) { sundaysElapsed++; } daysElapsed += 28; //30-day months } else if (month == 4 || month == 6 || month == 9 || month == 11) { //check for sunday on 1st if((daysElapsed + 2) % 7 == 0) { sundaysElapsed++; } daysElapsed += 30; //31-day months } else { //check for sunday on 1st if((daysElapsed + 2) % 7 == 0) { sundaysElapsed++; } daysElapsed += 31; } } } System.out.println("There were " + sundaysElapsed + " sundays on the first of the month and " + daysElapsed + " total days in the 20th century."); } } <file_sep>/problems/11/11.py import sys testArray = [] a1 = [8,2,22,97,38,15,00,40,00,75,4,5,7,78,52,12,50,77,91,8] a2 = [49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48,4,56,62,00] a3 = [81,49,31,73,55,79,14,29,93,71,40,67,53,88,30,3,49,13,36,65] a4 = [52,70,95,23,4,60,11,42,69,24,68,56,1,32,56,71,37,2,36,91] a5 = [22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80] a6 = [24,47,32,60,99,3,45,2,44,75,33,53,78,36,84,20,35,17,12,50] a7 = [32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70] a8 = [67,26,20,68,2,62,12,20,95,63,94,39,63,8,40,91,66,49,94,21] a9 = [24,55,58,5,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72] a10 = [21,36,23,9,75,00,76,44,20,45,35,14,00,61,33,97,34,31,33,95] a11 = [78,17,53,28,22,75,31,67,15,94,3,80,4,62,16,14,9,53,56,92] a12 = [16,39,5,42,96,35,31,47,55,58,88,24,00,17,54,24,36,29,85,57] a13 = [86,56,00,48,35,71,89,7,5,44,44,37,44,60,21,58,51,54,17,58] a14 = [19,80,81,68,5,94,47,69,28,73,92,13,86,52,17,77,4,89,55,40] a15 = [4,52,8,83,97,35,99,16,7,97,57,32,16,26,26,79,33,27,98,66] a16 = [88,36,68,87,57,62,20,72,3,46,33,67,46,55,12,32,63,93,53,69] a17 = [4,42,16,73,38,25,39,11,24,94,72,18,8,46,29,32,40,62,76,36] a18 = [20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74,4,36,16] a19 = [20,73,35,29,78,31,90,1,74,31,49,71,48,86,81,16,23,57,5,54] a20 = [1,70,54,71,83,51,54,69,16,92,33,48,61,43,52,1,89,19,67,48] testArray.append(a1) testArray.append(a2) testArray.append(a3) testArray.append(a4) testArray.append(a5) testArray.append(a6) testArray.append(a7) testArray.append(a8) testArray.append(a9) testArray.append(a10) testArray.append(a11) testArray.append(a12) testArray.append(a13) testArray.append(a14) testArray.append(a15) testArray.append(a16) testArray.append(a17) testArray.append(a18) testArray.append(a19) testArray.append(a20) #for i in range(0,20): # print("array",i,":\n",testArray[i] prodMax = 0 for k in range(0,20): # print("ROW",k,":") for i in range(0,17): prodCurrent = 1 for j in range(0,4): prodCurrent = prodCurrent * testArray[k][i+j] # print(testArray[k][i+j]) if prodCurrent > prodMax: prodMax = prodCurrent # print(prodCurrent,"\n") #print("horizontal max is",prodMax) for k in range(0,20): # print("COLUMN",k,":\n\n") for i in range(0,17): prodCurrent = 1 for j in range(0,4): prodCurrent = prodCurrent * testArray[i+j][k] # print(testArray[i+j][k]) if prodCurrent > prodMax: prodMax = prodCurrent # print(prodCurrent,"\n") #print("max combo found:",prodMax) for k in range(0,17): # print("ROW",k,":") for i in range(0,17): prodCurrent = 1 for j in range(0,4): prodCurrent = prodCurrent * testArray[k+j][i+j] # print(testArray[k+j][i+j]) if prodCurrent > prodMax: prodMax = prodCurrent # print(prodCurrent,"\n") for k in range(3,20): # print("ROW",k,":") for i in range(0,17): prodCurrent = 1 for j in range(0,4): prodCurrent = prodCurrent * testArray[k-j][i+j] # print(testArray[k-j][i+j]) if prodCurrent > prodMax: prodMax = prodCurrent # print(prodCurrent,"\n") print("max combo found:",prodMax) <file_sep>/problems/10/10.py primes = [] def sift(bound): primeList = [1] * bound primeList[0] = 0 primeList[1] = 0 for i in range(4,bound,2): primeList[i] = 0 for i in range(3,bound,2): if primeList[i] == 1: for j in range(2 * i,bound,i): primeList[j] = 0 for i in range(0,bound): if primeList[i] == 1: primes.append(int(i)) sift(2000000) sum = 0 for i in range(0,len(primes)): sum += primes[i] print(sum) <file_sep>/problems/6/6.py sum1 = 0 sum2 = 0 for i in range(1,101): sum1 += i sum1 = sum1**2 for i in range(1,101): sum2 += i**2 print(sum1-sum2) <file_sep>/problems/5/5.py import sys def check(test): for i in range(3,20): # print("testing",test,"for divisibility by",i) if test % i != 0: # print(j,"is not divisible by",i) return(0) return(1) for j in range(20,10000000000000000,20): # print(j) if check(j) == 1: print("smallest multiple found:",j) sys.exit() #print(check(int(input("enter test num ")))) <file_sep>/problems/24/24.py # problem 24 from copy import copy NUMBERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] permutation_count = 0 permutations = list() # recursive function def permute(pool, permutations, current=list(), depth=1): # print("pool: {0}; current: {1}; depth: {2}".format(pool, current, depth)) # base case if depth == len(NUMBERS): current.append(pool[0]) permutations.append(current) current = list() return temp_pool = copy(pool) temp_current = copy(current) # recursive case for i in range(len(temp_pool)): pool = copy(temp_pool) current = copy(temp_current) current.append(pool[i]) pool.remove(pool[i]) permute(pool, permutations, current, depth + 1) permute(copy(NUMBERS), permutations) print(permutations[999999]) print("done")
66d6d836fdb17404521c61d6fafabebb591f81b6
[ "Java", "Python" ]
18
Python
jaismith/euler
583c5ded07b0d7c5ca3b01b282876942014c8c3c
119283d070f57684f4170edf74b5326ca45b6fb2
refs/heads/master
<repo_name>csi-lnmiit/S38_Digital-Signatures<file_sep>/verify.py from ecdsa import SigningKey,VerifyingKey,BadSignatureError #Curve details- #NIST192p: siglen= 48, keygen=0.160s, sign=0.058s, verify=0.116s; def verify_sig(): vk = VerifyingKey.from_pem(open("pub_key.pem").read()) message = open("message_file1","rb").read() sig = open("signature","rb").read() print sig try: vk.verify(sig, message) print "GOOD SIGNATURE" except BadSignatureError: print "BAD SIGNATURE" verify_sig(); <file_sep>/p2p.py from Tkinter import * from ttk import * import socket import thread from ecdsa import SigningKey,VerifyingKey,BadSignatureError, NIST192p class ChatClient(Frame): def __init__(self, root): Frame.__init__(self, root) self.root = root self.initUI() self.serverSoc = None self.serverStatus = 0 self.buffsize = 1024 self.allClients = {} self.counter = 0 def initUI(self): self.root.title("Simple P2P Chat Client") ScreenSizeX = self.root.winfo_screenwidth() ScreenSizeY = self.root.winfo_screenheight() self.FrameSizeX = 800 self.FrameSizeY = 700 FramePosX = (ScreenSizeX - self.FrameSizeX)/2 FramePosY = (ScreenSizeY - self.FrameSizeY)/2 self.root.geometry("%sx%s+%s+%s" % (self.FrameSizeX,self.FrameSizeY,FramePosX,FramePosY)) self.root.resizable(width=False, height=False) padX = 10 padY = 10 parentFrame = Frame(self.root) parentFrame.grid(padx=padX, pady=padY, stick=E+W+N+S) ipGroup = Frame(parentFrame) serverLabel = Label(ipGroup, text="Set: ") self.nameVar = StringVar() self.nameVar.set("SDH") nameField = Entry(ipGroup, width=10, textvariable=self.nameVar) self.serverIPVar = StringVar() self.serverIPVar.set("127.0.0.1") serverIPField = Entry(ipGroup, width=15, textvariable=self.serverIPVar) self.serverPortVar = StringVar() self.serverPortVar.set("8090") serverPortField = Entry(ipGroup, width=5, textvariable=self.serverPortVar) serverSetButton = Button(ipGroup, text="Set", width=10, command=self.handleSetServer) addClientLabel = Label(ipGroup, text="Add friend: ") self.clientIPVar = StringVar() self.clientIPVar.set("127.0.0.1") clientIPField = Entry(ipGroup, width=15, textvariable=self.clientIPVar) self.clientPortVar = StringVar() self.clientPortVar.set("8091") clientPortField = Entry(ipGroup, width=5, textvariable=self.clientPortVar) clientSetButton = Button(ipGroup, text="Add", width=10, command=self.handleAddClient) serverLabel.grid(row=0, column=0) nameField.grid(row=0, column=1) serverIPField.grid(row=0, column=2) serverPortField.grid(row=0, column=3) serverSetButton.grid(row=0, column=4, padx=5) addClientLabel.grid(row=0, column=5) clientIPField.grid(row=0, column=6) clientPortField.grid(row=0, column=7) clientSetButton.grid(row=0, column=8, padx=5) readChatGroup = Frame(parentFrame) self.receivedChats = Text(readChatGroup, bg="white", width=60, height=30, state=DISABLED) self.friends = Listbox(readChatGroup, bg="white", width=30, height=30) self.receivedChats.grid(row=0, column=0, sticky=W+N+S, padx = (0,10)) self.friends.grid(row=0, column=1, sticky=E+N+S) writeChatGroup = Frame(parentFrame) self.chatVar = StringVar() self.chatField = Entry(writeChatGroup, width=80, textvariable=self.chatVar) sendChatButton = Button(writeChatGroup, text="Send", width=10, command=self.handleSendChat) self.chatField.grid(row=0, column=0, sticky=W) sendChatButton.grid(row=0, column=1, padx=5) self.statusLabel = Label(parentFrame) bottomLabel = Label(parentFrame, text="P2P Chatting Application which uses message verification using ECDSA") ipGroup.grid(row=0, column=0) readChatGroup.grid(row=1, column=0) writeChatGroup.grid(row=2, column=0, pady=10) self.statusLabel.grid(row=3, column=0) bottomLabel.grid(row=4, column=0, pady=10) def handleSetServer(self): if self.serverSoc != None: self.serverSoc.close() self.serverSoc = None self.serverStatus = 0 serveraddr = (self.serverIPVar.get().replace(' ',''), int(self.serverPortVar.get().replace(' ',''))) try: self.serverSoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #print "hi" self.serverSoc.bind(serveraddr) self.serverSoc.listen(5) self.setStatus("Server listening on %s:%s" % serveraddr) thread.start_new_thread(self.listenClients,()) self.serverStatus = 1 #print "1" self.genKeys() #print "2" self.name = self.nameVar.get().replace(' ','') if self.name == '': self.name = "%s:%s" % serveraddr except: self.setStatus("Error setting up server") def listenClients(self): while 1: clientsoc, clientaddr = self.serverSoc.accept() self.setStatus("Client connected from %s:%s" % clientaddr) self.addClient(clientsoc, clientaddr) clientsoc.send(self.pubKey.to_string()) thread.start_new_thread(self.handleClientMessages, (clientsoc, clientaddr)) self.serverSoc.close() def handleAddClient(self): if self.serverStatus == 0: self.setStatus("Set server address first") return clientaddr = (self.clientIPVar.get().replace(' ',''), int(self.clientPortVar.get().replace(' ',''))) try: clientsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsoc.connect(clientaddr) self.setStatus("Connected to client on %s:%s" % clientaddr) self.addClient(clientsoc, clientaddr) clientsoc.send(self.pubKey.to_string()) thread.start_new_thread(self.handleClientMessages, (clientsoc, clientaddr)) except: self.setStatus("Error connecting to client") def handleClientMessages(self, clientsoc, clientaddr): flag=0 while (flag==0): data=clientsoc.recv(48) if (len(data)==48): self.veriKey= VerifyingKey.from_string(data,curve=NIST192p) print "len of verikey:" + str(len(self.veriKey.to_string())) flag=1 while True: try: data = clientsoc.recv(self.buffsize) if not data: break sign= data[0:48] msg= data[48:] try: self.veriKey.verify(sign,msg) self.addChat("%s:%s" % clientaddr, msg) except: self.setStatus("Signatures not verified. Exit the chat") except: break self.removeClient(clientsoc, clientaddr) clientsoc.close() self.setStatus("Client disconnected from %s:%s" % clientaddr) def handleSendChat(self): if self.serverStatus == 0: self.setStatus("Set server address first") return msg = self.chatVar.get() data=msg if msg == '': return msg = self.priKey.sign(msg)+ msg self.addChat("me", data) for client in self.allClients.keys(): client.send(msg) def addChat(self, client, msg): self.receivedChats.config(state=NORMAL) self.receivedChats.insert("end",client+": "+msg+"\n") self.receivedChats.config(state=DISABLED) def addClient(self, clientsoc, clientaddr): self.allClients[clientsoc]=self.counter self.counter += 1 self.friends.insert(self.counter,"%s:%s" % clientaddr) def removeClient(self, clientsoc, clientaddr): print self.allClients self.friends.delete(self.allClients[clientsoc]) del self.allClients[clientsoc] print self.allClients def setStatus(self, msg): self.statusLabel.config(text=msg) print msg def genKeys(self): #print "11" self.priKey = SigningKey.generate(curve=NIST192p) #print "22" self.pubKey = self.priKey.get_verifying_key() #print "33" #open("priv_key.pem",'w').write(priv_key.to_pem()) #open("pub_key.pem",'w').write(pub_key.to_pem()) def main(): root = Tk() app = ChatClient(root) root.mainloop() if __name__ == '__main__': main() <file_sep>/sign_generation.py from ecdsa import SigningKey,VerifyingKey,BadSignatureError, NIST192p import ecdsa import sys #Curve details- #NIST192p: siglen= 48, keygen=0.160s, sign=0.058s, verify=0.116s; def generate_keys(): priv_key = SigningKey.generate(curve=NIST192p) pub_key = priv_key.get_verifying_key() open("priv_key.pem",'w').write(priv_key.to_pem()) open("pub_key.pem",'w').write(pub_key.to_pem()) #print type(priv_key) #print type(pub_key) print sys.getsizeof(pub_key.to_string()) print len(pub_key.to_string()) print sys.getsizeof(VerifyingKey.from_string(pub_key.to_string(),curve=NIST192p)) #print sys.getsizeof(pub_key.to_string()) def generate_sign(): priv_key = SigningKey.from_pem(open("priv_key.pem").read()) print "privkey" + str(sys.getsizeof(priv_key)) message = open("message_file","rb").read() sign = priv_key.sign(message); print "sign1" + str(sys.getsizeof(sign)) print len(sign) open("signature","wb").write(sign); print "sign2" + str(sys.getsizeof(sign)) generate_keys(); generate_sign();
6a74b6f01e34d51e5455ab9a11e6ec9b37b9a1c6
[ "Python" ]
3
Python
csi-lnmiit/S38_Digital-Signatures
d001dc24ee3ef2cae547c64c3714f1cd3b11a93b
74f5823c3523e6e63bb091383ceec8fb98f142c1
refs/heads/master
<file_sep># ~BenBarber's Dot Files These are my config files for setting up a MacOS/Linux system for the way I like to work. As I work across multiple machines I needed a way to make my development experience consistent and reproducible across them all. By managing my configuration through this git repository I can simply pull in any changes and run the installer to bring everything up to date. The dotfiles are managed with [YADM](https://thelocehiliosan.github.io/yadm/) which is a wrapper around the git commands you already know and use. ## Installation To get started simply run the bootstrap script with with a curl command. ``` curl -L https://raw.githubusercontent.com/BenBarber/dotfiles/master/bootstrap | bash ``` ## License Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <file_sep>#!/bin/bash system_type=$(uname -s) # Install MacOS requirements if [ "$system_type" = "Darwin" ]; then # Install Homebrew if it's missing if ! command -v brew >/dev/null 2>&1; then echo "Installing Homebrew..." /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" fi # Install YADM if it's missing if ! command -v yadm >/dev/null 2>&1; then echo "Installing YADM..." brew install git yadm fi fi # Install dotfiles echo "Installing dotfiles..." yadm clone <EMAIL>:BenBarber/dotfiles.git yadm submodule update --init --recursive # Install MacOs specifics if [ "$system_type" = "Darwin" ]; then # Install Homebrew formulas from .Brewfile if [ -f "$HOME/.Brewfile" ]; then echo "Installing Homebrew formulas..." brew bundle --global fi # Install Powerline Fonts echo "Installing Powerline Fonts..." git clone https://github.com/powerline/fonts.git --depth=1 cd fonts && ./install.sh && cd .. && rm -rf fonts # Set iTerm2 preferences if [ -d "$HOME/.iterm2" ]; then echo "Setting iTerm preferences..." defaults write com.googlecode.iterm2 PrefsCustomFolder "$HOME/.iterm2" fi fi
dc9b1f0bb1631b7653799a9a1548e4461ba030aa
[ "Markdown", "Shell" ]
2
Markdown
ergo-dubito/dotfiles-9
e457b5a5c0a5b2baad9982ef86472b7f15d90620
c84e98e309332cf4854cfe4210236ce7ec8c6ad7
refs/heads/master
<file_sep>import { AnyAction } from "redux"; import { ICompanyAddress } from "../../actions/companyAddresses/companyAddressesActions"; import * as companyAddresses from "../../types/companyAddresses/companyAddressesTypes"; type TState = { rawData: ICompanyAddress[] | null; }; const initialState: TState = { rawData: null, }; const companyAddressesReducer = (state = initialState, { type, payload }: AnyAction) => { switch (type) { case companyAddresses.SET_COMPANY_ADDRESSES: return { ...state, rawData: payload, }; default: return state; } }; export { companyAddressesReducer }; <file_sep>import { AnyAction, Dispatch } from "redux"; import { httpService } from "../../../services/httpService"; import * as companyAddresses from "../../types/companyAddresses/companyAddressesTypes"; interface ICompanyAddress { id: string; city: string; country: string; street: string; state: string; companyId: string; } const setCompanyAddresses = (payload: ICompanyAddress[]) => ({ type: companyAddresses.SET_COMPANY_ADDRESSES, payload, }); const fetchCompanyAddresses = () => { return async (dispatch: Dispatch<AnyAction>) => { const response = await httpService("get", "company-addresses"); dispatch(setCompanyAddresses(response)); }; }; export type { ICompanyAddress }; export { fetchCompanyAddresses, setCompanyAddresses }; <file_sep>import { TEndPoint, TRequest } from "../misc/misc"; const headers = { "Content-Type": "application/json", Accept: "application/json", }; const httpService = async (requestType: TRequest, endPoint: TEndPoint): Promise<any> => { if (requestType === "get") { const response = await fetch(`data/${endPoint}.json`, { method: "get", headers, }); return response.json(); } }; export { httpService }; <file_sep>import { AnyAction, Dispatch } from "redux"; import { httpService } from "../../../services/httpService"; import * as companies from "../../types/companies/companiesTypes"; interface ICompany { id: string; name: string; business: string; slogan: string; } const setCompanies = (payload: ICompany[]) => ({ type: companies.SET_COMPANIES, payload, }); const fetchCompanies = () => { return async (dispatch: Dispatch<AnyAction>) => { const response = await httpService("get", "companies"); dispatch(setCompanies(response)); }; }; export type { ICompany }; export { fetchCompanies, setCompanies }; <file_sep>const SET_COMPANY_ADDRESSES = "set-addresses"; export { SET_COMPANY_ADDRESSES }; <file_sep># Tick42's JavaScript Pre-Interview Task ## DON'T PANIC! Hello there and welcome to Tick42's pre-interview task assignment. Before we start, we want to thank you for your interest in Tick42 and for making the time to work on this task as part of your adventure to become one of us! In the `data` folder you will find four JSON files: ``` - companies.json - company-addresses.json - employees.json - projects.json ``` You will use them to build a small app. ### App requirements - Use the company and employees data to build a tree view like navigation with the following structure: ``` Company name Employee job area Employee name ``` - When the user clicks on a company, the app should display the company's address and the company's projects (use `projects.json`). It should be possible to visualize the information about each project as well as to manage the projects: edit project details (changing the project name) and assigning & removing employees from a project. If you feel that's too easy, you can add the ability to add and remove projects - When the user clicks on an employee's name you will need to show the employee's details, and projects they're part of. - Clicking on Employee's job area should only display how many employees work in that area, and the number of projects they participate in. ### Tech requirements - The app should be developed using whichever framework you're most comfortable with - React or Angular (but not Angular 1.x). You can start from scratch, from a boilerplate project or use a scaffolding CLI. - You can use ES5+ or TypeScript and any supporting libraries (e.g. Lodash, Ramda, RxJS, etc.) you need. - The code needs to demonstrate state management within the app as well as managing asynchronous requests. - In terms of serving the static JSON files upon app requests, it's up to you whether to create a dev server or use an existing package. - The app's aesthetics are up to you - you can use Bootstrap, Material or custom CSS. - We should be able to run your solution by simply unzipping it and running a single command on the command line. ### Getting started Download the attached .zip file with the JSON files and start your journey. Don't forget to save your work before sending us your masterpiece. Good luck and happy hacking! <file_sep>import { AnyAction, Dispatch } from "redux"; import { httpService } from "../../../services/httpService"; import * as projects from "../../types/projects/projectsTypes"; interface IProject { id: string; name: string; department: string; employeesId: string[]; companyId: string; } interface IUpdateProject { id: string; name: string; } interface IUpdateProjectEmployees { employeesId: string[]; projectId: string; } interface INewEmployee { projectId: string; newEmployeeId: string; } interface IRemoveProjects { companyId: string; unremovedCompanyProjects: IProject[]; } const setProjects = (payload: IProject[]) => ({ type: projects.SET_PROJECTS, payload, }); const updateProjectname = (payload: IUpdateProject) => ({ type: projects.UPDATE_PROJECT_NAME, payload, }); const updateProjectEmployees = (payload: IUpdateProjectEmployees) => ({ type: projects.UPDATE_PROJECT_EMPLOYEES, payload, }); const removeProjects = (payload: IRemoveProjects) => ({ type: projects.REMOVE_PROJECTS, payload, }); const addNewProject = (payload: IProject) => ({ type: projects.ADD_NEW_PROJECT, payload, }); export const assignNewEmployee = (payload: INewEmployee) => ({ type: projects.ASSIGN_NEW_EMPLOYEE, payload, }); const fetchProjects = () => { return async (dispatch: Dispatch<AnyAction>) => { const response = await httpService("get", "projects"); dispatch(setProjects(response)); }; }; export type { IProject, IUpdateProject, IRemoveProjects, IUpdateProjectEmployees, INewEmployee }; export { fetchProjects, setProjects, updateProjectname, updateProjectEmployees, removeProjects, addNewProject }; <file_sep>const SET_PROJECTS = "set-projects"; const UPDATE_PROJECT_NAME = "update-project-name"; const UPDATE_PROJECT_EMPLOYEES = "update-project-employees"; const ASSIGN_NEW_EMPLOYEE = "assign-new-employee"; const REMOVE_PROJECTS = "update-projects"; const ADD_NEW_PROJECT = "add-new-project"; export { SET_PROJECTS, UPDATE_PROJECT_NAME, UPDATE_PROJECT_EMPLOYEES, ASSIGN_NEW_EMPLOYEE, REMOVE_PROJECTS, ADD_NEW_PROJECT }; <file_sep>import { ChangeEvent } from "react"; import { ICompany } from "../store/actions/companies/companiesActions"; import { ICompanyAddress } from "../store/actions/companyAddresses/companyAddressesActions"; import { IEmployee } from "../store/actions/employees/employeesActions"; import { IProject } from "../store/actions/projects/projectsActions"; type TRequest = "get" | "post" | "put" | "patch" | "delete"; type TEndPoint = "companies" | "company-addresses" | "employees" | "projects"; type TVariant = "inherit" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "subtitle1" | "subtitle2" | "body1" | "body2" | "caption" | "button" | "overline" | "srOnly" | undefined; type TButton = "button" | "submit" | "reset"; type TOption = { type: (IEmployee | ICompany | ICompanyAddress | IProject)[]; }; type TOnChangeEvent = ChangeEvent<{ name?: string | undefined; value: unknown }>; export type { TRequest, TEndPoint, TVariant, TButton, TOption, TOnChangeEvent }; <file_sep>import { combineReducers } from "redux"; import { persistReducer } from "redux-persist"; import storage from "redux-persist/lib/storage"; import { companiesReducer } from "./companiesReducer/companiesReducer"; import { employeesReducer } from "./employeesReducer/employeesReducer"; import { projectsReducer } from "./projectsReducer/projectsReducer"; import { companyAddressesReducer } from "./companyAddressesReducer/companyAddressesReducer"; const persistConfig = { key: "root", storage, whitelist: ["companiesReducer", "employeesReducer", "projectsReducer", "companyAddressesReducer"], }; const rootReducer = combineReducers({ companiesReducer, employeesReducer, projectsReducer, companyAddressesReducer, }); export type TRootState = ReturnType<typeof rootReducer>; export default persistReducer(persistConfig, rootReducer); <file_sep>import { AnyAction, Dispatch } from "redux"; import { httpService } from "../../../services/httpService"; import * as employees from "../../types/employees/employeesTypes"; interface IEmployee { id: string; firstName: string; lastName: string; dateOfBirht: string; companyId: string; jobTitle: string; jobArea: string; jobType: string; } const setEmployees = (payload: IEmployee[]) => ({ type: employees.SET_EMPLOYEES, payload, }); const fetchEmployees = () => { return async (dispatch: Dispatch<AnyAction>) => { const response = await httpService("get", "employees"); dispatch(setEmployees(response)); }; }; export type { IEmployee }; export { fetchEmployees, setEmployees }; <file_sep>import { AnyAction } from "redux"; import { ICompany } from "../../actions/companies/companiesActions"; import * as companies from "../../types/companies/companiesTypes"; type TState = { rawData: ICompany[] | null; }; const initialState: TState = { rawData: null, }; const companiesReducer = (state = initialState, { type, payload }: AnyAction) => { switch (type) { case companies.SET_COMPANIES: return { ...state, rawData: payload, }; default: return state; } }; export { companiesReducer }; <file_sep>const SET_EMPLOYEES = "set-employees"; export { SET_EMPLOYEES }; <file_sep>import { AnyAction } from "redux"; import { INewEmployee, IProject, IRemoveProjects, IUpdateProject, IUpdateProjectEmployees } from "../../actions/projects/projectsActions"; import * as projects from "../../types/projects/projectsTypes"; type TState = { rawData: IProject[] | null; }; const initialState: TState = { rawData: null, }; const updateProjectName = (projects: IProject[], payload: IUpdateProject) => { const foundProject = projects.find((p) => p.id === payload.id); const otherProjects = projects.filter((p) => p.id !== payload.id); const hasThatName = otherProjects.find((p) => p.name === payload.name); if (hasThatName) { return [...otherProjects, { ...foundProject }]; } const hasDifferentName = foundProject && hasThatName && payload.name === foundProject.name ? foundProject.name : payload.name; return [...otherProjects, { ...foundProject, name: hasDifferentName }]; }; const updateProjectEmployees = (projects: IProject[], payload: IUpdateProjectEmployees) => { const foundProject = projects.find((p) => p.id === payload.projectId); const otherProjects = projects.filter((p) => p.id !== payload.projectId); return [...otherProjects, { ...foundProject, employeesId: payload.employeesId }]; }; const assignNewEmployeeWithinTheProject = (projects: IProject[], payload: INewEmployee) => { const foundProject = projects.find((p) => p.id === payload.projectId); const otherProjects = projects.filter((p) => p.id !== payload.projectId); return foundProject ? [...otherProjects, { ...foundProject, employeesId: [...foundProject.employeesId, payload.newEmployeeId] }] : []; }; const removeProjects = (projects: IProject[], payload: IRemoveProjects) => { const filteredProjects = projects.filter((p) => p.companyId !== payload.companyId); return [...filteredProjects, ...payload.unremovedCompanyProjects]; }; const addNewProject = (projects: IProject[], payload: IProject) => { const hasProject = projects.find((p: IProject) => p.id === payload.id || p.name === payload.name); debugger; if (hasProject) { return projects; } return [...projects, payload]; }; const projectsReducer = (state = initialState, { type, payload }: AnyAction) => { switch (type) { case projects.SET_PROJECTS: return { ...state, rawData: payload, }; case projects.UPDATE_PROJECT_NAME: return { ...state, rawData: updateProjectName(state.rawData ? state.rawData : [], payload), }; case projects.UPDATE_PROJECT_EMPLOYEES: return { ...state, rawData: updateProjectEmployees(state.rawData ? state.rawData : [], payload), }; case projects.ASSIGN_NEW_EMPLOYEE: return { ...state, rawData: assignNewEmployeeWithinTheProject(state.rawData ? state.rawData : [], payload), }; case projects.REMOVE_PROJECTS: return { ...state, rawData: removeProjects(state.rawData ? state.rawData : [], payload), }; case projects.ADD_NEW_PROJECT: return { ...state, rawData: addNewProject(state.rawData ? state.rawData : [], payload), }; default: return state; } }; export { projectsReducer }; <file_sep>import { createStore, applyMiddleware } from "redux"; import { composeWithDevTools } from "redux-devtools-extension"; import thunk from "redux-thunk"; import persistReducer from "./reducers"; import { persistStore } from "redux-persist"; export const store = createStore(persistReducer, composeWithDevTools(applyMiddleware(thunk))); export const persistor = persistStore(store); <file_sep>const SET_COMPANIES = "set-companies"; export { SET_COMPANIES }; <file_sep>import { AnyAction } from "redux"; import { IEmployee } from "../../actions/employees/employeesActions"; import * as employees from "../../types/employees/employeesTypes"; type TState = { rawData: IEmployee[] | null; }; const initialState: TState = { rawData: null, }; const employeesReducer = (state = initialState, { type, payload }: AnyAction) => { switch (type) { case employees.SET_EMPLOYEES: return { ...state, rawData: payload, }; default: return state; } }; export { employeesReducer };
eddc17ed8352a3ca92214a08602c1d1b6c047dd3
[ "Markdown", "TypeScript" ]
17
TypeScript
simeon12396/tick42-app
4344a16dcf9307c0bfb72c41824ff25adad929fc
41f385a0df335c32ff9a12f17938519621f86bd7
refs/heads/master
<repo_name>girisharma/PresalesBOM<file_sep>/features/support/hooks.rb Before("@user_with_two_projects") do @user = Factory.build(:user, :id => 4691) # Using actual project models instead of factories due to SQL query involved in @user.projects methos 2.times do Project.create!(:user_id => @user.id, :name => Factory.next(:project_name)) end end Before("@user_with_one_project") do @user = Factory.build(:user, :id => 4691) # Using actual project models instead of factories due to SQL query involved in @user.projects methos Project.create!(:user_id => @user.id, :name => Factory.next(:project_name), :description => 'a DWDM implementation') Project.first.update_attributes!(:user_id => @user.id) end Before("@user_with_no_projects") do @user = Factory.build(:user) end Before("@fix_project_ownership") do end<file_sep>/spec/models/.svn/text-base/opportunity_spec.rb.svn-base require 'spec_helper' describe Opportunity, 'associations' do it 'should belong to projects' do Opportunity.should belong_to(:project) end it 'should have many sites' do Opportunity.should have_many(:sites) end end describe Opportunity, 'composed_of' do it 'should have a composed of attribute named "cost"' do opportunity = Factory.build(:opportunity) opportunity.should respond_to(:cost) end end<file_sep>/spec/controllers/.svn/text-base/dashboards_controller_spec.rb.svn-base require 'spec_helper' describe DashboardsController do #Delete this example and add some real ones it "should use DashboardController" do controller.should be_an_instance_of(DashboardsController) end end <file_sep>/lib/extensions.rb # MN: 7.20.2010 - Placing contents of rspec-on-rails-matchers in extensions for now until rspec-on-rails-matchers # Gem is fully functional module Spec module Rails module Matchers # Associations def belong_to(association) return simple_matcher("model to belong to #{association}") do |model| model = model.class if model.is_a? ActiveRecord::Base model.reflect_on_all_associations(:belongs_to).find { |a| a.name == association } end end def have_many(association) return simple_matcher("model to have many #{association}") do |model| model = model.class if model.is_a? ActiveRecord::Base model.reflect_on_all_associations(:has_many).find { |a| a.name == association } end end def have_one(association) return simple_matcher("model to have one #{association}") do |model| model = model.class if model.is_a? ActiveRecord::Base model.reflect_on_all_associations(:has_one).find { |a| a.name == association } end end def have_and_belong_to_many(association) return simple_matcher("model to have and belong to many #{association}") do |model| model = model.class if model.is_a? ActiveRecord::Base model.reflect_on_all_associations(:has_and_belongs_to_many).find { |a| a.name == association } end end # Validations def validate_presence_of(attribute) return simple_matcher("model to validate the presence of #{attribute}") do |model| model.send("#{attribute}=", nil) !model.valid? && model.errors.invalid?(attribute) end end def validate_length_of(attribute, options) if options.has_key? :within min = options[:within].first max = options[:within].last elsif options.has_key? :is min = options[:is] max = min elsif options.has_key? :minimum min = options[:minimum] elsif options.has_key? :maximum max = options[:maximum] end return simple_matcher("model to validate the length of #{attribute} within #{min || 0} and #{max || 'Infinity'}") do |model| invalid = false if !min.nil? && min >= 1 model.send("#{attribute}=", 'a' * (min - 1)) invalid = !model.valid? && model.errors.invalid?(attribute) end if !max.nil? model.send("#{attribute}=", 'a' * (max + 1)) invalid ||= !model.valid? && model.errors.invalid?(attribute) end invalid end end def validate_uniqueness_of(attribute) return simple_matcher("model to validate the uniqueness of #{attribute}") do |model| model.class.stub!(:find).and_return(true) !model.valid? && model.errors.invalid?(attribute) end end def validate_confirmation_of(attribute) return simple_matcher("model to validate the confirmation of #{attribute}") do |model| model.send("#{attribute}_confirmation=", 'asdf') !model.valid? && model.errors.invalid?(attribute) end end def validate_date_of(attribute) return simple_matcher("model to validate the date of #{attribute}") do |model| model.send("#{attribute}=",'invalid_date') !model.valid? && model.errors.invalid?(attribute) end end def validate_datetime_of(attribute) return simple_matcher("model to validate the datetime of #{attribute}") do |model| model.send("#{attribute}=",'invalid_date') !model.valid? && model.errors.invalid?(attribute) end end end end end class Money attr_accessor :id # HACK for use with factory_girl def save true end alias_method :save!, :save def initialize(cents = 0, currency = Money.default_currency, bank = Money.default_bank) @cents = cents.round if currency.is_a?(Hash) # Earlier versions of Money wrongly documented the constructor as being able # to accept something like this: # # Money.new(50, :currency => "USD") # # We retain compatibility here. @currency = Currency.wrap(currency[:currency] || Money.default_currency) else @currency = Currency.wrap(currency) end @bank = bank end end <file_sep>/app/controllers/dashboards_controller.rb class DashboardsController < ApplicationController def index @user = session[:current_user] end end <file_sep>/app/controllers/projects_controller.rb class ProjectsController < ApplicationController def index @user = session[:current_user] end def show @user = session[:current_user] @project = Project.find(params[:id]) if @project.user_id != @user.id flash[:error] = 'You do not have permission to view this project' redirect_to :controller => 'user', :action => 'error' end end def new @user = session[:current_user] @project = Project.new(:user_id => @user) end end <file_sep>/spec/views/dashboards/index.html.erb_spec.rb require File.dirname(__FILE__) + '/../../spec_helper' describe '/dashboards/index.html.erb' do include DashboardsHelper before :each do #assigns[:user] = user_with_two_projects end it 'should render the dashboard page with two projects' do pending('resolving cucumber user service') render '/dashboards/index.html.erb' response.should have_tag('li', 2) end end<file_sep>/spec/models/.svn/text-base/site_spec.rb.svn-base require 'spec_helper' describe Site, 'associations' do it 'should belong to a project' do Site.should belong_to(:projects) end end describe Site, 'validations' do before :each do @site = Factory.build(:site) end it 'should validate the presence of the site name' do @site.should validate_presence_of(:name) end it 'should validate the presence of a description' do @site.should validate_presence_of(:description) end end<file_sep>/app/models/.svn/text-base/project.rb.svn-base class Project < ActiveRecord::Base belongs_to :user has_many :sites has_many :opportunities composed_of :cost, :class_name => "Money", :mapping => [%w(cents cents), %w(currency currency_as_string)], :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) } end <file_sep>/config/initializers/.svn/text-base/library_extensions.rb.svn-base # Used to allow extensions/monkeypatches to application require 'extensions'<file_sep>/app/models/.svn/text-base/opportunity.rb.svn-base class Opportunity < ActiveRecord::Base # Relationships belongs_to :project has_many :sites composed_of :cost, :class_name => "Money", :mapping => [%w(cents cents), %w(currency currency_as_string)], :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) } end <file_sep>/features/step_definitions/.svn/text-base/project_steps.rb.svn-base Then /^I should see a list of my projects$/ do response.should have_tag('li', 2) end <file_sep>/spec/controllers/.svn/text-base/projects_controller_spec.rb.svn-base require 'spec_helper' describe ProjectsController, '#index' do before :each do @user = user_with_two_projects session[:current_user] = @user get :index end context 'on success' do it 'should render the projects index template' do response.should render_template('projects/index') end it 'should return the current user' do assigns[:user].should == @user end end end describe ProjectsController, "#show" do before :each do @user = user_with_one_project session[:current_user] = @user end context 'on success' do before :each do get :show, :id => @user.projects.first.id end it 'should render the project show template' do response.should render_template('projects/show') end it 'should assign the project variable' do assigns[:project].should == @user.projects.first end end context 'on failure' do it 'should redirect to the user error page' do non_matching_project = Factory.build(:project) Project.stub!(:find).and_return(non_matching_project) get :show, :id => 5000 response.should redirect_to('/user/error') end end end describe ProjectsController, "#new" do context 'on success' do before :each do get :new end it 'should render the new project template' do response.should render_template('projects/new') end it 'should create a new project variable' do assigns[:project].should_not be_nil assigns[:project].new_record?.should be_true end end end<file_sep>/Gemfile source :rubygems source :rubyforge source :gemcutter gem 'GeoRuby', :require => 'geo_ruby' gem 'activerecord-oracle_enhanced-adapter' gem 'money' gem 'ruby-oci8' gem 'rails', '2.3.8' gem 'sqlite3-ruby' group :cucumber do gem 'autotest' gem 'autotest-rails' gem 'cucumber' gem 'cucumber-rails' gem 'database_cleaner' gem 'factory_girl' gem 'rspec' gem 'rspec-rails' gem 'ruby-debug' gem 'webrat' gem 'ZenTest' end group :test do gem 'autotest' gem 'autotest-rails' gem 'webrat' gem 'cucumber' gem 'cucumber-rails' gem 'database_cleaner' gem 'factory_girl' gem 'rspec' gem 'rspec-rails' gem 'ruby-debug' gem 'ZenTest' end group :development do gem 'factory_girl' gem 'ruby-debug' gem 'thin' end
db90e345e6de276ae377a54183d127ec7e413e40
[ "Ruby" ]
14
Ruby
girisharma/PresalesBOM
471a22cbe0900039dbeffb4d1e5a7d1cbb0887cd
c04924feeaf7c01782cc1934ee8144a2c7bc5c69
refs/heads/master
<file_sep>from django.contrib import admin from hello.models import Question # Register your models here. admin.site.register(Question)
eaefbabe63b488fcc9d043463253712673d92943
[ "Python" ]
1
Python
imShivamPatel/django
ecb38ea8f7fd7eb1005df41e0642b8837b091f62
0c41e4ba18d9ac7de6b773a504f1ca8eee74dece
refs/heads/master
<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignment6 { class Program { List<Employee> employeeList; List<Salary> salaryList; public Program() { employeeList = new List<Employee>() { new Employee(){ EmployeeID = 1, EmployeeFirstName = "Rajiv", EmployeeLastName = "Desai", Age = 49}, new Employee(){ EmployeeID = 2, EmployeeFirstName = "Karan", EmployeeLastName = "Patel", Age = 32}, new Employee(){ EmployeeID = 3, EmployeeFirstName = "Sujit", EmployeeLastName = "Dixit", Age = 28}, new Employee(){ EmployeeID = 4, EmployeeFirstName = "Mahendra", EmployeeLastName = "Suri", Age = 26}, new Employee(){ EmployeeID = 5, EmployeeFirstName = "Divya", EmployeeLastName = "Das", Age = 20}, new Employee(){ EmployeeID = 6, EmployeeFirstName = "Ridhi", EmployeeLastName = "Shah", Age = 60}, new Employee(){ EmployeeID = 7, EmployeeFirstName = "Dimple", EmployeeLastName = "Bhatt", Age = 53} }; salaryList = new List<Salary>() { new Salary(){ EmployeeID = 1, Amount = 1000, Type = SalaryType.Monthly}, new Salary(){ EmployeeID = 1, Amount = 500, Type = SalaryType.Performance}, new Salary(){ EmployeeID = 1, Amount = 100, Type = SalaryType.Bonus}, new Salary(){ EmployeeID = 2, Amount = 3000, Type = SalaryType.Monthly}, new Salary(){ EmployeeID = 2, Amount = 1000, Type = SalaryType.Bonus}, new Salary(){ EmployeeID = 3, Amount = 1500, Type = SalaryType.Monthly}, new Salary(){ EmployeeID = 4, Amount = 2100, Type = SalaryType.Monthly}, new Salary(){ EmployeeID = 5, Amount = 2800, Type = SalaryType.Monthly}, new Salary(){ EmployeeID = 5, Amount = 600, Type = SalaryType.Performance}, new Salary(){ EmployeeID = 5, Amount = 500, Type = SalaryType.Bonus}, new Salary(){ EmployeeID = 6, Amount = 3000, Type = SalaryType.Monthly}, new Salary(){ EmployeeID = 6, Amount = 400, Type = SalaryType.Performance}, new Salary(){ EmployeeID = 7, Amount = 4700, Type = SalaryType.Monthly} }; } public static void Main() { Program program = new Program(); program.Task1(); program.Task2(); program.Task3(); } public void Task1() { var task1 = from emp in employeeList join sal in salaryList on emp.EmployeeID equals sal.EmployeeID select new { emp.EmployeeFirstName, sal.Amount } into emp group emp by emp.EmployeeFirstName into emp select new { employeefirstname = emp.Key, totalamount = emp.Sum(y => y.Amount) } into emp orderby emp.totalamount select new { emp.employeefirstname, emp.totalamount }; foreach(var item in task1) { Console.WriteLine(item); } } public void Task2() { var task2 = (from emp in employeeList join sal in salaryList on emp.EmployeeID equals sal.EmployeeID //join karya select new { emp.EmployeeFirstName, emp.EmployeeID, emp.EmployeeLastName, emp.Age, sal.Amount, sal.Type } into emp //select kari ne emp onject ma save karya where emp.Type == SalaryType.Monthly // filter karya jaya type=salarytype.monthly hoy orderby emp.Age descending //age ne descending ma sort karya group emp by emp.EmployeeID into emp //employeeid thi group by karyu select new { EmployeeFirstName = emp.Select(e => e.EmployeeFirstName).ToArray(), EmployeeID = emp.Key, EmployeeLastName = emp.Select(e => e.EmployeeLastName).ToArray(), Age = emp.Select(e => e.Age).ToArray(), Amount = emp.Select(e => e.Amount).ToArray() }).Skip(1).Take(1); Console.WriteLine("\n"); foreach (var item2 in task2) { Console.Write("ID is: "+item2.EmployeeID); foreach (var m in item2.EmployeeFirstName) { Console.Write(", employee first name is: " + m); } foreach (var n in item2.EmployeeLastName) { Console.Write(", employeelastname is: " + n); } foreach (var x in item2.Age) { Console.Write(", employee age is: " + x); } foreach (var y in item2.Amount) { Console.Write(", employee monthly salary is: " + y); } } } public void Task3() { var task3 = from emp in employeeList join sal in salaryList on emp.EmployeeID equals sal.EmployeeID select new { emp.EmployeeFirstName, emp.Age,sal.Amount } into emp where emp.Age > 30 group emp by emp.EmployeeFirstName into emp select new { employeefirstname = emp.Key,totalamount = emp.Average(y => y.Amount) } into emp orderby emp.totalamount select new { emp.employeefirstname, emp.totalamount }; Console.WriteLine("\n"); foreach (var item in task3) { Console.WriteLine(item); } } } public enum SalaryType { Monthly, Performance, Bonus } }
bf84e3ec0bd2a86dc3b94fa749c8d4079d8b4a92
[ "C#" ]
1
C#
pmayur1998/csharp_assign6
e2bee2d4a1467c7faff295af57cfc1ed475949be
d4b5dc533992671fd3883c05daae2b7b18f207d6
refs/heads/master
<file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface ITransactionRepository: IRepository<Transaction> { } } <file_sep>using System.Collections.Generic; using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface ITeamRepository : IRepository<Team> { void Update(Team team); IEnumerable<Team> GetAll(); void RemoveEmployee(string EmployeeID, string TeamID); void AddEmployee(string EmployeeID, string TeamID); Team GetByName(string name); } } <file_sep>using System; using System.Collections.Generic; using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IEmployeeService { void Create(EmployeeDTO employee); EmployeeDTO GetUserById(string id); List<JobTitleDTO> GetJobTitles(); string GetJobTitleIdByName(string jobTitleName); void UpdateEmployee(EmployeeDTO employee); string GetTeamNameById(string id); IEnumerable<EmployeeDTO> GetAll(); IEnumerable<EmployeeDTO> GetAllFreeEmployees(); IEnumerable<EmployeeDTO> GetEmployeesByTeamId(string id); void AddToTeam(string EmployeeID, string TeamID); void RemoveFromTeam(string EmployeeID, string TeamID); string GetRoleByUserId(string id); JobTitleDTO GetJobTitleById(string id); string GetStatusByEmployeeId(string id); BalanceChangeDTO GetEmployeeDataForBalanceChange(string id); void UpdateEmployeeBalance(EmployeeDTO employee, string comment); } }<file_sep>using System; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class JobTitleRepository : IJobTitleRepository { private readonly VacationsContext _context; public JobTitleRepository(VacationsContext dbContext) { _context = dbContext; } public JobTitle[] Get(Func<JobTitle, bool> whereCondition = null) { IQueryable<JobTitle> baseCondition = _context.JobTitles; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public JobTitle GetById(string id) { return _context.JobTitles.FirstOrDefault(x => x.JobTitleID == id); } public void Remove(string id) { var obj = _context.JobTitles.FirstOrDefault(x => x.JobTitleID == id); if (obj != null) { _context.JobTitles.Remove(obj); _context.SaveChanges(); } } public void Add(JobTitle jobTitle) { _context.JobTitles.Add(jobTitle); _context.SaveChanges(); } } } <file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface IJobTitleRepository : IRepository<JobTitle> { } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Vacations.Models { public class BalanceChangeViewModel { [Required(ErrorMessage = " required field")] [Display(Name = "comment")] [StringLength(100, ErrorMessage = " should be shorter.")] public string Comment { get; set; } [Required(ErrorMessage = " required field")] [Display(Name = "balance")] [Range(1, 28, ErrorMessage = " should be from 1 to 28.")] public int Balance { get; set; } public string EmployeeID { get; set; } public string EmployeeName { get; set; } public string JobTitle { get; set; } public string TeamName { get; set; } public string TeamLeadName { get; set; } } }<file_sep>using IdentitySample.Models; using Microsoft.AspNet.Identity; using System; using System.Transactions; using Vacations.Models; using VacationsBLL.DTOs; using VacationsBLL.Interfaces; using VacationsBLL.Services; namespace Vacations.Subservice { public static class EmployeeCreationService { public static bool CreateAndRegisterEmployee(EmployeeViewModel model, string role, ApplicationUserManager userManager, ApplicationUser user, IEmployeeService employeeService) { using (TransactionScope transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var result = userManager.Create(user, Guid.NewGuid().ToString()); if (result.Succeeded) { userManager.AddToRole(model.EmployeeID, role); var _employee = Mapper.Map<EmployeeViewModel, EmployeeDTO>(model); employeeService.Create(_employee); transaction.Complete(); return result.Succeeded; } else { return false; } } } } }<file_sep>using System.Data.Entity; using VacationsDAL.Entities; namespace VacationsDAL.Contexts { public partial class VacationsContext : DbContext { public VacationsContext() : base("name=VacationsContext") { } public virtual DbSet<AspNetRole> AspNetRoles { get; set; } public virtual DbSet<AspNetUserClaim> AspNetUserClaims { get; set; } public virtual DbSet<AspNetUserLogin> AspNetUserLogins { get; set; } public virtual DbSet<AspNetUser> AspNetUsers { get; set; } public virtual DbSet<Employee> Employees { get; set; } public virtual DbSet<JobTitle> JobTitles { get; set; } public virtual DbSet<Team> Teams { get; set; } public virtual DbSet<Transaction> Transactions { get; set; } public virtual DbSet<TransactionType> TransactionTypes { get; set; } public virtual DbSet<Vacation> Vacations { get; set; } public virtual DbSet<VacationStatusType> VacationStatusTypes { get; set; } public virtual DbSet<VacationType> VacationTypes { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<AspNetRole>() .HasMany(e => e.AspNetUsers) .WithMany(e => e.AspNetRoles) .Map(m => m.ToTable("AspNetUserRoles").MapLeftKey("RoleId").MapRightKey("UserId")); modelBuilder.Entity<AspNetUser>() .HasMany(e => e.AspNetUserClaims) .WithRequired(e => e.AspNetUser) .HasForeignKey(e => e.UserId); modelBuilder.Entity<AspNetUser>() .HasMany(e => e.AspNetUserLogins) .WithRequired(e => e.AspNetUser) .HasForeignKey(e => e.UserId); modelBuilder.Entity<AspNetUser>() .HasOptional(e => e.Employee) .WithRequired(e => e.AspNetUser); modelBuilder.Entity<Employee>() .HasMany(e => e.Teams) .WithRequired(e => e.Employee) .HasForeignKey(e => e.TeamLeadID) .WillCascadeOnDelete(false); modelBuilder.Entity<Employee>() .HasMany(e => e.Transactions) .WithRequired(e => e.Employee) .WillCascadeOnDelete(false); modelBuilder.Entity<Employee>() .HasMany(e => e.Vacations) .WithRequired(e => e.Employee) .WillCascadeOnDelete(false); modelBuilder.Entity<Employee>() .HasMany(e => e.EmployeesTeam) .WithMany(e => e.Employees) .Map(m => m.ToTable("EmployeeTeam").MapLeftKey("EmployeeID").MapRightKey("TeamID")); modelBuilder.Entity<JobTitle>() .HasMany(e => e.Employees) .WithRequired(e => e.JobTitle) .WillCascadeOnDelete(false); modelBuilder.Entity<TransactionType>() .HasMany(e => e.Transactions) .WithRequired(e => e.TransactionType) .WillCascadeOnDelete(false); modelBuilder.Entity<VacationStatusType>() .HasMany(e => e.Vacations) .WithRequired(e => e.VacationStatusType) .WillCascadeOnDelete(false); } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace VacationsDAL.Entities { [Table("Vacation")] public partial class Vacation { [Required] [StringLength(128)] public string VacationID { get; set; } [Required] [StringLength(128)] public string EmployeeID { get; set; } [Column(TypeName = "date")] public DateTime DateOfBegin { get; set; } [Column(TypeName = "date")] public DateTime DateOfEnd { get; set; } [StringLength(100)] public string Comment { get; set; } [Required] [StringLength(128)] public string VacationStatusTypeID { get; set; } [Required] [StringLength(128)] public string VacationTypeID { get; set; } [StringLength(128)] public string TransactionID { get; set; } [StringLength(128)] public string ProcessedByID { get; set; } [Column(TypeName = "date")] public DateTime Created { get; set; } public int Duration { get; set; } public virtual Employee Employee { get; set; } public virtual Transaction Transaction { get; set; } public virtual VacationStatusType VacationStatusType { get; set; } } } <file_sep>namespace VacationsBLL.Enums { public enum RoleEnum { Administrator, TeamLeader, Employee } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace VacationsDAL.Entities { [Table("Transaction")] public partial class Transaction { public Transaction() { Vacations = new HashSet<Vacation>(); } public string TransactionID { get; set; } public int BalanceChange { get; set; } [Required] [StringLength(50)] public string Discription { get; set; } [Required] [StringLength(128)] public string EmployeeID { get; set; } [Column(TypeName = "date")] public DateTime TransactionDate { get; set; } [Required] [StringLength(128)] public string TransactionTypeID { get; set; } public virtual Employee Employee { get; set; } public virtual TransactionType TransactionType { get; set; } public virtual ICollection<Vacation> Vacations { get; set; } } } <file_sep>namespace VacationsBLL.Enums { public enum TransactionTypeEnum { VacationApprove, VacationDeny, ForceBalanceChangeTransaction } } <file_sep>using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IRequestService { RequestProcessDTO GetRequestDataById(string id); void SetReviewerID(string email); RequestDTO[] GetRequestsForAdmin(string searchKey = null); RequestDTO[] GetRequestsForTeamLeader(string searchKey = null); void DenyVacation(RequestProcessResultDTO result); void ApproveVacation(RequestProcessResultDTO result); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Vacations.Models { public class RequestVacationViewModel { public ProfileViewModel ProfileData; public VacationBalanceViewModel VacationBalanceData; public RequestCreationViewModel RequestCreationData; } }<file_sep>using System; using System.Linq; using System.Threading.Tasks; using VacationsDAL.Contexts; using VacationsDAL.Entities; namespace BalanceResetWebJob { public class Functions { public void UpdateBalance() { if (DateTime.Today.ToString("ddMM").Equals("0101")) { using (var context = new VacationsContext()) { var employees = context.Employees.Where(x => x.Status).ToList(); foreach (var employee in employees) { if (employee.VacationBalance < 0) { employee.VacationBalance += 28; } else { employee.VacationBalance = 28; } /*employee.Transactions.Add(new Transaction { BalanceChange = 28, Discription = "New Year", EmployeeID = employee.EmployeeID, Employee = employee, TransactionDate = DateTime.Today, TransactionID = Guid.NewGuid().ToString(), TransactionType = "", });*/ } context.SaveChanges(); } } } } } <file_sep>using System; using System.Data.Entity; using System.Data.Entity.Validation; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class VacationRepository : IVacationRepository { private readonly VacationsContext _context; public VacationRepository(VacationsContext dbContext) { _context = dbContext; } public Vacation[] Get(Func<Vacation, bool> whereCondition = null) { IQueryable<Vacation> baseCondition = _context.Vacations; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public Vacation GetById(string id) { return _context.Vacations.FirstOrDefault(x => x.VacationID == id); } public void Remove(string id) { var obj = _context.Vacations.FirstOrDefault(x => x.VacationID == id); if (obj != null) { _context.Vacations.Remove(obj); _context.SaveChanges(); } } public void Add(Vacation Vacation) { _context.Vacations.Add(Vacation); _context.SaveChanges(); } public void Update(Vacation vacation) { if (vacation != null) { _context.Entry(vacation).State = EntityState.Modified; _context.SaveChanges(); } } } } <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace VacationsDAL.Entities { [Table("VacationStatusType")] public partial class VacationStatusType { public VacationStatusType() { Vacations = new HashSet<Vacation>(); } public string VacationStatusTypeID { get; set; } [Required] [StringLength(50)] public string VacationStatusName { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Vacation> Vacations { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using VacationsBLL.DTOs; using VacationsBLL.Enums; using VacationsBLL.Functions; using VacationsBLL.Interfaces; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class EmployeeListService : IEmployeeListService { private IEmployeeRepository _employees; private IVacationRepository _vacations; private IVacationStatusTypeRepository _vacationStatuses; public EmployeeListService(IEmployeeRepository employees, IVacationRepository vacations, IVacationStatusTypeRepository vacationStatuses) { _employees = employees; _vacations = vacations; _vacationStatuses = vacationStatuses; } public List<EmployeeListDTO> EmployeeList(string searchKey = null) { Employee[] employees = null; var today = DateTime.UtcNow; var statusApprovedID = _vacationStatuses.GetByType(VacationStatusTypeEnum.Approved.ToString()).VacationStatusTypeID; var vacations = _vacations.Get(x => x.VacationStatusTypeID.Equals(statusApprovedID)); var result = new List<EmployeeListDTO>(); if (searchKey != null) { bool whereLinq(Employee emp) => (string.Format($"{emp.Name} {emp.Surname}").ToLower().Contains(searchKey.ToLower()) || emp.PhoneNumber.ToLower().Contains(searchKey.ToLower()) || emp.WorkEmail.ToLower().Contains(searchKey.ToLower())) && emp.Status; employees = _employees.Get(whereLinq); } else { employees = _employees.Get(x=>x.Status); } foreach (var employee in employees) { if (employee.EmployeesTeam.Count == 0) { var temp = Mapper.Map<Employee, EmployeeForListDTO>(employee); temp.CurrentVacationID = vacations.FirstOrDefault(x => x.EmployeeID.Equals(temp.EmployeeID) && x.DateOfBegin.Date <= today && x.DateOfEnd.Date >= today)?.VacationID; result.Add(new EmployeeListDTO { EmployeeDto = temp, TeamDto = new TeamDTO { TeamID = "Empty", TeamLeadID = "Empty", TeamName = "Empty" } }); } else { foreach (var team in employee.EmployeesTeam) { var temp = Mapper.Map<Employee, EmployeeForListDTO>(employee); temp.CurrentVacationID = vacations.FirstOrDefault(x => x.EmployeeID.Equals(temp.EmployeeID) && x.DateOfBegin.Date <= today && x.DateOfEnd.Date >= today)?.VacationID; result.Add(new EmployeeListDTO { EmployeeDto = temp, TeamDto = new TeamDTO { TeamID = team.TeamID, TeamLeadID = team.TeamLeadID, TeamName = team.TeamName } }); } } } return result.OrderBy(x=> FunctionHelper.EmployeeSortFunc(x.TeamDto.TeamName)).ToList(); } } } <file_sep>using System; using System.Globalization; using System.Linq; using System.Resources; using System.Transactions; using VacationsBLL.DTOs; using VacationsBLL.Enums; using VacationsBLL.Functions; using VacationsBLL.Interfaces; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class RequestService : IRequestService { public string ReviewerID { get; set; } private const string Empty = "None"; private IUsersRepository _users; private IJobTitleRepository _jobTitles; private IEmployeeRepository _employees; private IVacationRepository _vacations; private ITransactionRepository _transactions; private IVacationTypeRepository _vacationTypes; private IVacationStatusTypeRepository _vacationStatusTypes; private ITransactionTypeRepository _transactionTypes; private IEmailSendService _emailService; public RequestService(ITransactionTypeRepository transactionTypes, ITransactionRepository transactions, IJobTitleRepository jobTitles, IEmployeeRepository employees, IVacationRepository vacations, IVacationStatusTypeRepository vacationStatusTypes, IVacationTypeRepository vacationTypes, IUsersRepository users, IEmailSendService sendService) { _jobTitles = jobTitles; _employees = employees; _vacations = vacations; _vacationStatusTypes = vacationStatusTypes; _vacationTypes = vacationTypes; _transactions = transactions; _transactionTypes = transactionTypes; _users = users; _emailService = sendService; } public void SetReviewerID(string id) { ReviewerID = id; } public RequestDTO[] GetRequestsForAdmin(string searchKey=null) { var vacationStatusTypes = _vacationStatusTypes.Get(); var users =_users.Get(); bool whereLinq(Employee emp) => (emp.AspNetUser.AspNetRoles.Any(role => role.Name.Equals(RoleEnum.Administrator.ToString())) || (emp.EmployeesTeam.Count.Equals(1) && emp.EmployeesTeam.First().TeamLeadID.Equals(ReviewerID)) || emp.EmployeesTeam.Count.Equals(0)) && emp.Status.Equals(true); var employees = _employees.Get(whereLinq); if (employees != null) { var requestsList = _vacations.Get().Join(employees, vac => vac.EmployeeID, emp => emp.EmployeeID, (vac, emp) => new RequestDTO { EmployeeID = emp.EmployeeID, VacationID = vac.VacationID, Name = string.Format($"{emp.Name} {emp.Surname}"), TeamName = emp.EmployeesTeam.Count.Equals(0) ? Empty : emp.EmployeesTeam.First().TeamName, Duration = vac.Duration, VacationDates = string.Format($"{vac.DateOfBegin.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)}-{vac.DateOfEnd.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)}"), EmployeesBalance = emp.VacationBalance, Created = vac.Created, Status = vacationStatusTypes.FirstOrDefault(type => type.VacationStatusTypeID.Equals(vac.VacationStatusTypeID)).VacationStatusName, }).OrderBy(req => FunctionHelper.VacationSortFunc(req.Status)).ThenBy(req => req.Created).ToArray(); if(searchKey != null) { requestsList = requestsList.Where(x => x.Name.ToLower().Contains(searchKey.ToLower()) || x.TeamName.ToLower().Contains(searchKey.ToLower())).ToArray(); } return requestsList; } return new RequestDTO[0]; } public RequestDTO[] GetRequestsForTeamLeader(string searchKey = null) { var vacationStatusTypes = _vacationStatusTypes.Get(); bool whereLinq(Employee emp) => (emp.EmployeesTeam.Count.Equals(1) && emp.EmployeesTeam.First().TeamLeadID.Equals(ReviewerID)) && emp.Status.Equals(true); ; Employee[] employees = _employees.Get(whereLinq); if (employees != null) { var requestsList = _vacations.Get().Join(employees, vac => vac.EmployeeID, emp => emp.EmployeeID, (vac, emp) => new RequestDTO { EmployeeID = emp.EmployeeID, VacationID = vac.VacationID, Name = string.Format($"{emp.Name} {emp.Surname}"), TeamName = emp.EmployeesTeam.Count.Equals(0) ? Empty : emp.EmployeesTeam.First().TeamName, Duration = vac.Duration, VacationDates = string.Format($"{vac.DateOfBegin.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)}-{vac.DateOfEnd.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)}"), EmployeesBalance = emp.VacationBalance, Created = vac.Created, Status = vacationStatusTypes.FirstOrDefault(type => type.VacationStatusTypeID.Equals(vac.VacationStatusTypeID)).VacationStatusName, }).OrderBy(req => FunctionHelper.VacationSortFunc(req.Status)).ThenBy(req => req.Created).ToArray(); if (searchKey != null) { requestsList = requestsList.Where(x => x.Name.ToLower().Contains(searchKey.ToLower()) || x.TeamName.Contains(searchKey.ToLower())).ToArray(); } return requestsList; } return new RequestDTO[0]; } public RequestProcessDTO GetRequestDataById(string id) { var vacation = _vacations.GetById(id); if (vacation != null) { var employee = _employees.GetById(vacation.EmployeeID); var vacationType = _vacationTypes.GetById(vacation.VacationTypeID).VacationTypeName; var jobTitle = _jobTitles.GetById(employee.JobTitleID).JobTitleName; var status = _vacationStatusTypes.GetById(vacation.VacationStatusTypeID).VacationStatusName; string processedBy = null; if(vacation.ProcessedByID != null) { var processedByTemp = _employees.GetById(vacation.ProcessedByID); processedBy = string.Format($"{processedByTemp.Name} {processedByTemp.Surname}"); } var request = new RequestProcessDTO { EmployeeID = employee.EmployeeID, VacationID = vacation.VacationID, Comment = vacation.Comment, DateOfBegin = vacation.DateOfBegin, DateOfEnd = vacation.DateOfEnd, Duration = vacation.Duration, EmployeeName = string.Format($"{employee.Name} {employee.Surname}"), JobTitle = jobTitle, Status = status, VacationType = vacationType, TeamLeadName = employee.EmployeesTeam.Count.Equals(0) ? Empty : _employees.GetById(employee.EmployeesTeam.First().TeamLeadID).Name, TeamName = employee.EmployeesTeam.Count.Equals(0) ? Empty : employee.EmployeesTeam.First().TeamName, ProcessedBy = processedBy, EmployeesBalance = employee.VacationBalance }; return request; } else { return new RequestProcessDTO(); } } public void ApproveVacation(RequestProcessResultDTO result) { var vacation = _vacations.GetById(result.VacationID); var employee = _employees.GetById(result.EmployeeID); if (vacation != null && employee != null) { using (TransactionScope scope = new TransactionScope()) { var transaction = new VacationsDAL.Entities.Transaction { BalanceChange = result.Duration, Discription = result.Discription ?? Empty, EmployeeID = result.EmployeeID, TransactionDate = DateTime.UtcNow, TransactionTypeID = _transactionTypes.GetByType(TransactionTypeEnum.VacationApprove.ToString()).TransactionTypeID, TransactionID = Guid.NewGuid().ToString() }; _transactions.Add(transaction); vacation.Duration = result.Duration; vacation.DateOfBegin = result.DateOfBegin; vacation.DateOfEnd = result.DateOfEnd; vacation.ProcessedByID = ReviewerID; vacation.TransactionID = transaction.TransactionID; vacation.VacationStatusTypeID = _vacationStatusTypes.GetByType(VacationStatusTypeEnum.Approved.ToString()).VacationStatusTypeID; _vacations.Update(vacation); employee.VacationBalance -= result.Duration; _employees.Update(); _emailService.SendAsync(employee.WorkEmail, $"{employee.Name} {employee.Surname}", "Vacation request.", "Your vacation request was approved.", $"{employee.Name} {employee.Surname}, your vacation request from {vacation.DateOfBegin.ToString("dd-MM-yyyy")} to {vacation.DateOfEnd.ToString("dd-MM-yyyy")} was approved. Have a nice vacation."); scope.Complete(); } } } public void DenyVacation(RequestProcessResultDTO result) { var vacation = _vacations.GetById(result.VacationID); var employee = _employees.GetById(result.EmployeeID); if (vacation != null) { using (TransactionScope scope = new TransactionScope()) { var transaction = new VacationsDAL.Entities.Transaction { BalanceChange = 0, Discription = result.Discription ?? Empty, EmployeeID = result.EmployeeID, TransactionDate = DateTime.UtcNow, TransactionTypeID = _transactionTypes.GetByType(TransactionTypeEnum.VacationDeny.ToString()).TransactionTypeID, TransactionID = Guid.NewGuid().ToString() }; _transactions.Add(transaction); vacation.VacationStatusTypeID = _vacationStatusTypes.GetByType(VacationStatusTypeEnum.Denied.ToString()).VacationStatusTypeID; vacation.ProcessedByID = ReviewerID; vacation.TransactionID = transaction.TransactionID; _vacations.Update(vacation); _emailService.SendAsync(employee.WorkEmail, $"{employee.Name} {employee.Surname}", "Vacation request.", "Your vacation request was denied.", $"{employee.Name} {employee.Surname}, your vacation request from {vacation.DateOfBegin.ToString("dd-MM-yyyy")} to {vacation.DateOfEnd.ToString("dd-MM-yyyy")} was denied. Please, check it."); scope.Complete(); } } } } } <file_sep>namespace VacationsBLL.DTOs { public class JobTitleDTO { public string JobTitleID { get; set; } public string JobTitleName { get; set; } } } <file_sep>using System; using System.Collections.Generic; using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IUserService { bool AspNetUserExists(string id); UserDTO[] GetUsers(); } }<file_sep>using System.Linq; using VacationsBLL.DTOs; using VacationsBLL.Functions; using VacationsBLL.Interfaces; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class ProfileDataService : IProfileDataService { private const string empty = "None"; private IEmployeeRepository _employees; private IJobTitleRepository _jobTitles; private IVacationRepository _vacations; private IVacationStatusTypeRepository _vacationStatusTypes; private IVacationTypeRepository _vacationTypes; public ProfileDataService(IEmployeeRepository employees, IJobTitleRepository jobTitles, IVacationRepository vacations, IVacationStatusTypeRepository vacationStatusTypes, IVacationTypeRepository vacationTypes) { _employees = employees; _jobTitles = jobTitles; _vacations = vacations; _vacationTypes = vacationTypes; _vacationStatusTypes = vacationStatusTypes; } public ProfileDTO GetUserData(string id) { var employee = _employees.GetById(id); var teamLeader = empty; var jobTitle = _jobTitles.GetById(employee.JobTitleID).JobTitleName; if (employee.EmployeesTeam.Count > 0) { var tempLead = _employees.GetById(employee.EmployeesTeam.First().TeamLeadID); teamLeader = string.Format($"{tempLead.Name} {tempLead.Surname}"); } if (employee != null) { var userData = Mapper.Map<Employee, ProfileDTO>(employee); userData.TeamName = employee.EmployeesTeam.Count.Equals(0) ? empty : employee.EmployeesTeam.First().TeamName; userData.TeamLeader = teamLeader; userData.JobTitle = jobTitle; userData.EmployeeID = employee.EmployeeID; return userData; } return null; } public ProfileVacationDTO[] GetUserVacationsData(string id) { var employee = _employees.GetById(id); var vacationStatuses = _vacationStatusTypes.Get(); var vacationTypes = _vacationTypes.Get(); var vacations = _vacations.Get(x => x.EmployeeID.Equals(employee.EmployeeID)).Select(x => new ProfileVacationDTO { VacationType = vacationTypes.FirstOrDefault(y=>y.VacationTypeID.Equals(x.VacationTypeID)).VacationTypeName, Comment = x.Comment, DateOfBegin = x.DateOfBegin, DateOfEnd = x.DateOfEnd, Duration = x.Duration, Status = vacationStatuses.FirstOrDefault(y => y.VacationStatusTypeID.Equals(x.VacationStatusTypeID)).VacationStatusName, Created = x.Created }).OrderBy(x=>FunctionHelper.VacationSortFunc(x.Status)).ThenBy(x=>x.Created).ToArray(); return vacations; } public VacationBalanceDTO GetUserVacationBalance(string id) { var employee = _employees.GetById(id); return new VacationBalanceDTO { Balance = employee.VacationBalance }; } } } <file_sep>using System.Collections.Generic; using VacationsBLL.DTOs; using VacationsBLL.Interfaces; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class RoleService: IRoleService { IRolesRepository _roles; public RoleService(IRolesRepository roles) { _roles = roles; } public void Create(RoleDTO aspNetRole) { _roles.Add(Mapper.Map<RoleDTO, AspNetRole>(aspNetRole)); } public List<RoleDTO> GetRoles() { var roles = _roles.Get(); var rolesDTO = new List<RoleDTO>(); foreach (var role in roles) { rolesDTO.Add(Mapper.Map<AspNetRole, RoleDTO>(role)); } return rolesDTO; } } } <file_sep>namespace VacationsBLL.DTOs { public class VacationBalanceDTO { public int Balance { get; set; } } } <file_sep>using System; namespace VacationsDAL.Interfaces { public interface IRepository<T> { void Add(T employee); T[] Get(Func<T, bool> condition = null); T GetById(string id); void Remove(string id); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Vacations.Models { public class EmployeeListViewModel { public EmployeeForListViewModel EmployeeDto { get; set; } public EmployeeListTeamViewModel TeamDto { get; set; } } }<file_sep>using System.Collections.Generic; using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface ITeamService { void CreateTeam(TeamDTO team); IEnumerable<TeamListDTO> GetAllTeams(string searchKey=null); TeamListDTO GetById(string id); TeamDTO GetTeamById(string id); void UpdateTeamInfo(TeamDTO team); void DeleteTeam(string teamId); } }<file_sep>namespace VacationsBLL.DTOs { public class EmployeeListDTO { public EmployeeForListDTO EmployeeDto { get; set; } public TeamDTO TeamDto { get; set; } } } <file_sep>using System; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class TransactionRepository : ITransactionRepository { private readonly VacationsContext _context; public TransactionRepository(VacationsContext dbContext) { _context = dbContext; } public Transaction[] Get(Func<Transaction, bool> whereCondition = null) { IQueryable<Transaction> baseCondition = _context.Transactions; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public Transaction GetById(string id) { return _context.Transactions.FirstOrDefault(x => x.TransactionID == id); } public void Remove(string id) { var obj = _context.Transactions.FirstOrDefault(x => x.TransactionID == id); if (obj != null) { _context.Transactions.Remove(obj); _context.SaveChanges(); } } public void Add(Transaction Transaction) { _context.Transactions.Add(Transaction); _context.SaveChanges(); } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace VacationsDAL.Entities { [Table("Employee")] public partial class Employee { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Employee() { Teams = new HashSet<Team>(); Transactions = new HashSet<Transaction>(); Vacations = new HashSet<Vacation>(); EmployeesTeam = new HashSet<Team>(); } public string EmployeeID { get; set; } [Required] [StringLength(20)] public string Name { get; set; } [Required] [StringLength(30)] public string Surname { get; set; } [Column(TypeName = "date")] public DateTime BirthDate { get; set; } [Required] [StringLength(256)] public string PersonalMail { get; set; } [Required] [StringLength(60)] public string Skype { get; set; } [Column(TypeName = "date")] public DateTime HireDate { get; set; } public bool Status { get; set; } [Column(TypeName = "date")] public DateTime? DateOfDismissal { get; set; } public int VacationBalance { get; set; } [Required] [StringLength(128)] public string JobTitleID { get; set; } [Required] [StringLength(200)] public string WorkEmail { get; set; } [Required] [StringLength(200)] public string PhoneNumber { get; set; } public virtual AspNetUser AspNetUser { get; set; } public virtual JobTitle JobTitle { get; set; } public virtual ICollection<Team> Teams { get; set; } public virtual ICollection<Transaction> Transactions { get; set; } public virtual ICollection<Vacation> Vacations { get; set; } public virtual ICollection<Team> EmployeesTeam { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VacationsBLL.DTOs; using VacationsBLL.Enums; using VacationsBLL.Interfaces; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class VacationService : IVacationService { private IVacationRepository _vacationRepository; private IVacationStatusTypeRepository _vacationStatusTypeRepository; public VacationService(IVacationRepository vacations, IVacationStatusTypeRepository vacationStatusType) { _vacationRepository = vacations; _vacationStatusTypeRepository = vacationStatusType; } public void Create(VacationDTO vacation) { _vacationRepository.Add(Mapper.Map<VacationDTO, Vacation>(vacation)); } public List<VacationDTO> GetVacations() { var vacations = _vacationRepository.Get(); var vacationsDTO = new List<VacationDTO>(); foreach (var vacation in vacations) { vacationsDTO.Add(Mapper.Map<Vacation, VacationDTO>(vacation)); } return vacationsDTO; } public bool IsApproved(string id) { return _vacationStatusTypeRepository.GetById(id).VacationStatusName == VacationStatusTypeEnum.Approved.ToString(); } } } <file_sep>using VacationsBLL.DTOs; using VacationsBLL.Interfaces; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class UserService : IUserService { private IUsersRepository _users; public UserService(IUsersRepository users) { _users = users; } public bool AspNetUserExists(string id) { return _users.GetById(id) != null; } public UserDTO[] GetUsers() { return Mapper.MapCollection<AspNetUser, UserDTO>(_users.Get()); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Vacations.Models { public class BalanceChangeResultModel { public string EmployeeID { get; set; } public string Comment { get; set; } public int Balance { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IVacationService { void Create(VacationDTO employee); List<VacationDTO> GetVacations(); bool IsApproved(string id); } } <file_sep>using System; namespace VacationsBLL.DTOs { public class VacationDTO { public string VacationID { get; set; } public string EmployeeID { get; set; } public DateTime DateOfBegin { get; set; } public DateTime DateOfEnd { get; set; } public string Comment { get; set; } public string VacationTypeID { get; set; } public string VacationStatusTypeID { get; set; } public string TransactionID { get; set; } public string Duration { get; set; } public DateTime Created { get; set; } } } <file_sep>using IdentitySample.Models; using Microsoft.AspNet.Identity; using System; using System.Linq; using System.Transactions; using Vacations.Models; using VacationsBLL.DTOs; using VacationsBLL.Interfaces; using VacationsBLL.Services; namespace Vacations.Subservices { public static class EmployeeEditService { public static void EditEmployee(EmployeeViewModel model, string role, ApplicationUserManager userManager, ApplicationUser user, IEmployeeService employeeService, string id) { using (TransactionScope transaction = new TransactionScope()) { user.Email = model.WorkEmail; user.UserName = model.WorkEmail; userManager.Update(user); var employee = employeeService.GetUserById(id); if (employee.Status != model.Status) { if (!model.Status) { model.DateOfDismissal = DateTime.Today; } else { model.DateOfDismissal = null; model.HireDate = DateTime.Today; } } var userRole = userManager.GetRoles(model.EmployeeID).First(); if (userRole != role) { userManager.RemoveFromRole(model.EmployeeID, userRole); userManager.AddToRoles(model.EmployeeID, role); } employeeService.UpdateEmployee(Mapper.Map<EmployeeViewModel, EmployeeDTO>(model)); transaction.Complete(); } } } }<file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface IVacationTypeRepository : IRepository<VacationType> { } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vacations.Models { public class RequestProcessViewModel { public string EmployeeID { get; set; } public string VacationID { get; set; } public string EmployeeName { get; set; } public string JobTitle { get; set; } public string TeamName { get; set; } public string TeamLeadName { get; set; } [Display(Name = "vacation type")] public string VacationType { get; set; } [Required(ErrorMessage = " required field")] [Display(Name = "from")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime DateOfBegin { get; set; } [Required(ErrorMessage = " required field")] [Display(Name = "to")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime DateOfEnd { get; set; } [Display(Name = "Comment")] public string Comment { get; set; } [Required(ErrorMessage = " required field")] [Display(Name = "duration")] [Range(1, 28, ErrorMessage = " should be from 1 to 28.")] public int Duration { get; set; } public string Status { get; set; } public string ProcessedBy { get; set; } public int EmployeesBalance { get; set; } } } <file_sep>using PagedList; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Vacations.Models { public class UserViewModel { public ProfileViewModel ProfileData; public IPagedList<ProfileVacationsViewModel> VacationsData; public VacationBalanceViewModel VacationBalanceData; } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VacationsBLL.Interfaces; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class ValidateService : IValidateService { IEmployeeRepository _employees; ITeamRepository _teams; public ValidateService(IEmployeeRepository employees, ITeamRepository teams) { _employees = employees; _teams = teams; } public bool CheckEmail(string email) { return _employees.GetByEmail(email) == null ? false : true; } public bool CheckEmailOwner(string email, string id) { return _employees.GetByEmail(email).EmployeeID.Equals(id) ? false : true; } public bool CheckTeamName(string teamName) { return _teams.GetByName(teamName) == null ? false : true; } public bool CheckTeam(string teamName, string id) { return _teams.GetByName(teamName).TeamID.Equals(id) ? false : true; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using VacationsBLL.DTOs; namespace Vacations.Models { public class VacationRequestsViewModel { public RequestDTO[] Requests { get; set; } } }<file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace VacationsDAL.Entities { [Table("TransactionType")] public partial class TransactionType { public TransactionType() { Transactions = new HashSet<Transaction>(); } public string TransactionTypeID { get; set; } [Column("TransactionTypeName")] [Required] [StringLength(30)] public string TransactionTypeName{ get; set; } public virtual ICollection<Transaction> Transactions { get; set; } } } <file_sep>using System.Linq; using System.Web.Mvc; using VacationsBLL.Interfaces; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class PageListsService : IPageListsService { IJobTitleRepository _jobTitles; IRolesRepository _roles; IVacationTypeRepository _vacationTypes; IEmployeeRepository _employees; public PageListsService(IJobTitleRepository jobTitles, IRolesRepository roles, IVacationTypeRepository types, IEmployeeRepository employees) { _jobTitles = jobTitles; _roles = roles; _vacationTypes = types; _employees = employees; } public SelectListItem[] EmployeesList() { var employeesList = _employees.Get().Select(emp=>new SelectListItem { Text = emp.Name + " " + emp.Surname, Value = emp.EmployeeID }); return employeesList.ToArray(); } public SelectListItem[] EmployeesList(string value) { var employeesList = _employees.Get().Select(emp => new SelectListItem { Text = emp.Name + " " + emp.Surname, Value = emp.EmployeeID, Selected = emp.EmployeeID == value }); return employeesList.ToArray(); } public SelectListItem[] SelectEditRoles(string value) { var roles = _roles.Get().Select(role => new SelectListItem { Text = role.Name, Value = role.Name, Selected = role.Name == value }).ToArray(); return roles; } public SelectListItem[] SelectRoles() { var roles = _roles.Get().Select(role => new SelectListItem { Text = role.Name, Value = role.Name, }).ToArray(); return roles; } public SelectListItem[] SelectJobTitles() { var jobTitles = _jobTitles.Get().Select(jobTitle => new SelectListItem { Text = jobTitle.JobTitleName, Value = jobTitle.JobTitleID, }).ToArray(); return jobTitles; } public SelectListItem[] SelectEditJobTitles(string value) { var jobTitles = _jobTitles.Get().Select(jobTitle => new SelectListItem { Text = jobTitle.JobTitleName, Value = jobTitle.JobTitleID, Selected = jobTitle.JobTitleID == value }).ToArray(); return jobTitles; } public SelectListItem[] SelectStatuses() { var statusSelectList = new SelectListItem[] { new SelectListItem { Text = "Active", Value = "true" }, new SelectListItem { Text = "Fired", Value = "false" } }; return statusSelectList; } public SelectListItem[] SelectEditStatuses(string value) { var statusSelectList = new SelectListItem[] { new SelectListItem { Text = "Active", Value = "True", Selected = "True" == value }, new SelectListItem { Text = "Fired", Value = "False", Selected = "False" == value } }; return statusSelectList; } public SelectListItem[] SelectVacationTypes() { var vacationTypes = _vacationTypes.Get().Select(type => new SelectListItem { Text = type.VacationTypeName, Value = type.VacationTypeID }).ToArray(); return vacationTypes; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VacationsBLL.DTOs { public class BalanceChangeDTO { public string EmployeeID { get; set; } public string EmployeeName { get; set; } public string JobTitle { get; set; } public string TeamName { get; set; } public string TeamLeadName { get; set; } public int Balance { get; set; } } } <file_sep>using System; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class VacationTypeRepository : IVacationTypeRepository { private readonly VacationsContext _context; public VacationTypeRepository(VacationsContext dbContext) { _context = dbContext; } public VacationType[] Get(Func<VacationType, bool> whereCondition = null) { IQueryable<VacationType> baseCondition = _context.VacationTypes; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public VacationType GetById(string id) { return _context.VacationTypes.FirstOrDefault(x => x.VacationTypeID == id); } public void Remove(string id) { var obj = _context.VacationTypes.FirstOrDefault(x => x.VacationTypeID == id); if (obj != null) { _context.VacationTypes.Remove(obj); _context.SaveChanges(); } } public void Add(VacationType VacationType) { _context.VacationTypes.Add(VacationType); _context.SaveChanges(); } } } <file_sep>using System; using System.Collections.Generic; using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IRoleService { void Create(RoleDTO employee); List<RoleDTO> GetRoles(); } } <file_sep>using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IProfileDataService { ProfileDTO GetUserData(string id); VacationBalanceDTO GetUserVacationBalance(string id); ProfileVacationDTO[] GetUserVacationsData(string id); } }<file_sep>using IdentitySample.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using VacationsBLL.Enums; using System.Web.WebPages; using Vacations.Models; using VacationsBLL.DTOs; using VacationsBLL.Interfaces; using System; using System.Collections.Generic; using System.Transactions; using VacationsBLL.Services; using Vacations.Subservice; using PagedList; using Vacations.Subservices; namespace Vacations.Controllers { [Authorize(Roles = "Administrator")] public class AdminController : Controller { private const int requestPageSize = 14; private const int teamPageSize = 15; private const int employeePageSize = 10; private readonly IPageListsService _pageListsService; private readonly IEmployeeService _employeeService; private readonly IProfileDataService _profileDataService; private readonly IRequestService _requestProcessService; private readonly IEmployeeListService _employeeListService; private readonly ITeamService _teamService; private readonly IPhotoUploadService _photoUploadService; private readonly IRequestCreationService _requestCreationService; private IValidateService _validateService; public AdminController( IProfileDataService profileDataService, IEmployeeService employeeService, IPageListsService pageListsService, IEmployeeListService adminEmployeeListService, IRequestService requestService, ITeamService teamService, IPhotoUploadService photoUploadService, IValidateService validateService, IRequestCreationService requestCreationService) { _profileDataService = profileDataService; _employeeService = employeeService; _pageListsService = pageListsService; _employeeListService = adminEmployeeListService; _requestProcessService = requestService; _teamService = teamService; _photoUploadService = photoUploadService; _validateService = validateService; _requestCreationService = requestCreationService; } #region Props private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } private ApplicationSignInManager _signInManager; public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } #endregion [HttpGet] [AllowAnonymous] public ActionResult AddEmployee() { ViewData["statusSelectList"] = _pageListsService.SelectStatuses(); ViewData["jobTitlesSelectList"] = _pageListsService.SelectJobTitles(); ViewData["aspNetRolesSelectList"] = _pageListsService.SelectRoles(); return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> AddEmployee(EmployeeViewModel model, HttpPostedFileBase photo) { ViewData["statusSelectList"] = _pageListsService.SelectStatuses(); ViewData["jobTitlesSelectList"] = _pageListsService.SelectJobTitles(); ViewData["aspNetRolesSelectList"] = _pageListsService.SelectRoles(); if (ModelState.IsValid) { var role = Request.Params["aspNetRolesSelectList"]; var user = new ApplicationUser { UserName = model.WorkEmail, Email = model.WorkEmail, PhoneNumber = model.PhoneNumber }; model.EmployeeID = user.Id; model.JobTitleID = Request.Params["jobTitlesSelectList"]; model.Status = Request.Params["statusSelectList"].AsBool(); if (EmployeeCreationService.CreateAndRegisterEmployee(model, role, UserManager, user, _employeeService)) { _photoUploadService.UploadPhoto(photo, model.EmployeeID); var code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); var email = new EmailService(); var codeToSetPassword = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrlToSetPassword = Url.Action("ResetPasswordAndConfirmEmail", "Account", new { codeToResetPassword = codeToSetPassword, codeToConfirmationEmail = code, userId = user.Id }, protocol: Request.Url.Scheme); await email.SendAsync(model.WorkEmail, model.Name + " " + model.Surname, "Confirm your account", "Please, confirm your account", "Set Password and confirm your account by clicking this <a href=\"" + callbackUrlToSetPassword + "\">link</a>."); } return RedirectToAction("EmployeesList", "Admin"); } return RedirectToAction("EmployeesList", "Admin"); } [HttpGet] public ActionResult Edit(string id) { if (id == null) { return View("ErrorPage"); } var role = UserManager.GetRoles(id).FirstOrDefault(); var model = Mapper.Map<EmployeeDTO, EmployeeViewModel>(_employeeService.GetUserById(id)); ViewData["statusSelectList"] = _pageListsService.SelectEditStatuses(model.Status.ToString()); ViewData["jobTitlesSelectList"] = _pageListsService.SelectEditJobTitles(model.JobTitleID); ViewData["aspNetRolesSelectList"] = _pageListsService.SelectEditRoles(role); return View(model); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit(EmployeeViewModel model, string id, HttpPostedFileBase photo) { model.EmployeeID = id; var role = UserManager.GetRoles(id).FirstOrDefault(); ViewData["statusSelectList"] = _pageListsService.SelectEditStatuses(model.Status.ToString()); ViewData["jobTitlesSelectList"] = _pageListsService.SelectEditJobTitles(model.JobTitleID); ViewData["aspNetRolesSelectList"] = _pageListsService.SelectEditRoles(role); if (ModelState.IsValid) { model.JobTitleID = Request.Params["jobTitlesSelectList"]; model.Status = Request.Params["statusSelectList"].AsBool(); var roleParam = Request.Params["aspNetRolesSelectList"]; var user = UserManager.FindById(id); EmployeeEditService.EditEmployee(model, roleParam, UserManager, user, _employeeService, id); if (photo != null) { _photoUploadService.UploadPhoto(photo, model.EmployeeID); } if (User.Identity.GetUserId().Equals(id)) { return RedirectToAction("Index", "Profile"); } return RedirectToAction("EmployeesList", "Admin"); } if (User.Identity.GetUserId().Equals(id)) { return RedirectToAction("Index", "Profile"); } return RedirectToAction("EmployeesList", "Admin"); } public ActionResult EmployeesList(int page = 1, string searchKey = null) { ViewData["SearchKey"] = searchKey; ViewBag.EmployeeService = _employeeService; ViewBag.TeamService = _teamService; var employeeList = _employeeListService.EmployeeList(searchKey); return View(Mapper.MapCollection<EmployeeListDTO,EmployeeListViewModel>(employeeList.ToArray()).ToPagedList(page, employeePageSize)); } [HttpGet] public ActionResult RegisterTeam() { ViewData["employeesSelectList"] = _pageListsService.EmployeesList(); ViewData["listOfEmployees"] = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(_employeeService.GetAllFreeEmployees().ToArray()); return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult RegisterTeam(TeamViewModel model) { if (ModelState.IsValid) { model.TeamLeadID = Request.Params["employeesSelectList"]; model.TeamID = Guid.NewGuid().ToString(); TeamCreationService.RegisterTeam(model, Request.Params["members"], _employeeService, _teamService, UserManager); ViewBag.ListService = _pageListsService; ViewBag.ListOfEmployees = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(_employeeService.GetAll().ToArray()); ViewData["employeesSelectList"] = _pageListsService.EmployeesList(); ViewData["listOfEmployees"] = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(_employeeService.GetAllFreeEmployees() .ToArray()); } return RedirectToAction("TeamsList", "Admin"); } [HttpGet] public ActionResult Requests(int page = 1, string searchKey = null) { ViewData["SearchKey"] = searchKey; _requestProcessService.SetReviewerID(User.Identity.GetUserId()); var map = Mapper.MapCollection<RequestDTO, RequestViewModel>(_requestProcessService.GetRequestsForAdmin(searchKey)); var list = map.ToPagedList(page, requestPageSize); return View(list); } [HttpGet] public ActionResult ProcessPopupPartial(string id, bool isCalledFromList = false) { ViewData["isCalledFromList"] = isCalledFromList; var request = Mapper.Map<RequestProcessDTO, RequestProcessViewModel>(_requestProcessService.GetRequestDataById(id)); return PartialView("ProcessPopupPartial", request); } [HttpPost] public ActionResult ProcessPopupPartial(RequestProcessResultModel model) { _requestProcessService.SetReviewerID(User.Identity.GetUserId()); if (ModelState.IsValid) { if (model.Result.Equals(VacationStatusTypeEnum.Approved.ToString())) { _requestProcessService.ApproveVacation(Mapper.Map<RequestProcessResultModel, RequestProcessResultDTO>(model)); } else { _requestProcessService.DenyVacation(Mapper.Map<RequestProcessResultModel, RequestProcessResultDTO>(model)); } } return RedirectToAction("Requests"); } [HttpGet] public ActionResult BalanceChangePopupPartial(string id) { var employee = Mapper.Map<BalanceChangeDTO, BalanceChangeViewModel>(_employeeService.GetEmployeeDataForBalanceChange(id)); return PartialView("BalanceChangePopupPartial", employee); } [HttpPost] public ActionResult BalanceChangePopupPartial(BalanceChangeResultModel model) { var employee = _employeeService.GetUserById(model.EmployeeID); if (ModelState.IsValid) { employee.VacationBalance = model.Balance; _employeeService.UpdateEmployeeBalance(employee, model.Comment); if (User.Identity.GetUserId().Equals(employee.EmployeeID)) { return RedirectToAction("Index", "Profile"); } return RedirectToAction("EmployeesList", "Admin"); } if (User.Identity.GetUserId().Equals(employee.EmployeeID)) { return RedirectToAction("Index", "Profile"); } return RedirectToAction("EmployeesList","Admin"); } [HttpGet] public ActionResult CreateRequestForEmployeePartial(string id) { ViewData["VacationTypesSelectList"] = _pageListsService.SelectVacationTypes(); var creationData = _requestCreationService.GetEmployeeDataForRequestByID(id); return PartialView("CreateRequestForEmployeePartial", Mapper.Map<RequestForEmployeeDTO, RequestForEmployeeViewModel>(creationData)); } [HttpPost] public ActionResult CreateRequestForEmployeePartial(RequestForEmployeeViewModel model) { _requestProcessService.SetReviewerID(User.Identity.GetUserId()); var vacation = Mapper.Map<RequestForEmployeeViewModel, VacationDTO>(model); vacation.Comment = model.Discription; vacation.VacationTypeID = Request.Params["VacationTypesSelectList"]; _requestCreationService.ForceVacationForEmployee(vacation); var request = Mapper.Map<VacationDTO, RequestProcessResultDTO>(vacation); request.Result = VacationStatusTypeEnum.Approved.ToString(); _requestProcessService.ApproveVacation(request); return RedirectToAction("EmployeesList","Admin"); } [HttpGet] public ActionResult TeamsList(string searchKey, int page = 1) { ViewData["SearchKey"] = searchKey; var result = new List<TeamListViewModel>(); var teams = _teamService.GetAllTeams(searchKey); foreach (var teamListDto in teams) { var teamLead = _employeeService.GetUserById(teamListDto.TeamLeadID); result.Add(new TeamListViewModel { TeamID = teamListDto.TeamID, TeamName = teamListDto.TeamName, TeamLeadName = teamLead.Name + " " + teamLead.Surname, AmountOfEmployees = teamListDto.AmountOfEmployees }); } return View(result.ToPagedList(page, teamPageSize)); } [HttpGet] public ActionResult ViewTeamProfile(string id) { var team = _teamService.GetById(id); var employeesDTOs = _employeeService.GetEmployeesByTeamId(team.TeamID); var teamLead = _employeeService.GetUserById(team.TeamLeadID); var employees = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(employeesDTOs.ToArray()); var result = new TeamProfileViewModel { TeamID = team.TeamID, TeamName = team.TeamName, TeamLeadName = teamLead.Name + " " + teamLead.Surname, TeamLeadID = team.TeamLeadID, Status = teamLead.Status, AmountOfEmployees = team.AmountOfEmployees, Employees = employees }; return View(result); } [HttpGet] public ActionResult EmployeeView(string id) { var employee = _employeeService.GetUserById(id); if (employee != null) { var model = Mapper.Map<EmployeeDTO, EmployeeViewModel>(employee); ViewData["Status"] = _employeeService.GetStatusByEmployeeId(model.EmployeeID); ViewData["JobTitle"] = _employeeService.GetJobTitleById(model.JobTitleID).JobTitleName; ViewData["Role"] = _employeeService.GetRoleByUserId(model.EmployeeID); return View(model); } return RedirectToAction("Requests", "Admin"); } [HttpGet] public ActionResult EditTeam(string id) { var team = Mapper.Map<TeamDTO, TeamViewModel>(_teamService.GetTeamById(id)); var employees = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(_employeeService.GetEmployeesByTeamId(id).ToArray()); ViewData["employeesSelectList"] = _pageListsService.EmployeesList(team.TeamLeadID); ViewData["listOfEmployees"] = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(_employeeService.GetAllFreeEmployees().ToArray()); ViewData["Employees"] = employees; ViewData["Team"] = team; return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult EditTeam(TeamViewModel model, string id) { using (TransactionScope transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { model.TeamLeadID = Request.Params["employeesSelectList"]; model.TeamID = id; string members = Request.Params["members"]; var employees = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(_employeeService.GetEmployeesByTeamId(id).ToArray()); _teamService.UpdateTeamInfo(Mapper.Map<TeamViewModel, TeamDTO>(model)); var userRole = UserManager.GetRoles(model.TeamLeadID).First(); if (userRole.Equals(RoleEnum.Employee.ToString())) { UserManager.RemoveFromRole(model.TeamLeadID, userRole); UserManager.AddToRoles(model.TeamLeadID, RoleEnum.TeamLeader.ToString()); } var oldEmployeesID = new List<string>(); foreach (var employee in employees) { oldEmployeesID.Add(employee.EmployeeID); } if (members == null) { foreach (var employeeId in oldEmployeesID) { if (employeeId != model.TeamLeadID) { _employeeService.RemoveFromTeam(employeeId, model.TeamID); } } _teamService.DeleteTeam(model.TeamID); transaction.Complete(); return RedirectToAction("TeamsList", "Admin", _profileDataService); } var newEmployeesID = members.Split(',').ToList(); var employeesToRemove = oldEmployeesID.Except(newEmployeesID); var employeesToAdd = newEmployeesID.Except(oldEmployeesID); foreach (var employeeId in employeesToAdd) { if (employeeId != model.TeamLeadID) { _employeeService.AddToTeam(employeeId, model.TeamID); } } foreach (var employeeId in employeesToRemove) { if (employeeId != model.TeamLeadID) { _employeeService.RemoveFromTeam(employeeId, model.TeamID); } } transaction.Complete(); } return RedirectToAction("TeamsList", "Admin"); } } } <file_sep>using Microsoft.Azure; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.RetryPolicies; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Web; using VacationsBLL.Interfaces; namespace VacationsBLL.Services { public class PhotoUploadService : IPhotoUploadService { private const string ConnectionStringSettingName = "StorageConnectionString"; private const string ContainerName = "photos"; private const string defaultPhoto = "default.jpg"; private byte[] ConvertFileIntoByteArray(HttpPostedFileBase file) { if (file != null) { byte[] buffer = new byte[file.ContentLength]; byte[] content; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = file.InputStream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } content = ms.ToArray(); } return content; } return new byte[0]; } public void UploadPhoto(HttpPostedFileBase file, string id) { if (file == null) { var bytePhoto = DownloadFileInBlocks(defaultPhoto); var fileName = string.Format($"{id}.jpg"); UploadFileInBlocks(bytePhoto, fileName); } else { var bytePhoto = ConvertFileIntoByteArray(file); var fileName = string.Format($"{id}.jpg"); UploadFileInBlocks(bytePhoto, fileName); } } private byte[] DownloadFileInBlocks(string fileName) { CloudBlobContainer cloudBlobContainer = GetContainerReference(); CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(Path.GetFileName(fileName)); int blockSize = 1024 * 1024; // 1 MB block size blob.FetchAttributes(); long fileSize = blob.Properties.Length; byte[] blobContents = new byte[fileSize]; int position = 0; while (fileSize > 0) { int blockLength = (int)Math.Min(blockSize, fileSize); blob.DownloadRangeToByteArray(blobContents, position, position, blockLength); position += blockLength; fileSize -= blockSize; } return blobContents; } private void UploadFileInBlocks(byte[] file, string fileName) { CloudBlobContainer cloudBlobContainer = GetContainerReference(); CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(Path.GetFileName(fileName)); blob.DeleteIfExists(); List<string> blockIDs = new List<string>(); int blockSize = 5 * 1024 * 1024; long fileSize = file.Length; int blockId = 0; while (fileSize > 0) { int blockLength = (int)Math.Min(blockSize, fileSize); string blockIdEncoded = GetBase64BlockId(blockId); blockIDs.Add(blockIdEncoded); byte[] bytesToUpload = new byte[blockLength]; Array.Copy(file, blockId * blockSize, bytesToUpload, 0, blockLength); using (MemoryStream memoryStream = new MemoryStream(bytesToUpload, 0, blockLength)) { blob.PutBlock(blockIdEncoded, memoryStream, null, null, new BlobRequestOptions { RetryPolicy = new ExponentialRetry(TimeSpan.FromSeconds(2), 1) }); } blockId++; fileSize -= blockLength; } blob.PutBlockList(blockIDs); } private string GetBase64BlockId(int blockId) { return Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}", blockId.ToString("0000000")))); } private CloudBlobContainer GetContainerReference() { string connectionString = CloudConfigurationManager.GetSetting(ConnectionStringSettingName); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); CloudBlobContainer container = blobClient.GetContainerReference(ContainerName); container.CreateIfNotExists(); return container; } } } <file_sep>using System; using System.ComponentModel.DataAnnotations; namespace Vacations.Models { public class ProfileViewModel { public string EmployeeID { get; set; } [Display(Name = "work mail")] public string WorkEmail { get; set; } [Display(Name = "name")] public string Name { get; set; } [Display(Name = "surname")] public string Surname { get; set; } [Display(Name = "birth date")] public DateTime BirthDate { get; set; } [Display(Name = "personal mail")] public string PersonalMail { get; set; } [Display(Name = "skype")] public string Skype { get; set; } [Display(Name = "phone number")] public string PhoneNumber { get; set; } [Display(Name = "hire date")] public DateTime HireDate { get; set; } [Display(Name = "status")] public bool Status { get; set; } [Display(Name = "date of dismissal")] public DateTime? DateOfDismissal { get; set; } [Display(Name = "balance")] public int VacationBalance { get; set; } [Display(Name = "job title")] public string JobTitle { get; set; } [Display(Name = "team name")] public string TeamName { get; set; } [Display(Name = "team leader")] public string TeamLeader { get; set; } } }<file_sep>using System; namespace VacationsBLL.DTOs { public class RequestDTO { public string EmployeeID { get; set; } public string VacationID { get; set; } public string Name { get; set; } public string TeamName { get; set; } public string VacationDates { get; set; } public int Duration { get; set; } public int EmployeesBalance { get; set; } public string Status { get; set; } public DateTime Created { get; set; } public string ProcessedBy { get; set; } } } <file_sep>using IdentitySample.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using VacationsBLL.Interfaces; namespace IdentitySample.Controllers { public class AccountController : Controller { private IEmployeeService _employeeService; private IUserService _aspNetUserService; public AccountController(IEmployeeService employeeService, IRoleService roleService, IPageListsService pageListsService, IUserService userService) { _employeeService = employeeService; _aspNetUserService = userService; } private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } [HttpGet] [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } private ApplicationSignInManager _signInManager; public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model) { ViewData["DeniedLoginText"] = "DeniedLoginText"; ViewData["DeniedLoginBorder"] = "DeniedLoginBorder"; if (!ModelState.IsValid) { return View(model); } var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, false, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToAction("Index", "Profile"); case SignInStatus.Failure: default: ModelState.AddModelError("", "Invalid login attempt."); return View(model); } } [HttpGet] [AllowAnonymous] public async Task<ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null || !_aspNetUserService.AspNetUserExists(userId)) { return View("ErrorPage"); } var result = await UserManager.ConfirmEmailAsync(userId, code); return View(result.Succeeded ? "ConfirmEmail" : "ErrorPage"); } [HttpGet] [AllowAnonymous] public ActionResult ForgotPassword() { return View(); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { ViewData["response"] = "Ready! Please, check your email."; if (ModelState.IsValid) { var user = await UserManager.FindByEmailAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { return View("ForgotPasswordResponse"); } var email = new EmailService(); var employee = _employeeService.GetUserById(user.Id); var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code }, protocol: Request.Url.Scheme); await email.SendAsync(user.Email, employee.Name + " " + employee.Surname, "Restore password", "Please restore your password", "Please restore your password by clicking this <a href=\"" + callbackUrl + "\">link</a>."); } return View("ForgotPasswordResponse"); } [HttpGet] [AllowAnonymous] public ActionResult ForgotPasswordResponse() { return View(); } [HttpGet] [AllowAnonymous] public ActionResult ResetPassword(string code) { return code == null ? View("ErrorPage") : View(); } [HttpGet] [AllowAnonymous] public async Task<RedirectToRouteResult> ResetPasswordAndConfirmEmail(string codeToResetPassword, string codeToConfirmationEmail, string userId) { if (userId == null || codeToConfirmationEmail == null || !_aspNetUserService.AspNetUserExists(userId)) { return RedirectToAction("ErrorPage"); } var result = await UserManager.ConfirmEmailAsync(userId, codeToConfirmationEmail); return codeToResetPassword == null ? RedirectToAction("ErrorPage") : RedirectToAction("ResetPassword", new {code = codeToResetPassword}); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByEmailAsync(model.Email); if (user == null) { return RedirectToAction("Login", "Account"); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction("Login", "Account"); } AddErrors(result); return View(); } [HttpGet] public ActionResult LogOff() { AuthenticationManager.SignOut(); return RedirectToAction("Login", "Account"); } public ActionResult ErrorPage() { return View(); } #region Helpers private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } internal class ChallengeResult : HttpUnauthorizedResult { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } public ChallengeResult(string provider, string redirectUri, string userId) { LoginProvider = provider; RedirectUri = redirectUri; UserId = userId; } public string LoginProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); } } #endregion } }<file_sep>using System; using System.Collections.Generic; namespace VacationsBLL.DTOs { public class EmployeeDTO { public string EmployeeID { get; set; } public string Name { get; set; } public string Surname { get; set; } public DateTime BirthDate { get; set; } public string PersonalMail { get; set; } public string Skype { get; set; } public DateTime HireDate { get; set; } public bool Status { get; set; } public DateTime? DateOfDismissal { get; set; } public int VacationBalance { get; set; } public string JobTitleID { get; set; } public string PhoneNumber { get; set; } public string WorkEmail { get; set; } public ICollection<TeamDTO> EmployeesTeam { get; set; } public virtual ICollection<TeamDTO> Teams { get; set; } } } <file_sep>namespace WebJob { class Program { static void Main(string[] args) { var functions = new Functions(); functions.SendMessages().Wait(); } } }<file_sep>namespace VacationsBLL.Interfaces { public interface IValidateService { bool CheckEmail(string email); bool CheckEmailOwner(string email, string id); bool CheckTeamName(string teamName); bool CheckTeam(string teamName, string id); } }<file_sep>using System; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class RolesRepository: IRolesRepository { private readonly VacationsContext _context; public RolesRepository(VacationsContext dbContext) { _context = dbContext; } public AspNetRole[] Get(Func<AspNetRole, bool> whereCondition = null) { IQueryable<AspNetRole> baseCondition = _context.AspNetRoles; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public AspNetRole GetById(string id) { return _context.AspNetRoles.FirstOrDefault(x => x.Id == id); } public void Remove(string id) { var obj = _context.AspNetRoles.FirstOrDefault(x => x.Id == id); if (obj != null) { _context.AspNetRoles.Remove(obj); } _context.SaveChanges(); } public void Add(AspNetRole aspNetRole) { _context.AspNetRoles.Add(aspNetRole); _context.SaveChanges(); } } } <file_sep>using SimpleInjector; using SimpleInjector.Integration.Web; using SimpleInjector.Integration.Web.Mvc; using System.Web.Mvc; using VacationsBLL.Interfaces; using VacationsBLL.Services; using VacationsDAL.Contexts; using VacationsDAL.Interfaces; using VacationsDAL.Repositories; namespace VacationsBLL.SimpleInjectorConfig { public class SimpleInjectorConfig { public static void RegisterComponents() { var container = new Container(); container.Options.DefaultScopedLifestyle = new WebRequestLifestyle(); container.Register<ITeamRepository, TeamRepository>(Lifestyle.Scoped); container.Register<ITransactionRepository, TransactionRepository>(Lifestyle.Scoped); container.Register<ITransactionTypeRepository, TransactionTypeRepository>(Lifestyle.Scoped); container.Register<IVacationRepository, VacationRepository>(Lifestyle.Scoped); container.Register<IVacationStatusTypeRepository, VacationStatusTypeRepository>(Lifestyle.Scoped); container.Register<IUsersRepository, UsersRepository>(Lifestyle.Scoped); container.Register<IRolesRepository, RolesRepository>(Lifestyle.Scoped); container.Register<IEmployeeRepository, EmployeeRepository>(Lifestyle.Scoped); container.Register<IJobTitleRepository, JobTitleRepository>(Lifestyle.Scoped); container.Register<IVacationTypeRepository, VacationTypeRepository>(Lifestyle.Scoped); container.Register<VacationsContext>(Lifestyle.Scoped); container.Register<IRequestService, RequestService>(Lifestyle.Scoped); container.Register<IRoleService, RoleService>(Lifestyle.Scoped); container.Register<IUserService, UserService>(Lifestyle.Scoped); container.Register<IEmployeeService, EmployeeService>(Lifestyle.Scoped); container.Register<IPageListsService, PageListsService>(Lifestyle.Scoped); container.Register<IProfileDataService, ProfileDataService>(Lifestyle.Scoped); container.Register<ITeamService, TeamService>(Lifestyle.Scoped); container.Register<IRequestCreationService, RequestCreationService>(Lifestyle.Scoped); container.Register<IEmployeeListService, EmployeeListService>(Lifestyle.Scoped); container.Register<IPhotoUploadService, PhotoUploadService>(Lifestyle.Scoped); container.Register<IValidateService, ValidateService>(Lifestyle.Scoped); container.Register<IVacationService, VacationService>(Lifestyle.Scoped); container.Register<IEmailSendService, EmailSendService>(Lifestyle.Scoped); container.Verify(); DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container)); } } } <file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface IVacationRepository : IRepository<Vacation> { void Update(Vacation employee); } } <file_sep>using System; namespace VacationsBLL.DTOs { public class TransactionDTO { public string TransactionID { get; set; } public int BalanceChange { get; set; } public string Discription { get; set; } public string EmployeeID { get; set; } public DateTime TransactionDate { get; set; } public string TransactionTypeID { get; set; } } } <file_sep>using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Vacations.Models; using VacationsBLL.DTOs; using VacationsBLL.Enums; using VacationsBLL.Interfaces; using VacationsBLL.Services; using PagedList; namespace Vacations.Controllers { [Authorize(Roles = "TeamLeader")] public class TeamLeaderController : Controller { private const int requestPageSize = 14; private const int teamPageSize = 15; private const int employeePageSize = 4; private readonly IPageListsService _pageListsService; private readonly IEmployeeService _employeeService; private readonly IProfileDataService _profileDataService; private readonly IRequestService _requestProcessService; private readonly IEmployeeListService _employeeListService; private readonly ITeamService _teamService; private readonly IPhotoUploadService _photoUploadService; private readonly IRequestCreationService _requestCreationService; public TeamLeaderController( IProfileDataService profileDataService, IEmployeeService employeeService, IPageListsService pageListsService, IEmployeeListService employeeListService, IRequestService requestService, ITeamService teamService, IPhotoUploadService photoUploadService, IRequestCreationService requestCreationService) { _profileDataService = profileDataService; _employeeService = employeeService; _pageListsService = pageListsService; _employeeListService = employeeListService; _requestProcessService = requestService; _teamService = teamService; _photoUploadService = photoUploadService; _requestCreationService = requestCreationService; } public ActionResult EmployeesList(int page = 1, string searchKey = null) { ViewData["SearchKey"] = searchKey; ViewBag.EmployeeService = _employeeService; ViewBag.TeamService = _teamService; var employeeList = _employeeListService.EmployeeList(searchKey).Where(x => x.TeamDto.TeamLeadID == User.Identity.GetUserId()); return View(Mapper.MapCollection<EmployeeListDTO, EmployeeListViewModel>(employeeList.ToArray()).ToPagedList(page, employeePageSize)); } [HttpGet] public ActionResult Requests(int page = 1, string searchKey = null) { ViewData["SearchKey"] = searchKey; _requestProcessService.SetReviewerID(User.Identity.GetUserId()); var map = Mapper.MapCollection<RequestDTO, RequestViewModel>(_requestProcessService.GetRequestsForTeamLeader(searchKey)); var list = map.ToPagedList(page, requestPageSize); return View(list); } [HttpGet] public ActionResult TeamsList(string searchKey, int page = 1) { ViewData["SearchKey"] = searchKey; var result = new List<TeamListViewModel>(); var teams = _teamService.GetAllTeams(searchKey).Where(x=> x.TeamLeadID == User.Identity.GetUserId()); foreach (var teamListDto in teams) { var teamLead = _employeeService.GetUserById(teamListDto.TeamLeadID); result.Add(new TeamListViewModel { TeamID = teamListDto.TeamID, TeamName = teamListDto.TeamName, TeamLeadName = teamLead.Name + " " + teamLead.Surname, AmountOfEmployees = teamListDto.AmountOfEmployees }); } return View(result.ToPagedList(page,teamPageSize)); } [HttpGet] public ActionResult ViewTeamProfile(string id) { var team = _teamService.GetById(id); var employeesDTOs = _employeeService.GetEmployeesByTeamId(team.TeamID); var teamLead = _employeeService.GetUserById(team.TeamLeadID); var employees = Mapper.MapCollection<EmployeeDTO, EmployeeViewModel>(employeesDTOs.ToArray()); var result = new TeamProfileViewModel { TeamID = team.TeamID, TeamName = team.TeamName, TeamLeadName = teamLead.Name + " " + teamLead.Surname, TeamLeadID = team.TeamLeadID, Status = teamLead.Status, AmountOfEmployees = team.AmountOfEmployees, Employees = employees }; return View(result); } [HttpGet] public ActionResult ProcessPopupPartial(string id, bool isCalledFromList = false) { ViewData["isCalledFromList"] = isCalledFromList; var request = Mapper.Map<RequestProcessDTO, RequestProcessViewModel>(_requestProcessService.GetRequestDataById(id)); return PartialView("ProcessPopupPartial", request); } [HttpPost] public ActionResult ProcessPopupPartial(RequestProcessResultModel model) { if (ModelState.IsValid) { if (model.Result.Equals(VacationStatusTypeEnum.Approved.ToString())) { _requestProcessService.ApproveVacation(Mapper.Map<RequestProcessResultModel, RequestProcessResultDTO>(model)); } else { _requestProcessService.DenyVacation(Mapper.Map<RequestProcessResultModel, RequestProcessResultDTO>(model)); } } _requestProcessService.SetReviewerID(User.Identity.GetUserId()); return View("Requests", Mapper.MapCollection<RequestDTO, RequestViewModel>(_requestProcessService.GetRequestsForTeamLeader())); } [HttpGet] public ActionResult CreateRequestForEmployeePartial(string id) { ViewData["VacationTypesSelectList"] = _pageListsService.SelectVacationTypes(); var creationData = _requestCreationService.GetEmployeeDataForRequestByID(id); return PartialView("CreateRequestForEmployeePartial", Mapper.Map<RequestForEmployeeDTO, RequestForEmployeeViewModel>(creationData)); } [HttpPost] public ActionResult CreateRequestForEmployeePartial(RequestForEmployeeViewModel model) { _requestProcessService.SetReviewerID(User.Identity.GetUserId()); var vacation = Mapper.Map<RequestForEmployeeViewModel, VacationDTO>(model); vacation.Comment = model.Discription; vacation.VacationTypeID = Request.Params["VacationTypesSelectList"]; _requestCreationService.ForceVacationForEmployee(vacation); var request = Mapper.Map<VacationDTO, RequestProcessResultDTO>(vacation); request.Result = VacationStatusTypeEnum.Approved.ToString(); _requestProcessService.ApproveVacation(request); return RedirectToAction("EmployeesList", "TeamLeader"); } [HttpGet] public ActionResult EmployeeView(string id) { var employee = _employeeService.GetUserById(id); if (employee != null) { var model = Mapper.Map<EmployeeDTO, EmployeeViewModel>(employee); ViewData["Status"] = _employeeService.GetStatusByEmployeeId(model.EmployeeID); ViewData["JobTitle"] = _employeeService.GetJobTitleById(model.JobTitleID).JobTitleName; ViewData["Role"] = _employeeService.GetRoleByUserId(model.EmployeeID); return View(model); } return RedirectToAction("Requests", "TeamLeader"); } } }<file_sep>using System; namespace VacationsBLL.DTOs { public class RequestProcessDTO { public string EmployeeID { get; set; } public string VacationID { get; set; } public string EmployeeName { get; set; } public string JobTitle { get; set; } public string TeamName { get; set; } public string TeamLeadName { get; set; } public string VacationType { get; set; } public DateTime DateOfBegin { get; set; } public DateTime DateOfEnd { get; set; } public string Comment { get; set; } public int Duration { get; set; } public string Status { get; set; } public string ProcessedBy { get; set; } public int EmployeesBalance{ get; set; } } } <file_sep>namespace VacationsBLL.Enums { public enum VacationStatusTypeEnum { Approved, Denied, Pending } }<file_sep>using System; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class VacationStatusTypeRepository : IVacationStatusTypeRepository { private readonly VacationsContext _context; public VacationStatusTypeRepository(VacationsContext dbContext) { _context = dbContext; } public VacationStatusType[] Get(Func<VacationStatusType, bool> whereCondition = null) { IQueryable<VacationStatusType> baseCondition = _context.VacationStatusTypes; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public VacationStatusType GetById(string id) { return _context.VacationStatusTypes.FirstOrDefault(x => x.VacationStatusTypeID == id); } public VacationStatusType GetByType(string type) { return _context.VacationStatusTypes.FirstOrDefault(x => x.VacationStatusName.Equals(type)); } public void Remove(string id) { var obj = _context.VacationStatusTypes.FirstOrDefault(x => x.VacationStatusTypeID == id); if (obj != null) { _context.VacationStatusTypes.Remove(obj); _context.SaveChanges(); } } public void Add(VacationStatusType VacationStatusType) { _context.VacationStatusTypes.Add(VacationStatusType); _context.SaveChanges(); } } } <file_sep>namespace VacationsBLL.DTOs { public class TeamListDTO { public string TeamID { get; set; } public string TeamName { get; set; } public string TeamLeadID { get; set; } public int AmountOfEmployees { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Vacations.Models { public class EmployeeForListViewModel { public string EmployeeID { get; set; } public string Name { get; set; } public string Surname { get; set; } public int VacationBalance { get; set; } public string PhoneNumber { get; set; } public string WorkEmail { get; set; } public string CurrentVacationID { get; set; } } }<file_sep>using System; using System.ComponentModel.DataAnnotations; namespace Vacations.Models { public class ProfileVacationsViewModel { [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] public DateTime DateOfBegin { get; set; } [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] public DateTime DateOfEnd { get; set; } public string Comment { get; set; } public string VacationType { get; set; } public string Status { get; set; } public int Duration { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VacationsBLL.Interfaces { public interface IEmailSendService { Task SendAsync(string address, string name, string title, string plainTextContent, string message); } } <file_sep>using System; using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface IUsersRepository { AspNetUser[] Get(Func<AspNetUser, bool> condition = null); AspNetUser GetById(string id); AspNetUser GetByUserName(string email); } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class TeamRepository : ITeamRepository { private readonly VacationsContext _context; public TeamRepository(VacationsContext dbContext) { _context = dbContext; } public Team[] Get(Func<Team, bool> whereCondition = null) { IQueryable<Team> baseCondition = _context.Teams; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public Team GetById(string id) { return _context.Teams.FirstOrDefault(x => x.TeamID == id); } public Team GetByName(string name) { return _context.Teams.FirstOrDefault(x => x.TeamName == name); } public void Remove(string id) { var obj = _context.Teams.FirstOrDefault(x => x.TeamID == id); if (obj != null) { _context.Teams.Remove(obj); _context.SaveChanges(); } } public void RemoveEmployee(string EmployeeID, string TeamID) { var obj = _context.Teams.FirstOrDefault(x => x.TeamID == TeamID); if (obj != null) { var employee = obj.Employees.FirstOrDefault(x => x.EmployeeID == EmployeeID); if (employee != null) { obj.Employees.Remove(employee); _context.SaveChanges(); } } } public void AddEmployee(string EmployeeID, string TeamID) { var obj = _context.Teams.FirstOrDefault(x => x.TeamID == TeamID); if (obj != null) { var employee = _context.Employees.FirstOrDefault(x => x.EmployeeID == EmployeeID); if (employee != null) { obj.Employees.Add(employee); _context.SaveChanges(); } } } public void Add(Team team) { _context.Teams.Add(team); _context.SaveChanges(); } public void Update(Team team) { var obj = _context.Teams.FirstOrDefault(x => x.TeamID == team.TeamID); if (obj != null) { obj.TeamName = team.TeamName; obj.TeamLeadID = team.TeamLeadID; _context.SaveChanges(); } } public IEnumerable<Team> GetAll() { return _context.Teams.ToList(); } } } <file_sep>using System.Collections.Generic; using AutoMapper; namespace VacationsBLL.Services { public static class Mapper { public static TypeToMapTo Map<TypeToMapFrom, TypeToMapTo>(TypeToMapFrom model) { var mapper = new MapperConfiguration(cfg => cfg.CreateMap<TypeToMapFrom, TypeToMapTo>()).CreateMapper(); return mapper.Map<TypeToMapFrom, TypeToMapTo>(model); } public static TypeToMapTo[] MapCollection<TypeToMapFrom, TypeToMapTo>(TypeToMapFrom[] model) { var mapper = new MapperConfiguration(cfg => cfg.CreateMap<TypeToMapFrom, TypeToMapTo>()).CreateMapper(); return mapper.Map<TypeToMapFrom[], TypeToMapTo[]>(model); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using VacationsBLL.Interfaces; namespace Vacations.Controllers { public class RemoteValidationController : Controller { private IValidateService _validateService; public RemoteValidationController(IValidateService validateService) { _validateService = validateService; } public JsonResult ValidateEmail(string EmployeeID,string WorkEmail) { if (EmployeeID=="undefined") { if (_validateService.CheckEmail(WorkEmail)) { return Json(" is in use", JsonRequestBehavior.AllowGet); } return Json(true, JsonRequestBehavior.AllowGet); } if (_validateService.CheckEmail(WorkEmail) && _validateService.CheckEmailOwner(WorkEmail,EmployeeID)) { return Json(" is in use", JsonRequestBehavior.AllowGet); } return Json(true, JsonRequestBehavior.AllowGet); } public JsonResult ValidateTeamName(string TeamName, string TeamID) { if (TeamID == "undefined") { if (_validateService.CheckTeamName(TeamName)) { return Json(" is in use", JsonRequestBehavior.AllowGet); } return Json(true, JsonRequestBehavior.AllowGet); } if (_validateService.CheckTeamName(TeamName) && _validateService.CheckTeam(TeamName,TeamID)) { return Json(" is in use", JsonRequestBehavior.AllowGet); } return Json(true, JsonRequestBehavior.AllowGet); } } }<file_sep>using System; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class TransactionTypeRepository : ITransactionTypeRepository { private readonly VacationsContext _context; public TransactionTypeRepository(VacationsContext dbContext) { _context = dbContext; } public TransactionType[] Get(Func<TransactionType, bool> whereCondition = null) { IQueryable<TransactionType> baseCondition = _context.TransactionTypes; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public TransactionType GetById(string id) { return _context.TransactionTypes.FirstOrDefault(x => x.TransactionTypeID == id); } public void Remove(string id) { var obj = _context.TransactionTypes.FirstOrDefault(x => x.TransactionTypeID == id); if (obj != null) { _context.TransactionTypes.Remove(obj); _context.SaveChanges(); } } public void Add(TransactionType TransactionType) { _context.TransactionTypes.Add(TransactionType); _context.SaveChanges(); } public TransactionType GetByType(string type) { return _context.TransactionTypes.FirstOrDefault(x => x.TransactionTypeName.Equals(type)); } } } <file_sep>using IdentitySample.Models; using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using System.Web; using IdentitySample.Models; using Microsoft.AspNet.Identity; using Vacations.Models; using VacationsBLL.DTOs; using VacationsBLL.Enums; using VacationsBLL.Interfaces; using VacationsBLL.Services; namespace Vacations.Subservices { public static class TeamCreationService { public static void RegisterTeam(TeamViewModel model, string employees, IEmployeeService employeeService, ITeamService teamService, ApplicationUserManager userManager) { using (TransactionScope transaction = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { teamService.CreateTeam(Mapper.Map<TeamViewModel, TeamDTO>(new TeamViewModel { TeamLeadID = model.TeamLeadID, TeamID = model.TeamID, TeamName = model.TeamName })); string members = employees; if (members != null) { var result = members.Split(','); foreach (var employeeId in result) { if (employeeId != model.TeamLeadID) { employeeService.AddToTeam(employeeId, model.TeamID); } } } var userRole = userManager.GetRoles(model.TeamLeadID).First(); if (userRole == RoleEnum.Employee.ToString()) { userManager.RemoveFromRole(model.TeamLeadID, userRole); userManager.AddToRoles(model.TeamLeadID, RoleEnum.TeamLeader.ToString()); } transaction.Complete(); } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using VacationsBLL.DTOs; using VacationsBLL.Interfaces; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL.Services { public class TeamService : ITeamService { private ITeamRepository _teams; public TeamService(ITeamRepository teams) { _teams = teams; } public void CreateTeam(TeamDTO team) { _teams.Add(Mapper.Map<TeamDTO, Team>(team)); } public IEnumerable<TeamListDTO> GetAllTeams(string searchKey = null) { Team[] teams = null; var result = new List<TeamListDTO>(); if (searchKey != null) { bool whereLinq(Team team) => team.TeamName.ToLower().Contains(searchKey.ToLower()) || team.TeamName.ToLower().Contains(searchKey.ToLower()); teams = _teams.Get(whereLinq); } else { teams = _teams.Get(); } foreach (var team in teams) { result.Add(new TeamListDTO { TeamID = team.TeamID, TeamLeadID = team.TeamLeadID, TeamName = team.TeamName, AmountOfEmployees = team.Employees.Count } ); } return result; } public TeamListDTO GetById(string id) { var team = _teams.GetById(id); if(team != null) { var result = new TeamListDTO { TeamID = team.TeamID, TeamLeadID = team.TeamLeadID, TeamName = team.TeamName, AmountOfEmployees = team.Employees.Count }; return result; } return new TeamListDTO(); } public void DeleteTeam(string teamId) { _teams.Remove(teamId); } public TeamDTO GetTeamById(string id) { return Mapper.Map<Team, TeamDTO>(_teams.GetById(id)); } public void UpdateTeamInfo(TeamDTO team) { _teams.Update(Mapper.Map<TeamDTO, Team>(team)); } } } <file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface IVacationStatusTypeRepository : IRepository<VacationStatusType> { VacationStatusType GetByType(string type); } } <file_sep>using System.Web; namespace VacationsBLL.Interfaces { public interface IPhotoUploadService { void UploadPhoto(HttpPostedFileBase photo, string id); } }<file_sep>using System; namespace VacationsBLL.DTOs { public class ProfileVacationDTO { public DateTime DateOfBegin { get; set; } public DateTime DateOfEnd { get; set; } public string Comment { get; set; } public string VacationType { get; set; } public int Duration { get; set; } public string Status { get; set; } public DateTime Created { get; set; } } } <file_sep>using System; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class EmployeeRepository : IEmployeeRepository { private readonly VacationsContext _context; public EmployeeRepository(VacationsContext dbContext) { _context = dbContext; } public Employee[] Get(Func<Employee,bool> whereCondition = null) { IQueryable<Employee> baseCondition = _context.Employees.Include(x=> x.Teams); return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public Employee GetById(string id) { return _context.Employees.FirstOrDefault(x => x.EmployeeID == id); } public Employee GetByEmail(string email) { return _context.Employees.FirstOrDefault(x => x.WorkEmail == email); } public void Remove(string id) { var obj = _context.Employees.FirstOrDefault(x => x.EmployeeID == id); if (obj != null) { _context.Employees.Remove(obj); _context.SaveChanges(); } } public void Add(Employee employee) { try { _context.Employees.Add(employee); _context.SaveChanges(); } catch (DbUpdateException e) { } } public void Update() { _context.SaveChanges(); } } } <file_sep>using System.Collections.Generic; using IdentitySample.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace Vacations.Migrations { using System.Data.Entity.Migrations; internal sealed class Configuration : DbMigrationsConfiguration<ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(ApplicationDbContext context) { // This method will be called after migrating to the latest version. //Add-Migration InitialMigrations -IgnoreChanges //This should generate a blank "InitialMigration" file.Now, add any desired //changes to the class you want.Once changes are added, run the update command again: //update-database -verbose //Now the automatic migration will be applied and the table will be altered with your changes. // Initialize default identity roles var store = new RoleStore<IdentityRole>(context); var manager = new RoleManager<IdentityRole>(store); // RoleTypes is a class containing constant string values for different roles var identityRoles = new List<IdentityRole> { new IdentityRole() {Name = "Administrator"}, new IdentityRole() {Name = "TeamLeader"}, new IdentityRole() {Name = "Employee"} }; foreach (var role in identityRoles) { manager.Create(role); } // Initialize default user var admin = new ApplicationUser { Email = "<EMAIL>", UserName = "<EMAIL>" }; context.Users.AddOrUpdate(u => u.UserName, admin); var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context)); roleManager.Create(new IdentityRole("Administrator")); var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context)); userManager.Create(admin, "admin321"); userManager.AddToRole(admin.Id, "Administrator"); } } } <file_sep>using System.Collections.Generic; namespace VacationsBLL.DTOs { public class UserDTO { public string Id { get; set; } public string Email { get; set; } public ICollection<RoleDTO> AspNetRoles { get; set; } } } <file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface IEmployeeRepository : IRepository<Employee> { Employee GetByEmail(string email); void Update(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Vacations.Models { public class EmployeeListTeamViewModel { public string TeamID { get; set; } public string TeamName { get; set; } public string TeamLeadID { get; set; } } }<file_sep>using System; using System.Configuration; using System.Linq; using System.Threading.Tasks; using SendGrid; using SendGrid.Helpers.Mail; using VacationsBLL.Enums; using VacationsDAL.Contexts; using VacationsDAL.Entities; namespace WebJob { public class Functions { private readonly string SendGridApiKeyName = "SendGridApiKey"; private bool IsApproved(VacationsContext context, string id) { var obj = context.VacationStatusTypes.FirstOrDefault(x => x.VacationStatusTypeID == id); return obj != null && obj.VacationStatusName == VacationStatusTypeEnum.Approved.ToString(); } private async Task SendAsync(string address, string name, string title, string plainTextContent, string message) { var apiKey = ConfigurationManager.AppSettings[SendGridApiKeyName]; var client = new SendGridClient(apiKey); var from = new EmailAddress("<EMAIL>", "Softheme Vacations"); var subject = title; var to = new EmailAddress(address, name); var htmlContent = "<strong>" + message + "</strong>"; var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); var response = await client.SendEmailAsync(msg); } private Employee GetUserById(VacationsContext context, string id) { var obj = context.Employees.FirstOrDefault(x => x.EmployeeID == id); return obj; } private async Task SendMessageBeforeVacations(VacationsContext context) { var date = DateTime.Today; var vacations = context.Vacations.ToList(); if (vacations.Count != 0) { foreach (var vacation in vacations) { if (vacation.DateOfBegin.AddDays(-14).ToString("ddMMyyyy").Equals(date.ToString("ddMMyyyy")) && IsApproved(context, vacation.VacationStatusTypeID)) { var employee = GetUserById(context, vacation.EmployeeID); var team = employee.EmployeesTeam.FirstOrDefault(); if (team != null) { var teamLeader = GetUserById(context, team.TeamLeadID); await SendAsync(teamLeader.WorkEmail, teamLeader.Name + " " + teamLeader.Surname, "Soon the vacation of your employee", employee.Name + " " + employee.Surname, employee.Name + " " + employee.Surname + " will go on vacation " + vacation.DateOfBegin.ToString("dd-MM-yyyy")); } } } } } private async Task SendMessageForBirthdays(VacationsContext context) { var date = DateTime.Today; var employees = context.Employees.Where(x => !x.EmployeesTeam.Count.Equals(0)).ToList(); if (employees.Count != 0) { foreach (var employee in employees) { var yesterday = employee.BirthDate.AddDays(-1); if (yesterday.ToString("ddMM").Equals(date.ToString("ddMM"))) { var employeeTeam = employee.EmployeesTeam.FirstOrDefault(); if (employeeTeam != null) { var teamLeader = GetUserById(context, employeeTeam.TeamLeadID); await SendAsync(teamLeader.WorkEmail, teamLeader.Name + " " + teamLeader.Surname, "The birthday of your employee tomorrow", employee.Name + " " + employee.Surname, employee.Name + " " + employee.Surname + " has a birthday tomorrow"); } } } } } public async Task SendMessages() { using (var context = new VacationsContext()) { await SendMessageForBirthdays(context); await SendMessageBeforeVacations(context); } } } } <file_sep>using System; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using VacationsBLL.SimpleInjectorConfig; namespace IdentitySample { // Note: For instructions on enabling IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=301868 public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); SimpleInjectorConfig.RegisterComponents(); } protected void Application_Error(object sender, EventArgs e) { HttpContext httpContext = HttpContext.Current; if (httpContext != null) { RequestContext requestContext = ((MvcHandler)httpContext.CurrentHandler).RequestContext; Exception exception = Server.GetLastError(); } Response.Clear(); Context.Response.Redirect("~/Account/ErrorPage"); } } } <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace VacationsDAL.Entities { [Table("Team")] public partial class Team { public Team() { Employees = new HashSet<Employee>(); } public string TeamID { get; set; } [Required] [StringLength(50)] public string TeamName { get; set; } [Required] [StringLength(128)] public string TeamLeadID { get; set; } public virtual Employee Employee { get; set; } public virtual ICollection<Employee> Employees { get; set; } } } <file_sep>using IdentitySample.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using System; using System.Web; using System.Web.Mvc; using VacationsBLL.Enums; using Vacations.Models; using VacationsBLL.DTOs; using VacationsBLL.Interfaces; using VacationsBLL.Services; using PagedList; namespace Vacations.Controllers { [Authorize(Roles = "Administrator, Employee, TeamLeader")] public class ProfileController : Controller { private const int pageSize = 9; private readonly IPageListsService _pageListsService; private IProfileDataService _profileDataService; private IEmployeeService _employeeService; private IRequestCreationService _requestCreationService; public ProfileController(IProfileDataService profileDataService, IEmployeeService employeesService, IPageListsService pageListsService, IRequestCreationService requestCreationService) { _profileDataService = profileDataService; _employeeService = employeesService; _pageListsService = pageListsService; _requestCreationService = requestCreationService; } #region IdentityProps private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private ApplicationUserManager _userManager; public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } private ApplicationSignInManager _signInManager; public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } #endregion [HttpGet] [Authorize] public ActionResult Index(int page = 1) { var a = User.Identity.GetUserId(); var userData = new UserViewModel { ProfileData = Mapper.Map<ProfileDTO, ProfileViewModel>(_profileDataService.GetUserData(User.Identity.GetUserId())), VacationBalanceData = Mapper.Map<VacationBalanceDTO, VacationBalanceViewModel>( _profileDataService.GetUserVacationBalance(User.Identity.GetUserId())), VacationsData = Mapper.MapCollection<ProfileVacationDTO, ProfileVacationsViewModel>( _profileDataService.GetUserVacationsData(User.Identity.GetUserId())).ToPagedList(page,pageSize) }; return View("MyProfile", userData); } [HttpGet] public ActionResult RequestVacation() { ViewData["VacationTypesSelectList"] = _pageListsService.SelectVacationTypes(); var requestVacationData = new RequestVacationViewModel { ProfileData = Mapper.Map<ProfileDTO, ProfileViewModel>(_profileDataService.GetUserData(User.Identity.GetUserId())), VacationBalanceData = Mapper.Map<VacationBalanceDTO, VacationBalanceViewModel>( _profileDataService.GetUserVacationBalance(User.Identity.GetUserId())), RequestCreationData = new RequestCreationViewModel() }; return View(requestVacationData); } [HttpPost] public ActionResult RequestVacation(RequestCreationViewModel model) { if (ModelState.IsValid) { model.EmployeeID = User.Identity.GetUserId(); model.VacationID = Guid.NewGuid().ToString(); model.VacationTypeID = Request.Params["VacationTypesSelectList"]; model.VacationStatusTypeID = _requestCreationService.GetStatusIdByType(VacationStatusTypeEnum.Pending.ToString()); model.Created = DateTime.UtcNow; _requestCreationService.CreateVacation(Mapper.Map<RequestCreationViewModel, VacationDTO>(model)); return RedirectToAction("Index","Profile"); } else { return RedirectToAction("Index", "Profile"); } } [HttpGet] public ActionResult LogOff() { AuthenticationManager.SignOut(); return RedirectToAction("Login", "Account"); } } }<file_sep>namespace VacationsBLL.DTOs { public class TeamDTO { public string TeamID { get; set; } public string TeamName { get; set; } public string TeamLeadID { get; set; } } } <file_sep>using System; using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IRequestCreationService { void CreateVacation(VacationDTO vacation); string GetStatusIdByType(string type); RequestForEmployeeDTO GetEmployeeDataForRequestByID(string id); void ForceVacationForEmployee(VacationDTO request); } }<file_sep>using System; namespace VacationsBLL.DTOs { public class RequestProcessResultDTO { public string VacationID { get; set; } public int Duration { get; set; } public string Discription { get; set; } public string EmployeeID { get; set; } public string Result { get; set; } public DateTime DateOfBegin { get; set; } public DateTime DateOfEnd { get; set; } } } <file_sep>using System; using System.Web.Mvc; namespace VacationsBLL.Interfaces { public interface IPageListsService { SelectListItem[] SelectEditRoles(string editValue); SelectListItem[] SelectEditJobTitles(string editValue); SelectListItem[] SelectEditStatuses(string editValue); SelectListItem[] EmployeesList(string editValue); SelectListItem[] SelectRoles(); SelectListItem[] SelectJobTitles(); SelectListItem[] SelectStatuses(); SelectListItem[] SelectVacationTypes(); SelectListItem[] EmployeesList(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Vacations.Models { public class TeamProfileViewModel { public string TeamID { get; set; } public string TeamName { get; set; } public string TeamLeadName { get; set; } public string TeamLeadID { get; set; } public bool Status { get; set; } public int AmountOfEmployees { get; set; } public IEnumerable<EmployeeViewModel> Employees { get; set; } } }<file_sep>using System; using System.Linq; using VacationsDAL.Contexts; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsDAL.Repositories { public class UsersRepository : IUsersRepository { private readonly VacationsContext _context; public UsersRepository(VacationsContext context) { _context = context; } public AspNetUser[] Get(Func<AspNetUser, bool> whereCondition = null) { IQueryable<AspNetUser> baseCondition = _context.AspNetUsers; return whereCondition == null ? baseCondition.ToArray() : baseCondition.Where(whereCondition).ToArray(); } public AspNetUser GetById(string id) { return _context.AspNetUsers.FirstOrDefault(x => x.Id == id); } public AspNetUser GetByUserName(string email) { return _context.AspNetUsers.FirstOrDefault(x => x.UserName.Equals(email)); } } } <file_sep>using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace VacationsDAL.Entities { [Table("JobTitle")] public partial class JobTitle { public JobTitle() { Employees = new HashSet<Employee>(); } public string JobTitleID { get; set; } [Column("JobTitle")] [StringLength(50)] public string JobTitleName { get; set; } public virtual ICollection<Employee> Employees { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VacationsBLL.Enums; namespace VacationsBLL.Functions { public static class FunctionHelper { public static int VacationSortFunc(string statusType) { if (statusType.Equals(VacationStatusTypeEnum.Pending.ToString())) { return 0; } else { return 1; } } public static int EmployeeSortFunc(string teamName) { if (!teamName.Equals("Empty")) { return 0; } else { return 1; } } } } <file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface IRolesRepository : IRepository<AspNetRole> { } } <file_sep>using VacationsBLL.Interfaces; using VacationsDAL.Interfaces; using VacationsBLL.DTOs; using VacationsDAL.Entities; using System.Linq; using System.Transactions; using System; using VacationsBLL.Enums; namespace VacationsBLL.Services { public class RequestCreationService : IRequestCreationService { private const string Empty = "None"; private IVacationRepository _vacations; private IJobTitleRepository _jobTitles; private IEmployeeRepository _employees; private IVacationStatusTypeRepository _vacationStatusTypes; private IEmailSendService _emailService; public string GetStatusIdByType(string type) { return _vacationStatusTypes.GetByType(type).VacationStatusTypeID; } public RequestCreationService(IVacationRepository vacations, IVacationStatusTypeRepository vacationStatusTypes, IEmployeeRepository employees, IEmailSendService emailService, IJobTitleRepository jobTitles) { _vacations = vacations; _vacationStatusTypes = vacationStatusTypes; _employees = employees; _emailService = emailService; _jobTitles = jobTitles; } public void CreateVacation(VacationDTO vacation) { using(TransactionScope scope = new TransactionScope()) { _vacations.Add(Mapper.Map<VacationDTO, Vacation>(vacation)); var employee = _employees.GetById(vacation.EmployeeID); if (employee.EmployeesTeam.Count > 0) { var team = employee.EmployeesTeam.First(); var teamLead = _employees.GetById(team.TeamLeadID); _emailService.SendAsync(teamLead.WorkEmail, $"{teamLead.Name} {teamLead.Surname}", "Vacation request.", "Employee has requested a vacation.", $"{teamLead.Name} {teamLead.Surname}, your employee, {employee.Name} {teamLead.Surname}, has requested a vacation from {vacation.DateOfBegin.ToString("dd-MM-yyyy")} to {vacation.DateOfEnd.ToString("dd-MM-yyyy")}. Please, check it."); } scope.Complete(); } } public void ForceVacationForEmployee(VacationDTO request) { request.VacationID = Guid.NewGuid().ToString(); request.VacationStatusTypeID = GetStatusIdByType(VacationStatusTypeEnum.Pending.ToString()); request.Created = DateTime.UtcNow; CreateVacation(request); } public RequestForEmployeeDTO GetEmployeeDataForRequestByID(string id) { var employee = _employees.GetById(id); if (employee != null) { var jobTitle = _jobTitles.GetById(employee.JobTitleID).JobTitleName; var request = new RequestForEmployeeDTO { EmployeeID = employee.EmployeeID, EmployeeName = string.Format($"{employee.Name} {employee.Surname}"), JobTitle = jobTitle, TeamLeadName = employee.EmployeesTeam.Count.Equals(0) ? Empty : _employees.GetById(employee.EmployeesTeam.First().TeamLeadID).Name, TeamName = employee.EmployeesTeam.Count.Equals(0) ? Empty : employee.EmployeesTeam.First().TeamName, }; return request; } else { return new RequestForEmployeeDTO(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BalanceResetWebJob { class Program { static void Main(string[] args) { var functions = new Functions(); functions.UpdateBalance(); } } } <file_sep>using VacationsDAL.Entities; namespace VacationsDAL.Interfaces { public interface ITransactionTypeRepository : IRepository<TransactionType> { TransactionType GetByType(string type); } } <file_sep>using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace Vacations.Models { public class TeamViewModel { public string TeamID { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "team name")] [Remote("ValidateTeamName", "RemoteValidation", AdditionalFields = "TeamID")] [StringLength(50, ErrorMessage = " should be shorter.")] public string TeamName { get; set; } public string TeamLeadID { get; set; } } }<file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Configuration; using System.Linq; using System.Web; namespace Vacations.Models { public class RequestCreationViewModel { [StringLength(128)] public string VacationID { get; set; } [StringLength(128)] public string EmployeeID { get; set; } [Required] [Display(Name = "From")] [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] public DateTime DateOfBegin { get; set; } [Required] [Display(Name = "To")] [DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)] public DateTime DateOfEnd { get; set; } [StringLength(100)] public string Comment { get; set; } [StringLength(128)] public string VacationTypeID { get; set; } [StringLength(128)] public string VacationStatusTypeID { get; set; } [Required] [Range(1, 28, ErrorMessage = " should be from 1 to 28.")] public int Duration { get; set; } [Column(TypeName = "date")] public DateTime Created { get; set; } } }<file_sep>using System; namespace VacationsBLL.DTOs { public class ProfileDTO { public string EmployeeID { get; set; } public string WorkEmail { get; set; } public string Name { get; set; } public string Surname { get; set; } public DateTime BirthDate { get; set; } public string PersonalMail { get; set; } public string Skype { get; set; } public string PhoneNumber { get; set; } public DateTime HireDate { get; set; } public bool Status { get; set; } public DateTime? DateOfDismissal { get; set; } public int VacationBalance { get; set; } public string JobTitle { get; set; } public string TeamName { get; set; } public string TeamLeader{ get; set; } } } <file_sep>using System.Configuration; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using SendGrid; using SendGrid.Helpers.Mail; using VacationsBLL.Interfaces; namespace VacationsBLL.Services { public class EmailSendService: IEmailSendService { private readonly string SendGridApiKeyName = "SendGridApiKey"; public async Task SendAsync(string address, string name, string title, string plainTextContent, string message) { var apiKey = ConfigurationManager.AppSettings[SendGridApiKeyName]; var client = new SendGridClient(apiKey); var from = new EmailAddress("<EMAIL>", "Softheme Vacations"); var subject = title; var to = new EmailAddress(address, name); var htmlContent = "<strong>" + message + "</strong>"; var msg = MailHelper.CreateSingleEmail(from, to, subject, plainTextContent, htmlContent); var response = await client.SendEmailAsync(msg); } } } <file_sep>using System.Collections.Generic; using VacationsBLL.DTOs; namespace VacationsBLL.Interfaces { public interface IEmployeeListService { List<EmployeeListDTO> EmployeeList(string searchKey = null); } }<file_sep>using System; using System.ComponentModel.DataAnnotations; using System.Web; using System.Web.Mvc; namespace Vacations.Models { public class EmployeeViewModel { public string EmployeeID { get; set; } [Required(ErrorMessage =" required field")] [EmailAddress(ErrorMessage =" invalid email")] [Display(Name = "work email")] [Remote("ValidateEmail", "RemoteValidation",AdditionalFields = "EmployeeID")] [StringLength(200, ErrorMessage = " should be shorter.")] public string WorkEmail { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "name")] [StringLength(20, ErrorMessage = " should be shorter.")] public string Name { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "surname")] [StringLength(30, ErrorMessage = " should be shorter.")] public string Surname { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "date of birth")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime BirthDate { get; set; } [Required(ErrorMessage =" required field")] [EmailAddress(ErrorMessage = " invalid email")] [Display(Name = "personal email")] [StringLength(256, ErrorMessage = " should be shorter.")] public string PersonalMail { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "phone number")] public string PhoneNumber { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "skype")] [StringLength(60, ErrorMessage = " should be shorter.")] public string Skype { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "hire date")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime HireDate { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "status")] public bool Status { get; set; } [Display(Name = "date of dismissal")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime? DateOfDismissal { get; set; } [Required(ErrorMessage =" required field")] [Display(Name = "days in vacation")] [Range(1,28, ErrorMessage = " should be from 1 to 28.")] public int VacationBalance { get; set; } [Display(Name = "job title")] public string JobTitleID { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Vacations.Models { public class RequestViewModel { public string EmployeeID { get; set; } public string VacationID { get; set; } public string Name { get; set; } public string TeamName { get; set; } public string VacationDates { get; set; } public int Duration { get; set; } public int EmployeesBalance { get; set; } public string Status { get; set; } public DateTime Created { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Transactions; using VacationsBLL.DTOs; using VacationsBLL.Enums; using VacationsBLL.Interfaces; using VacationsBLL.Services; using VacationsDAL.Entities; using VacationsDAL.Interfaces; namespace VacationsBLL { public class EmployeeService : IEmployeeService { private const string Empty = "None"; private IEmployeeRepository _employees; private IJobTitleRepository _jobTitles; private ITeamRepository _teams; private IRolesRepository _roles; private IUsersRepository _users; private ITransactionTypeRepository _transactionTypes; private ITransactionRepository _transactions; public EmployeeService(IEmployeeRepository employees, IJobTitleRepository jobTitles, ITeamRepository teams, IUsersRepository users, IRolesRepository roles, ITransactionTypeRepository transactionTypes, ITransactionRepository transactions) { _employees = employees; _jobTitles = jobTitles; _teams = teams; _roles = roles; _users = users; _transactionTypes = transactionTypes; _transactions = transactions; } public void Create(EmployeeDTO employee) { _employees.Add(Mapper.Map<EmployeeDTO, Employee>(employee)); } public EmployeeDTO GetUserById(string id) { return Mapper.Map<Employee, EmployeeDTO>(_employees.GetById(id)); } public JobTitleDTO GetJobTitleById(string id) { return Mapper.Map<JobTitle,JobTitleDTO>(_jobTitles.GetById(id)); } public string GetRoleByUserId(string id) { return _roles.GetById(_users.GetById(id).AspNetRoles.First().Id).Name; } public string GetStatusByEmployeeId(string id) { return _employees.GetById(id).Status.Equals(true) ? "Active" : "Fired"; } public List<JobTitleDTO> GetJobTitles() { var jobTitles = _jobTitles.Get(); return jobTitles.Select(jobTitle => Mapper.Map<JobTitle, JobTitleDTO>(jobTitle)).ToList(); } public string GetJobTitleIdByName(string jobTitleName) { return _jobTitles.Get().FirstOrDefault(x => x.JobTitleName.Equals(jobTitleName)).JobTitleID; } public void UpdateEmployee(EmployeeDTO employee) { var employeeToUpdate = _employees.GetById(employee.EmployeeID); MapChanges(employeeToUpdate, employee); _employees.Update(); } public void UpdateEmployeeBalance(EmployeeDTO employee, string comment) { using (TransactionScope scope = new TransactionScope()) { var employeeToUpdate = _employees.GetById(employee.EmployeeID); var transaction = new VacationsDAL.Entities.Transaction { BalanceChange = employee.VacationBalance-employeeToUpdate.VacationBalance, Discription = comment, EmployeeID = employeeToUpdate.EmployeeID, TransactionDate = DateTime.UtcNow, TransactionTypeID = _transactionTypes.GetByType(TransactionTypeEnum.ForceBalanceChangeTransaction.ToString()).TransactionTypeID, TransactionID = Guid.NewGuid().ToString() }; employeeToUpdate.VacationBalance = employee.VacationBalance; _employees.Update(); _transactions.Add(transaction); scope.Complete(); } } public BalanceChangeDTO GetEmployeeDataForBalanceChange(string id) { var employee = _employees.GetById(id); var jobTitle = _jobTitles.GetById(employee.JobTitleID).JobTitleName; var employeeData = new BalanceChangeDTO { EmployeeID = employee.EmployeeID, EmployeeName = $"{employee.Name} {employee.Surname}", JobTitle = jobTitle, TeamLeadName = employee.EmployeesTeam.Count.Equals(0) ? Empty : _employees.GetById(employee.EmployeesTeam.First().TeamLeadID).Name, TeamName = employee.EmployeesTeam.Count.Equals(0) ? Empty : employee.EmployeesTeam.First().TeamName, Balance = employee.VacationBalance }; return employeeData; } public string GetTeamNameById(string id) { return _teams.GetById(id).TeamName; } public IEnumerable<EmployeeDTO> GetAll() { return Mapper.MapCollection<Employee, EmployeeDTO>(_employees.Get()); } public void AddToTeam(string EmployeeID, string TeamID) { var team = _teams.GetById(TeamID); var employee = _employees.GetById(EmployeeID); _teams.AddEmployee(EmployeeID, TeamID); } public void RemoveFromTeam(string EmployeeID, string TeamID) { var team = _teams.GetById(TeamID); var employee = _employees.GetById(EmployeeID); _teams.RemoveEmployee(EmployeeID, TeamID); } public IEnumerable<EmployeeDTO> GetAllFreeEmployees() { return Mapper.MapCollection<Employee, EmployeeDTO>(_employees.Get(x => x.EmployeesTeam.Count == 0).ToArray()); } public IEnumerable<EmployeeDTO> GetEmployeesByTeamId(string id) { var result = new List<EmployeeDTO>(); var employees = _employees.Get().ToList(); foreach (var employee in employees) { foreach (var team in employee.EmployeesTeam) { if (team.TeamID == id) { result.Add(Mapper.Map<Employee, EmployeeDTO>(employee)); break; } } } return result; } private void MapChanges(Employee entity, EmployeeDTO changes) { var entityChanges = Mapper.Map<EmployeeDTO, Employee>(changes); entity.BirthDate = entityChanges.BirthDate; entity.DateOfDismissal = entityChanges.DateOfDismissal; entity.EmployeeID = entityChanges.EmployeeID; entity.HireDate = entityChanges.HireDate; entity.JobTitleID = entityChanges.JobTitleID; entity.Name = entityChanges.Name; entity.PersonalMail = entityChanges.PersonalMail; entity.PhoneNumber = entityChanges.PhoneNumber; entity.Skype = entityChanges.Skype; entity.Status = entityChanges.Status; entity.Surname = entityChanges.Surname; entity.WorkEmail = entityChanges.WorkEmail; } } }
9760ea605741f3920d8f961e32b9900c18d2e97c
[ "C#" ]
106
C#
maximkhanin/VacationProject
a4006bbe33fe0ab475d98ad0d26e9bf888548975
5d5da72d3b29270c4d87c7d5a3fa43aee81c9631
refs/heads/master
<file_sep># MPOF Merge Part Of File Allows replacing the text between specified tags by the content of a separate file. <file_sep>''' Created on 29 juill. 2019 @author: david.larochelle ''' import sys, getopt if __name__ == '__main__': pass # default value StartIdentifier = "" EndIdentifier = "" FileToInsert = "" BaseFile = "" OutputFile = "" try: opts, args = getopt.getopt(sys.argv[1:],"hs:e:i:f:o:") except getopt.GetoptError: print("MergePartOfFile: Replaces the text between specified tags by the content of a separate file.") print('MPOF.py -s StartIdentifier -e EndIdentifier -f BaseFile -i FileToInsert -o OutputFile') sys.exit(2) for opt, arg in opts: if opt == '-h': print("MergePartOfFile: Replaces the text between specified tags by the content of a separate file.") print('MPOF.py -s StartIdentifier -e EndIdentifier -f BaseFile -i FileToInsert -o OutputFile') sys.exit() elif opt in ("-s"): StartIdentifier = str(arg) elif opt in ("-e"): EndIdentifier = str(arg) elif opt in ("-i"): FileToInsert = str(arg) elif opt in ("-f"): BaseFile = str(arg) elif opt in ("-o"): OutputFile = str(arg) import os if (FileToInsert == "" or BaseFile == "" or StartIdentifier == "" or EndIdentifier == ""): print("Missing arguments. Aborting.") sys.exit() # If Outputfile is not provided, save changes in BaseFile if (OutputFile == ""): OutputFile = BaseFile import re # Read Input file try: f = open(FileToInsert, 'r') InputStream = f.read() f.close() except: print("Could not read input file " + FileToInsert) sys.exit() # Re-insert tags to input stream. InputStream = StartIdentifier + "\r\n" + InputStream + "\r\n" + EndIdentifier # Read Output file try: f = open(BaseFile, 'r') OutputStream = f.read() f.close() except: print("Could not read output file " + BaseFile) sys.exit() # Create regular expression pattern chop = re.compile(StartIdentifier+'.*?'+EndIdentifier, re.DOTALL) # Chop text between #chop-begin and #chop-end data_chopped = chop.sub(InputStream, OutputStream) # Test if changes were done successfully if (data_chopped == OutputStream): print("No tags found in basefile. Aborting.") sys.exit() # Save result try: f = open(OutputFile, 'w') f.write(data_chopped) f.close() except: print("Could not write to file " + BaseFile + ". Aborting.") sys.exit() print ("Changes successfull to file "+ OutputFile)
df91d9c445c9584ba1b562b548cadde01003ce8b
[ "Markdown", "Python" ]
2
Markdown
laroch02/MPOF
a00cdfc9b22cf8b4c9032393d8fff63defd8597e
2cb86b94f908e33691b2823c1594b2fac1040afa
refs/heads/master
<repo_name>kgersen/blackbox-prom-grafana<file_sep>/run.sh docker-compose --project-name prom -f bb-traefik-prom-grafana-stack-compose.yml up -d <file_sep>/ipv6.sh docker network connect bridge prom_blackblox <file_sep>/README.md #Arch Linux pacman -S prometheus-node-exporter sudo vi /etc/conf.d/prometheus-node-exporter NODE_EXPORTER_ARGS="--web.listen-address=ip-lan:9100 --collector.filesystem.ignored-mount-points='^/(sys|proc|dev|host|etc|rootfs/var/lib/docker/containers|rootfs/var/lib/docker/overlay2|rootfs/run/docker/netns|rootfs/var/lib/docker/aufs)($$|/)' ~ <file_sep>/reload_prom_conf.sh docker exec -it prom_prometheus kill -HUP 1
f4dee854ffcb699f46c70784fbbdaefaf8e77e39
[ "Markdown", "Shell" ]
4
Shell
kgersen/blackbox-prom-grafana
4f2b9a4514d9d9014dc817c6c091d7eaf491d57a
20854b35e2d91f551a398959a9acbd5b56b785f6
refs/heads/master
<repo_name>PGui/FiberTaskingLib<file_sep>/ci_scripts/travis_ci_install_osx.sh #!/bin/bash set -x #echo on brew update brew cask uninstall oclint upgradeBrewFormula () { if brew ls --versions $1 > /dev/null then brew outdated $1 || brew upgrade $1 else brew install $1 fi } case "${CXX}" in g++-4.9) upgradeBrewFormula gcc@4.9 ;; g++-5) upgradeBrewFormula gcc@5 ;; g++-6) upgradeBrewFormula gcc@6 ;; clang++-3.7) upgradeBrewFormula llvm@3.7 ;; clang++-3.8) upgradeBrewFormula llvm@3.8 ;; clang++-3.9) upgradeBrewFormula llvm@3.9 # 3.9 is keg-only, so we have to set the full file path export MY_CC=/usr/local/opt/llvm@3.9/bin/clang export MY_CXX=/usr/local/opt/llvm@3.9/bin/clang++ ;; *) echo "Compiler not supported: ${CXX}. See travis_ci_install_osx.sh"; exit 1 ;; esac <file_sep>/CMakeLists.txt ### # FiberTaskingLib - A tasking library that uses fibers for efficient task switching # # This library was created as a proof of concept of the ideas presented by # <NAME> in his 2015 GDC Talk 'Parallelizing the Naughty Dog Engine Using Fibers' # # http://gdcvault.com/play/1022186/Parallelizing-the-Naughty-Dog-Engine # # FiberTaskingLib is the legal property of <NAME> # Copyright <NAME> 2015 - 2018 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ## cmake_minimum_required(VERSION 3.2) project(FiberTaskingLib) # Options option(FTL_BUILD_TESTS "Build FiberTaskingLib tests" ON) option(FTL_BUILD_BENCHMARKS "Build FiberTaskingLib benchmarks" ON) option(FTL_VALGRIND "Link and test with Valgrind" OFF) option(FTL_FIBER_STACK_GUARD_PAGES "Add guard pages around the fiber stacks" OFF) # Include Valgrind if (FTL_VALGRIND) add_definitions(-DFTL_VALGRIND=1) endif() # Define the guard page size if (FTL_FIBER_STACK_GUARD_PAGES) add_definitions(-DFTL_FIBER_STACK_GUARD_PAGES=1) endif() # CTest needs to be included as soon as possible if (FTL_BUILD_TESTS) include(CTest) endif() set(CMAKE_CXX_STANDARD 11) # C++11... set(CMAKE_CXX_STANDARD_REQUIRED ON) #...is required... set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11 set_property(GLOBAL PROPERTY USE_FOLDERS ON) set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake") # Add third party libs add_subdirectory(third_party) # Warning flags include(${CMAKE_SOURCE_DIR}/cmake/CheckAndAddFlag.cmake) if (("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") OR (CMAKE_CXX_COMPILER_ID MATCHES "Clang")) Check_And_Add_Flag(-fdiagnostics-color=always) Check_And_Add_Flag(-Wall) Check_And_Add_Flag(-Wextra) Check_And_Add_Flag(-Wpedantic) Check_And_Add_Flag(-Wconversion) Check_And_Add_Flag(-Wsign-conversion) Check_And_Add_Flag(-Wcast-align) Check_And_Add_Flag(-Wcast-qual) Check_And_Add_Flag(-Wctor-dtor-privacy) Check_And_Add_Flag(-Wdisabled-optimization) Check_And_Add_Flag(-Wdouble-promotion) Check_And_Add_Flag(-Wduplicated-branches) Check_And_Add_Flag(-Wduplicated-cond) Check_And_Add_Flag(-Wformat=2) Check_And_Add_Flag(-Wlogical-op) Check_And_Add_Flag(-Wmissing-include-dirs) Check_And_Add_Flag(-Wnoexcept) Check_And_Add_Flag(-Wnull-dereference) Check_And_Add_Flag(-Wold-style-cast) Check_And_Add_Flag(-Woverloaded-virtual) Check_And_Add_Flag(-Wshadow) Check_And_Add_Flag(-Wstrict-aliasing=1) Check_And_Add_Flag(-Wstrict-null-sentinel) Check_And_Add_Flag(-Wstrict-overflow=2) Check_And_Add_Flag(-Wswitch-default) Check_And_Add_Flag(-Wundef) Check_And_Add_Flag(-Wuseless-cast) Check_And_Add_Flag(-Wno-unknown-pragmas) Check_And_Add_Flag(-Wno-aligned-new) if(("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") AND (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.0)) # Useless flag that hits a bunch of valid code Check_And_Add_Flag(-Wno-missing-field-initializers) endif() else() Check_And_Add_Flag(/W4) Check_And_Add_Flag(/wd4324) endif() # Build FiberTaskingLib add_subdirectory(source) # Build Tests if (FTL_BUILD_TESTS) add_subdirectory(tests) endif() # Build benchmarks if (FTL_BUILD_BENCHMARKS) add_subdirectory(benchmarks) endif() # Linter scripts set(CMAKE_EXPORT_COMPILE_COMMANDS True CACHE BOOL "Export Compile Commands for Linting" FORCE) configure_file(tools/lint-clang.bash.in tools/lint-clang.bash @ONLY) configure_file(tools/format.bash.in tools/format.bash @ONLY)
ecb467fa318a96559ab38b54f62c9cff964731fe
[ "CMake", "Shell" ]
2
Shell
PGui/FiberTaskingLib
d28f9ca68f86226dce439daa72e94e3ceb3ec3da
b6e1c7b63a9136b77361461981e8f33bf476abff
refs/heads/master
<file_sep># rlc-token RLC Token for the iEx.ec project Thanks to Beyond the Void, for helping us shaping the crowdsale contract, Open Zeppelin and SmartPool for the security audit and François Branciard for the testing. The RLC token is deployed at 0x607F4C5BB672230e8672085532f7e901544a7375 The Crowdsale contract is deployed at 0xec33fB8D7c781F6FeaF2Dd46D521D4F292320200 ## To test This is a truffle 3 repo Launch `testrpc` on another terminal Launch `truffle test` ## Deployment Launch migrations script `truffle migrate` and the run this on truffle console: RLC.at(RLC.address).transfer(Crowdsale.address,87000000000000000) RLC.at(RLC.address).transferOwnership(Crowdsale.address) <file_sep>#!/bin/sh # This script tries to remove imports one by one while making sure that the # project can still be compiled, so that the minimum number of imports is used. # This approach is really inefficient, but good enough given that it can just # be run once in a while to unclutter imports. set -e set -u compile(){ echo Compiling... truffle compile >/dev/null 2>&1 } echo "This script will run on the following files:" find 'contracts' -iname '*.sol' echo "Continue? [y/N]" read -r answer if [ "$answer" != "y" ]; then exit 2 fi echo "Compiling once with original files as a sanity check" compile || exit 3 tmp="$(mktemp)" find 'contracts' -type f -iname '*.sol' |\ while read -r f ; do grep -n '^ *import' "$f" | cut -d':' -f1 |\ while read -r line; do cp "$f" "$tmp" sed -i "$line"'s/.*//' "$f" compile || cp "$tmp" "$f" done done exit 0 <file_sep># trimport This script removes unused and useless import directives from Solidity contracts. It should be executed from the root of a Truffle folder. It goes through the `contracts` subfolder, and removes every import line as long as `truffle compile` succeeds. <file_sep>var RLC = artifacts.require("./RLC.sol"); var Crowdsale = artifacts.require("./Crowdsale.sol"); module.exports = function(deployer, network) { var owner = web3.eth.accounts[0]; var btcproxy = web3.eth.accounts[1]; deployer.deploy(RLC, {from: owner}).then(function(){ return deployer.deploy(); }); }; /* ADD these step truffle console: RLC.at(RLC.address).transfer(Crowdsale.address,87000000000000000) RLC.at(RLC.address).balanceOf(Crowdsale.address) RLC.at(RLC.address).transferOwnership(Crowdsale.address) RLC.at(RLC.address).owner() */
2eb378599e9ef61e987e3add7f83ed42fff107b4
[ "Markdown", "JavaScript", "Shell" ]
4
Markdown
ChainSecurity/trimport
9bae7554365075d6be6fd1b8425161bdae518ca1
e822bfefe225b1c735113e9ece5f4447b6d38a3d
refs/heads/main
<file_sep>const coap = require("coap"), // or coap si = require("systeminformation"), updateSwitch = () => { if (alertSwitch === true) console.log(`Please Charge note book`); }; var alertSwitch = false; var interval = setInterval(() => { const client = coap.request({ hostname: "192.168.219.185", pathname: "battery", //observe: true, }); client.on("response", async function (res) { //console.log(client); //res.pipe(process.stdout); var percent = await JSON.parse(res.payload); //console.log(res); if (percent.percent < 30) { alertSwitch = true; } else alertSwitch = false; updateSwitch(); }); client.end(); }, 5000); <file_sep>const coap = require("coap"), // or coap si = require("systeminformation"), server = coap.createServer(); server.on("request", async function (req, res) { var battery = await si.battery(); res.end(JSON.stringify(battery)); res.on("finish", function (err) {}); }); server.listen(5683, "192.168.219.185", function () { console.log("server started"); });
0008b5c24b546af9accddb219994311efa95e7a2
[ "JavaScript" ]
2
JavaScript
jgus52/coap_pj
85d5c8da0e9f4cb6dccc58ea943323abe1c96342
09d96f15394db9df5ef00d4da2ffe733118780f7
refs/heads/master
<repo_name>swimablefish/kubernetes-qperf<file_sep>/README.md # kubernetes-qperf Basic network performance testing ``` alpine:3.7 qperf from testing repo kubernetes > 1.8.0 ``` Change SERVER_ADDR in the client deployment config to your cluster's record. ## 1 Example output from AKS (Azure managed Kubernetes) Standard D2 v2 (2 vcpus, 7 GB memory) ``` iteration:1 t:16 latency = 171 us iteration:2 t:39 latency = 225 us iteration:3 t:37 latency = 205 us iteration:4 t:41 latency = 174 us iteration:5 t:37 latency = 210 us iteration:6 t:11 latency = 184 us iteration:7 t:48 latency = 237 us iteration:8 t:13 latency = 178 us iteration:9 t:36 latency = 198 us iteration:10 t:10 latency = 187 us iteration:11 t:16 latency = 171 us iteration:12 t:32 latency = 167 us iteration:13 t:34 latency = 162 us iteration:14 t:33 latency = 221 us iteration:15 t:55 latency = 197 us iteration:16 t:55 latency = 213 us iteration:17 t:31 latency = 202 us iteration:18 t:49 latency = 226 us iteration:19 t:35 latency = 176 us iteration:20 t:14 latency = 218 us ``` ## 2 Setup Need to specify the nodes in 02server.yml and 03client.yaml first ``` kubectl apply -f ./service ``` ## To add antiafinity or daemonset make sure client is not on the same node as server. <file_sep>/iperf3/README.md # iperf3 in kubernetes 1. Choose 2 nodes, one is client, the other is server 2. Put client.yaml into to client's /etc/kubernetes/manifests 3. Put server.yaml into to server's /etc/kubernetes/manifests 4. Install iperf3 into the client and server pods 5. Run `kubectl create -f svc.yaml` 6. Run `iperf3 -p 5001 -s` in the server pod 7. Run `iperf3 -p 5001 -t 10 -p 10` in the client pod to start the test <file_sep>/docker/qperf/entrypoint.sh #!/bin/sh iteration=1 t=10 echo "Running as ${SERVICE_TYPE}" echo "SERVER_ADDR ${SERVER_ADDR}" echo "SERVER_PORT ${SERVER_PORT}" if [ ${SERVICE_TYPE} == "server" ] ; then qperf -lp ${SERVER_PORT} elif [ ${SERVICE_TYPE} == "client" ] ; then while true ; do sleep 1 t=$(shuf -i ${QPERF_INTERVAL} -n 1) lat=$(qperf -t ${t} --use_bits_per_sec ${SERVER_ADDR} -lp ${SERVER_PORT} tcp_lat | grep "latency") echo "iteration:${iteration} t:${t} ${lat}" let iteration++ done elif [ ${SERVICE_TYPE} == "ping" ] ; then sleep 1 ping -i 5 ${SERVER_ADDR} | awk -F'=' '{print$4}' fi <file_sep>/docker/qperf/Dockerfile FROM alpine:3.7 RUN echo "http://nl.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories && \ apk --update --no-cache add tar bash libstdc++ bind-tools iputils busybox-extras && \ apk --update --no-cache --force-broken-world add qperf@testing COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh ENTRYPOINT [ "/entrypoint.sh" ]
7218c7b1b217627d78e79afeeca2ddfa7ec2accf
[ "Markdown", "Dockerfile", "Shell" ]
4
Markdown
swimablefish/kubernetes-qperf
0e8d3294502d2925601def5fb2409a4914b036b2
a8b62d746df0342ce7e8fd431b5bae72e3ba49d8
refs/heads/master
<repo_name>13681899297/banbenku<file_sep>/codes/GlobalFun.py # 编译日期:2020-05-08 15:38:35 # 版权所有:www.i-search.com.cn # coding=utf-8 <file_sep>/codes/Main_d.py # coding=utf-8 # 编译日期:2020-05-08 15:48:11 # 版权所有:www.i-search.com.cn import time import pdb from ubpa.ilog import ILog from ubpa.base_img import * import getopt from sys import argv import sys import pandas as pd import ubpa.ibrowse as ibrowse import ubpa.icsv as icsv import ubpa.iexcel as iexcel import ubpa.iie as iie import ubpa.ikeyboard as ikeyboard import ubpa.itools.rpa_environment as rpa_environment class YeHongJun_KaoShi: def __init__(self,**kwargs): self.__logger = ILog(__file__) self.path = set_img_res_path(__file__) self.robot_no = '' self.proc_no = '' self.job_no = '' self.input_arg = '' if('robot_no' in kwargs.keys()): self.robot_no = kwargs['robot_no'] if('proc_no' in kwargs.keys()): self.proc_no = kwargs['proc_no'] if('job_no' in kwargs.keys()): self.job_no = kwargs['job_no'] if('input_arg' in kwargs.keys()): self.input_arg = kwargs['input_arg'] self.input_arg = self.input_arg.replace("\\","/") def ExportExcel(self,pv_df=None): lv_fileName='YHJ_KaoHe.xlsx' lv_UserProfile=None #获取环境变量 self.__logger.debug('Flow:ExportExcel,StepNodeTag:08152548128127,Note:') lv_UserProfile = rpa_environment.get_sys_variable(var='USERPROFILE') #创建excel self.__logger.debug('Flow:ExportExcel,StepNodeTag:08152534447125,Note:') iexcel.create_excel(path=lv_UserProfile + '\\Desktop\\',file_name=lv_fileName) #关闭excel应用 self.__logger.debug('Flow:ExportExcel,StepNodeTag:08153320996142,Note:') iexcel.close_excel_apps() #导出excel self.__logger.debug('Flow:ExportExcel,StepNodeTag:08153330549144,Note:') icsv.write_excel(path=lv_UserProfile + '\\Desktop\\' + lv_fileName,df=pv_df) def GetData(self,pv_maxPageNumber=7,pv_key='i-Search-05'): lv_totalResult=None lv_pageResult=None # 代码块 self.__logger.debug('Flow:GetData,StepNodeTag:0815030114185,Note:初始化lv_totalResult') lv_totalResult = pd.DataFrame() # For循环 self.__logger.debug('Flow:GetData,StepNodeTag:0815093966295,Note:循环获取数据') for i in range(pv_maxPageNumber): # IE拾取表格(web) self.__logger.debug('Flow:GetData,StepNodeTag:0814522186952,Note:') time.sleep(1) lv_pageResult = iie.get_ie_table(title=r'理财管理',selector=r'#boxTable',waitfor=10) # 代码块 self.__logger.debug('Flow:GetData,StepNodeTag:08152035948114,Note:合并结果') lv_totalResult = lv_totalResult.append(lv_pageResult) # 鼠标点击 self.__logger.debug('Flow:GetData,StepNodeTag:0815065762293,Note:翻页') time.sleep(1) iie.do_click_pos(win_title=r'双录系统-录音、录像、录屏 - Internet Explorer',title=r'理财管理',selector=r'#ListForm > DIV:nth-of-type(2) > DIV:nth-of-type(1) > DIV:nth-of-type(2) > FONT:nth-of-type(1) > DIV:nth-of-type(1) > SPAN:nth-of-type(3)',button=r'left',curson=r'center',times=1,run_mode=r'ctrl',continue_on_error=r'break',waitfor=10) # 表格过滤 self.__logger.debug('Flow:GetData,StepNodeTag:0815121659699,Note:筛选出目标结果') tvar0815121659699 = lv_totalResult[(lv_totalResult['产品代码'].str.startswith(pv_key))] # Return返回 self.__logger.debug('Flow:GetData,StepNodeTag:08152243722120,Note:返回结果') return tvar0815121659699 def LoginCSM(self): password='<PASSWORD>==' userName='ceshi001' url='http://192.168.127.12:9080/login.action' #打开浏览器 self.__logger.debug('Flow:LoginCSM,StepNodeTag:0814383211710,Note:打开CSM') ibrowse.open_browser(browser_type='ie',url=url) # 热键输入 self.__logger.debug('Flow:LoginCSM,StepNodeTag:0814400306515,Note:最大化窗口') ikeyboard.key_send_cs(text='#{UP}',waitfor=10) # 设置文本 self.__logger.debug('Flow:LoginCSM,StepNodeTag:0814403727417,Note:输入用户名') iie.set_text(url=r'http://192.168.127.12:9080/login.action',selector=r'#loginWrap > UL:nth-of-type(1) > LI:nth-of-type(1) > INPUT:nth-of-type(1)',text=userName,waitfor=10) # 设置文本 self.__logger.debug('Flow:LoginCSM,StepNodeTag:0814423516022,Note:输入密码') iie.set_text(url=r'http://192.168.127.12:9080/login.action',selector=r'#loginWrap > UL:nth-of-type(1) > LI:nth-of-type(2) > INPUT:nth-of-type(1)',text=password,waitfor=10) # 鼠标点击 self.__logger.debug('Flow:LoginCSM,StepNodeTag:0814432656329,Note:点击登录') iie.do_click_pos(win_title=r'双录系统-录音、录像、录屏 - Internet Explorer',url=r'http://192.168.127.12:9080/login.action',selector=r'#loginWrap > UL:nth-of-type(1) > LI:nth-of-type(2) > INPUT:nth-of-type(2)',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',continue_on_error=r'break',waitfor=10) def ProductsPage(self): # 鼠标点击 self.__logger.debug('Flow:ProductsPage,StepNodeTag:0814463326434,Note:') iie.do_click_pos(win_title=r'双录系统-录音、录像、录屏 - Internet Explorer',url=r'http://192.168.127.12:9080/login.action',selector=r'#frame-nav > UL:nth-of-type(1) > LI:nth-of-type(1) > A:nth-of-type(1)',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',continue_on_error=r'break',waitfor=10) # 鼠标点击 self.__logger.debug('Flow:ProductsPage,StepNodeTag:0814464601036,Note:') iie.do_click_pos(win_title=r'双录系统-录音、录像、录屏 - Internet Explorer',url=r'http://192.168.127.12:9080/login.action',selector=r'#MenuContext > TABLE:nth-of-type(1) > TBODY:nth-of-type(1) > TR:nth-of-type(1) > TD:nth-of-type(2) > LI:nth-of-type(5) > A:nth-of-type(1)',button=r'left',curson=r'center',times=1,run_mode=r'unctrl',continue_on_error=r'break',waitfor=10) def Main(self): # 子流程:LoginCSM self.__logger.debug('Flow:Main,StepNodeTag:0814440592931,Note:登录到CSM系统') (temptemp)=self.LoginCSM() # 子流程:ProductsPage self.__logger.debug('Flow:Main,StepNodeTag:0814473839038,Note:定位到产品页') (temptemp)=self.ProductsPage() # 子流程:GetData self.__logger.debug('Flow:Main,StepNodeTag:08151445709108,Note:获取数据') (tvar08151445709108)=self.GetData(pv_maxPageNumber=7,pv_key='i-Search-05') # 子流程:ExportExcel self.__logger.debug('Flow:Main,StepNodeTag:08153531919158,Note:保存文件') (temptemp)=self.ExportExcel(pv_df=tvar08151445709108) if __name__ == '__main__': robot_no = '' proc_no = '' job_no = '' input_arg = '' try: argv = sys.argv[1:] opts, args = getopt.getopt(argv,"hr:p:j:i:",["robot = ","proc = ","job = ","input = "]) except getopt.GetoptError: print ('robot.py -r <robot> -p <proc> -j <job>') for opt, arg in opts: if opt == '-h': print ('robot.py -r <robot> -p <proc> -j <job>') elif opt in ("-r", "--robot"): robot_no = arg elif opt in ("-p", "--proc"): proc_no = arg elif opt in ("-j", "--job"): job_no = arg elif opt in ("-i", "--input"): input_arg = arg pro = YeHongJun_KaoShi(robot_no=robot_no,proc_no=proc_no,job_no=job_no,input_arg=input_arg) pro.Main() ___logger = ILog(__file__) ___logger.debug('Class:Main,ProTag:Quit,Note:Exit')
78a80000da027d61ee7adb706eea46d5ce2876b1
[ "Python" ]
2
Python
13681899297/banbenku
7a91a2147a1251145a74cd098bf60d4f659032e7
8be72fc4c135b9d5c15e312749cc30a76b5332c8
refs/heads/master
<repo_name>luckyMcHanc/42-lem-in-project<file_sep>/src/add_rooms.c #include "../includes/lem_in.h" int room_exist(char *room_name, t_rooms *rooms) { t_rooms *tmp; tmp = rooms; if (!rooms) return (0); while(tmp) { if (!ft_strcmp(room_name, tmp->data)) return (1); tmp = tmp->next; } return (0); } int valid_room(char *room_name) { char **tmp; int x; int i; x = 0; i = 0; tmp = ft_strsplit(room_name, ' '); while (tmp[i]) i++; if (i != 3) ft_error(); i = -1; if (ft_isint(tmp[1]) && ft_isint(tmp[2])) x = 1; if (x) return (1); return (0); } t_rooms *add_room(t_rooms *rooms, char *room_name, t_init *init) { t_rooms *node; t_rooms *temp; int i; if (!valid_room(room_name)) ft_error(); if (room_exist(room_name, rooms) || room_name[0] == 'L') ft_error(); i = ft_strchr(room_name, ' ') - room_name; if (!(node = (t_rooms *)malloc(sizeof(t_rooms *)))) ft_error(); node->data = ft_strndup(room_name, i); node->next = NULL; ft_putendl(node->data); init->nb_rooms++; if (!rooms) rooms = node; else { temp = rooms; while(temp->next) temp = temp->next; temp->next = node; } return (rooms); } <file_sep>/includes/lem_in.h #include "libft/libft.h" typedef struct s_depedents { char *start; char *end; int nb_ants; int nb_rooms; int nb_r; char *line; } t_init; typedef struct s_rooms { struct s_rooms *next; char *data; } t_rooms; typedef struct s__links { int **links; } t_links; typedef struct s_path { int *visited; char *map; struct s_path *next; } t_path; typedef struct s_visit { int *path; } t_visit; t_rooms *create_rooms(t_init *init, t_rooms *t_rooms); t_rooms *add_room(t_rooms *rooms, char *room_name, t_init *init); t_links *create_links(t_links *links, t_rooms *rooms, t_init *init); int exist_link(char *exist, t_rooms *rooms); t_path *find_path(t_rooms *rooms, t_links *links, t_init *init, t_path *visit); t_path *create_map(t_path *visit, t_path *map, t_rooms *rooms, t_init *init); t_path *display_ants(t_path *map, t_init *init); void free_data(t_links *links, t_rooms *rooms, t_path *visit, t_init *init, t_path *map); char **display_small(t_init *init, char **temp, int pn); void ft_error(); <file_sep>/src/create_links.c #include "../includes/lem_in.h" t_links *init_links(t_links *links, int i) { int x; x = 0; if (!(links = (t_links *)malloc(sizeof(t_links)))) ft_error(0); if (!(links->links = (int **)malloc(sizeof(int*) * i))) ft_error(0); while (x < i) { if (!(links->links[x] = (int *)malloc(sizeof(int) * i))) ft_error(0); x++; } return (links); } int exist_link(char *exist, t_rooms *rooms) { int i; t_rooms *tmp; i = 0; tmp = rooms; while (tmp) { if (!ft_strcmp(exist, tmp->data)) return (i); i++; tmp = tmp->next; } return (-1); } t_links *add_link(t_rooms *rooms, t_links *links, char *line) { char **li; int a; int b; li = ft_strsplit(line, '-'); a = 0; while(li[a]) a++; if (a != 2) ft_error(); a = exist_link(li[0], rooms); b = exist_link(li[1], rooms); ft_putendl(line); if (a ==-1 || b == -1) ft_error(); links->links[a][b] = 1; links->links[b][a] = 1; return (links); } t_links *create_links(t_links *links, t_rooms *rooms, t_init *init) { int i; i = init->nb_rooms; links = init_links(links, i); if (init->line) links = add_link(rooms, links, init->line); while(get_next_line(0, &init->line) == 1) { if (init->line[0] != '#') links = add_link(rooms, links, init->line); } return (links); } <file_sep>/src/find_path.c #include "../includes/lem_in.h" int visited_before(int *visited, int v, int i) { int x; x = 0; while(x < i) { if (visited[x] == v) return (1); x++; } return (0); } t_path *init_path(t_path *visit, t_init *init, int start) { if (!(visit = (t_path *)malloc(sizeof(t_path)))) ft_error(); if (!(visit->visited = (int *)malloc(sizeof(int) * init->nb_rooms + 1))) ft_error(); visit->visited[0] = start; return (visit); } t_visit *init_visit(t_visit *visit, t_init *init, int start) { if (!(visit = (t_visit *)malloc(sizeof(t_visit)))) ft_error(); if (!(visit->path = (int *)malloc(sizeof(int) * init->nb_rooms + 1))) ft_error(); visit->path[0] = start; return (visit); } int ft_minus(int j) { j = j - 1; if( j < 0) ft_error(); return (j); } t_path *visit_rooms(t_path *visit, int start, int end, t_init *init, t_links *links, t_visit *path) { int x; int j; int a; int b; j = 0; b = 0; a = -1; while (a != end) { x = 0; while (x < init->nb_rooms) { if (links->links[start][x] == 1 && !visited_before(path->path, x, init->nb_rooms)) { visit->visited[++j] = x; path->path[++b] = x; if (x == end) { visit->visited[j] = x; a = x; break; } start = x; x = 0; } x++; } j = ft_minus(j); start = visit->visited[j]; } return (visit); } t_path *find_path(t_rooms *rooms, t_links *links, t_init *init, t_path *visit) { int start; int end; t_visit *path; path = NULL; start = exist_link(init->start, rooms); end = exist_link(init->end, rooms); visit = init_path(visit, init, start); path = init_visit(path, init, start); visit = visit_rooms(visit, start, end, init, links, path); return (visit); } <file_sep>/src/display_small.c #include "../includes/lem_in.h" int print_first(int x, char **tmp, t_init *init) { int c; int a; c = 1; a = 0; if (x >= init->nb_ants) return (2); while (a < x && tmp[a]) a++; while (c <= x && x < init->nb_ants) { ft_putchar('L'); ft_putnbr(c); ft_putchar('-'); ft_putstr(tmp[a]); ft_putchar(' '); a--; c++; } ft_putchar('\n'); return (1); } int print_medium(int x, char **tmp, t_init *init) { int a; int b; int c; int d; a = x - 1; b = 1; c = 1; d = 1; if (a >= init->nb_r) return (3); while(b <= init->nb_ants) { if (!ft_strcmp(tmp[a], init->end)) d = 2; ft_putchar('L'); ft_putnbr(c); ft_putchar('-'); ft_putstr(tmp[a]); ft_putchar(' '); a--; c++; b++; } ft_putchar('\n'); if (d == 2) return (3); return (2); } int print_last(int x, char **map, t_init *init, int pn) { int a; int b; int c; int i; char **tmp; b = pn - x; c = x - init->nb_r + 1; tmp = map; a = 1; i = init->nb_r - 1; while (a <= b && b <= init->nb_ants) { ft_putchar('L'); ft_putnbr(c); ft_putchar('-'); ft_putstr(tmp[i]); ft_putchar(' '); a++; c++; i--; } ft_putchar('\n'); return (3); } char **display_small(t_init *init, char **temp, int pn) { int x; int status; x = 1; status = 1; while(x < pn) { if (status == 1) status = print_first(x, temp, init); else if (status == 2) status = print_medium(x, temp, init); else if (status == 3) status = print_last(x, temp, init, pn); x++; } return(temp); } <file_sep>/src/display_ants.c #include "../includes/lem_in.h" char **reverse(t_path *head, char **tmp, t_init *init) { t_path *map; int i; map = head; i = 0; if (!(tmp = (char **)malloc(sizeof(char *) * init->nb_r))) ft_error(); while (map) { if (!(tmp[i] = (char *)malloc(sizeof(char) * ft_strlen(map->map)))) ft_error(); tmp[i] = ft_strcpy(tmp[i], map->map); map = map->next; i++; } return (tmp); } int ft_positive(int x, char **map, t_init *init) { int a; char **tmp; int c; tmp = map; a = 0; while (a < x && tmp[a]) { a++; } c = 1; if (x == (init->nb_r - 1)) return (2); while (c <= x) { ft_putchar('L'); ft_putnbr(c); ft_putchar('-'); ft_putstr(tmp[a]); ft_putchar(' '); a--; c++; } ft_putchar('\n'); if (x >= init->nb_ants) return (2); return (1); } int ft_constant(int x, char **map, t_init *init) { int a; int b; int c; char **tmp; tmp = map; a = init->nb_r - 1; c = x - init->nb_r + 1; b = 1; while(b < init->nb_r) { ft_putchar('L'); ft_putnbr(c); ft_putchar('-'); ft_putstr(tmp[a]); ft_putchar(' '); a--; b++; c++; } ft_putchar('\n'); if (x >= init->nb_ants) return (3); return 2; } int ft_negative(int x, char **map, t_init *init, int pn) { int a; int b; int c; int i; char **tmp; b = pn - x; c = x - init->nb_r + 1; tmp = map; a = 1; i = init->nb_r - 1; while (a <= b && b <= init->nb_ants) { ft_putchar('L'); ft_putnbr(c); ft_putchar('-'); ft_putstr(tmp[i]); ft_putchar(' '); a++; c++; i--; } ft_putchar('\n'); return (3); } t_path *display_ants(t_path *map, t_init *init) { int x; int pn; int status; char **tmp; x = 1; status = 1; tmp = NULL; pn = init->nb_ants + init->nb_r; tmp = reverse(map, tmp, init); ft_putchar('\n'); if (init->nb_ants < init->nb_r) tmp = display_small(init, tmp, pn); else { while (x < pn) { if (status == 1) status = ft_positive(x, tmp, init); else if (status == 2) status = ft_constant(x, tmp, init); else if (status == 3) status = ft_negative(x, tmp, init, pn); x++; } } return (map); } <file_sep>/src/create_map.c #include "../includes/lem_in.h" int node_exist(char *node, t_path *map) { t_path *tmp; tmp = map; while(tmp) { if (!ft_strcmp(node, map->map)) return (1); tmp = tmp->next; } return (0); } t_path *add_to_map(t_path *map, t_rooms *rooms, t_init *init) { t_path *node; t_path *tmp; if (node_exist(rooms->data, map)) return (map); if (!(node = (t_path *)malloc(sizeof(t_path *)))) ft_error(); node->map = ft_strdup(rooms->data); node->next = NULL; if (!map) map = node; else { tmp = map; while (tmp->next) tmp = tmp->next; tmp->next = node; } init->nb_r++; return (map); } t_path *create_map(t_path *visit, t_path *map, t_rooms *rooms, t_init *init) { int x; int j; t_rooms *tmp; x = 0; while (x < init->nb_rooms && x > -1) { j = 0; tmp = rooms; while (j < init->nb_rooms && tmp) { if (j == visit->visited[x]) map = add_to_map(map, tmp, init); tmp = tmp->next; j++; } x++; } return (map); } <file_sep>/src/create_rooms.c #include "../includes/lem_in.h" int is_position(char *line) { if (!ft_strcmp(line, "##start")) return 1; else if (!ft_strcmp(line, "##end")) return 2; return 0; } void room_name(char *line, t_init *init, int state) { int i; char **name; if (!ft_strchr(line, ' ') || ft_strchr(line, '#') || line[0] == 'L') ft_error(); name = ft_strsplit(line, ' '); i = 0; while (name[i]) i++; if (i != 3) ft_error(); if (state == 1) init->start = ft_strdup(name[0]); if (state == 2) init->end = ft_strdup(name[0]); i = 0; } t_rooms *create_rooms(t_init *init, t_rooms *rooms) { char *line; char *tmp; int state; state = 0; while (get_next_line(0, &line) == 1) { tmp = ft_strdup(line); if (state > 0) room_name(tmp, init, state); state = is_position(line); if (line[0] != '#' && ft_strchr(line, ' ')) rooms = add_room(rooms, line, init); if (!ft_strchr(line, ' ') && line[0] != '#') { init->line = ft_strdup(line); break ; } } if (ft_strlen(line) == 0) ft_error(); return (rooms); } <file_sep>/src/main.c #include "../includes/lem_in.h" void initializer(t_init *init) { t_init *temp; temp = init; temp->start = NULL; temp->end = NULL; temp->line = NULL; temp->nb_ants = 0; temp->nb_rooms = 0; temp->nb_r = 0; } void is_map_valid(t_init *init) { if (init->start == NULL || init->end == NULL) ft_error(); } void get_ants(t_init *init) { char *line; while(get_next_line(0, &line) == 1) { if(ft_isint(line) && ft_atoi(line) > 0) { init->nb_ants = ft_atoi(line); free(line); break ; } else { if (line[0] != '#') ft_error(); } free(line); } ft_putnbr(init->nb_ants); ft_putchar('\n'); } int main(void) { t_init init; t_rooms *rooms; t_links *links; t_path *visit; t_path *map; rooms = NULL; map = NULL; links = NULL; visit = NULL; initializer(&init); get_ants(&init); rooms = create_rooms(&init, rooms); links = create_links(links, rooms, &init); is_map_valid(&init); visit = find_path(rooms, links, &init, visit); map = create_map(visit, map, rooms, &init); map = display_ants(map, &init); return (0); } <file_sep>/Makefile NAME = lem_in.a SRC = src/main.c \ src/add_rooms.c \ src/create_rooms.c \ src/create_map.c \ src/create_links.c \ src/display_ants.c \ src/find_path.c \ src/ft_error.c \ src/display_small.c SRCO = *.o CFLAGS = -Wall -Werror -Wextra all : $(NAME) $(NAME) : @make -C includes/libft/ @gcc -c -g $(CFLAGS) $(SRC) @ar rc $(NAME) $(SRCO) @ranlib $(NAME) @gcc $(CFLAGS) src/main.c lem_in.a includes/libft/libft.a -o lem-in clean : @/bin/rm -f $(SRCO) @/bin/rm -f includes/libft/*.o fclean : clean @/bin/rm -f $(NAME) @/bin/rm -f includes/libft/libft.a @rm lem-in re : fclean all <file_sep>/Dockerfile FROM ubuntu RUN apt-get -y update RUN apt -y install build-essential && apt-get -y install manpages-dev COPY ./ /lem_in_ WORKDIR /lem_in<file_sep>/includes/libft/ft_join.c #include "libft.h" char *ft_jointostr(char *str, char *buff) { char *limited; if (!str) return (NULL); limited = ft_strjoin(str, buff); free(str); return (limited); }<file_sep>/src/ft_error.c #include "../includes/lem_in.h" void ft_error() { ft_putendl("Error"); exit(0); }
f93c80471b2333ce122593aee929fdf973b81418
[ "C", "Makefile", "Dockerfile" ]
13
C
luckyMcHanc/42-lem-in-project
07964dc5512dc17105ebb82c21960ef45322d127
c511215faba0ae787499c35ca3391f353efb873a
refs/heads/master
<repo_name>VVK-3/Medicare-App-and-Website<file_sep>/Website/backend/Routes/sell.js const express = require('express'); const verifyToken = require('../Helpers/verifytoken') const bodyParser = require('body-parser') const router = express.Router() const Trans = require('../Models/Transaction') router.use(bodyParser()) router.use(bodyParser.json()) router.use(bodyParser.urlencoded({ extended: true })) router.use(verifyToken) router.post('/', (req, res) => { if (req.body.acc == undefined) { res.send().json({ "msg": "login in to meta mask" }); } const username = req.user.userName // console.log(req.body.acc); const trans = new Trans({ transid: req.body.tid, name: username, from: req.body.acc, medname: req.body.medname, sid: req.body.sid, meds: 1 , dot: Date.now(), }) trans.save() .then( resu => { // console.log(resu); res.status(200).send(resu); } ) .catch(err => { // console.log(err) }) }); module.exports = router<file_sep>/Website/backend/Models/Transaction.js var mongoose = require('mongoose'); const Schema = mongoose.Schema({ transid: String, from: String, to: String, sid: Number, eid: Number, meds: Number, dot: Date, name: String, accepted: Boolean, Toname: String, medlist: Array, exp: Date, msg: String, medname: String }) const Trans = mongoose.model('Trans', Schema) module.exports = Trans;<file_sep>/README.md # Medicare-App-and-Website * All in One Solution for Supply Chain Management for pharma industry using Blockchain. * Website for the manufacturer,distributers,retailers to update the status of medicine using BlockChain at every stage of the supplychain. * Flutter App for the consumers to check the expiry of medicine, track & trace the medicine ,check the details of medicine,etc. by scanning the BarCode on the medicine. ## System Architecture :computer: :rocket: <br /> <img src="App/ScreenShots/systemarch.png" height=500> <br /> ## App for The Consumers :iphone: Login Page | Home Page ------------ | ------------- <img src="App/ScreenShots/login.jpg" height=500> | <img src="App/ScreenShots/home.jpg" height=500> After Scanning Medicine | Medicine Tracking ------------ | ------------- <img src="App/ScreenShots/scan.jpg" height=500> | <img src="App/ScreenShots/details.jpg" height=500> Medicine Information | Checking Stock in Nearby Stores ------------ | ------------- <img src="App/ScreenShots/medinfo.jpg" height=500> | <img src="App/ScreenShots/stock.jpg" height=500> ### Medicine Reminder <img src="App/ScreenShots/reminderhome.jpg" height=500> <img src="App/ScreenShots/remind.jpg" height=500> ### Notifications For Medicine Expiry and Reminders <img src="App/ScreenShots/expirynotif.png" height=500> </br> ## Website For Manufactures,Retailers and Distributers :computer: <br /> <img src="App/ScreenShots/Screenshot 1.png" height=300> </br> <img src="App/ScreenShots/Screenshot 2.png" height=300> </br> <img src="App/ScreenShots/Screenshot 3.png" height=300> </br> <img src="App/ScreenShots/Screenshot 4.png" height=300> </br> <br /> <br /> <file_sep>/Website/backend/Routes/index.js const express = require('express'); const router = express.Router() router.use('/login', require('./login')) router.use('/signup/', require('./signup')) router.use('/getuser/', require('./getuser')) router.use('/getalluser/', require('./getalluser')) router.use('/displayallusers/', require('./displayallusers')) router.use('/addmed/', require('./addmeds')) router.use('/getnotifs/', require('./getnotification')) router.use('/gettrans/', require('./gettransaction')) router.use('/accept/', require('./accept')) router.use('/reject/', require('./reject')) router.use('/acceptmeds/', require('./acceptmed')) router.use('/rejectmeds/', require('./rejectmed')) router.use('/backtrack/', require('./backtrack')) router.use('/setdist/', require('./setdist')) router.use('/updatenot/', require('./updatenot')) router.use('/sell/', require('./sell')) router.use('/givemaxeid/', require('./givemaxeid')) router.use('/checkforusername/', require('./check_username_exist')) module.exports = router<file_sep>/Website/frontend/src/Home/Home.js import React, { Component } from 'react'; import './Home.css'; import { FiLogOut } from 'react-icons/fi'; import { GoSearch } from 'react-icons/go'; import { Nav, Navbar, Card, Container, Col, Row, Button } from 'react-bootstrap'; import AuthService from '../AuthService/AuthService.js'; import withAuth from '../withAuth' import supplychain from '../supplychain'; import web3 from '../web3'; import swal from 'sweetalert'; const img = require('../assets/loader.gif'); class Home extends Component { componentWillMount() { this.updateLoginAccountStatus() this.getTrans() this.getNotifs() this.getMaxId() this.Auth.fetch('http://localhost:5000/api/getuser', { method: 'POST', body: JSON.stringify({ }) }).then(res => { // console.log("this is accepted or not", res.accepted) this.setState({ typeofuser: res.typeofuser, userName: res.userName, addrs: res.address, accepted: res.accepted, accountName: res.name }) web3.eth.getAccounts((err, accounts) => { // console.log(err, accounts) if (err) { // console.log('An error occurred ' + err); } else if (accounts[0] != res.address) { // alert( 'Please login into MetaMask with your registered account..!'); swal({ title: "Please Note", text: "Please login into MetaMask with your registered account..!", icon: "warning", dangerMode: true, }).then(willD => { this.logout() window.location.reload(); }) } }); }) .catch(err => { // console.log('view own Question error', err) }) } updateLoginAccountStatus = () => { web3.eth.getAccounts((err, accounts) => { // console.log(err, accounts) if (err) { // console.log('An error occurred ' + err); } else if (accounts.length == 0) { // alert( 'Please login to MetaMask..!'); swal({ title: "Please Note", text: "Please login to MetaMask..!", icon: "warning", dangerMode: true, }).then(a => { this.logout() window.location.reload(); }) } }); this.Auth.fetch('http://localhost:5000/api/getuser', { method: 'POST', body: JSON.stringify({ }) }).then(res => { if (res.accepted === false) { swal({ title: "Please Note", text: "Admin Not Approve you yet Please Wait", icon: "warning", dangerMode: true, }).then(a => { this.logout() window.location.reload(); }) } }); } getTrans = () => { const a = web3.eth.getAccounts().then(r => { // console.log(r[0] + " This is current account address"); // console.log(this.state.Name) this.Auth.fetch('http://localhost:5000/api/gettrans', { method: 'POST', body: JSON.stringify({ acc: r[0], user: this.state.Name, userName: this.state.userName }) }).then(res => { this.setState({ results: res }) // console.log(this.state) // console.log("This is Transaction ", this.state.results) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) }) }; getNotifs = () => { const a = web3.eth.getAccounts().then(r => { // console.log(r[0]); this.Auth.fetch('http://localhost:5000/api/getnotifs', { method: 'POST', body: JSON.stringify({ acc: r[0], userName: this.state.userName }) }).then(res => { this.setState({ notif: res }) // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) }) } getMaxId = () => { this.Auth.fetch('http://localhost:5000/api/givemaxeid', { method: 'POST', body: JSON.stringify({ }) }).then(res => { let a = Math.max(...res) if (a == "-Infinity") { this.setState({ maxeid: 100 }) } else { this.setState({ maxeid: a + 1 }) } // console.log("HHHHHHHHHHHHHHHHHHHHHH", this.state) }) .catch(err => { // console.log(err) }) } addmed = () => { this.mytryHandler() // alert("Please accept the transaction in metamask and reject if any error") swal({ title: "Please Note", text: "Please accept the transaction in metamask and reject if any error", icon: "success", dangerMode: true, }).then(willDelete => { this.setState({ loading: true }) const a = web3.eth.getAccounts().then(r => { // console.log(r[0]); // console.log(this.state.typeofuser) if (this.state.typeofuser == "Manufacturer") { var date = new Date(); // console.log(Number(this.state.expire)) date.setDate(date.getDate() + Number(this.state.expire)); // console.log(date); var dst = date.toString(); const am = supplychain.methods.setmed(this.state.medname, this.state.maxeid, this.state.eid, this.state.to, this.state.expire, dst).send({ from: r[0] }).then(re => { const allLines = this.fillRange(this.state.maxeid, this.state.eid); // console.log(re.transactionHash) this.Auth.fetch('http://localhost:5000/api/addmed', { method: 'POST', body: JSON.stringify({ tid: re.transactionHash, name: this.state.medname, Mname: this.state.userName, sid: this.state.maxeid, eid: this.state.eid, medlist: allLines, to: this.state.to, toname: this.state.toname, acc: r[0], exp: date }) }).then(res => { // console.log(res) this.setState({ results: res, loading: false }) // console.log(this.state) window.location.reload(); }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) // I'm deliberately missing gas option here // const data = await contract.methods.myMethod().send({ from: account, gasPrice }); } if (this.state.typeofuser == "Distributer") { let id = this.state.id // console.log(id) const am = supplychain.methods.setdistdetails(this.state.to, this.state.sid, this.state.eid).send({ from: r[0] }).then(re => { // console.log("this is very good", re) // console.log(re.transactionHash) this.Auth.fetch('http://localhost:5000/api/setdist', { method: 'POST', body: JSON.stringify({ tid: re.transactionHash, medname: this.state.passmedname, sid: this.state.sid, eid: this.state.eid, to: this.state.to, toname: this.state.toname, acc: r[0] }) }).then(res => { this.setState({ results: res, loading: false }) // console.log(this.state) this.Auth.fetch('http://localhost:5000/api/updatenot', { method: 'POST', body: JSON.stringify({ Id: id, med: this.state.eid - this.state.sid + 1 //send id and remove from notifs }) }).then(res => { this.setState({ results: res, id: '' }) // console.log(this.state) window.location.reload(); }) .catch(err => { // console.log(err) }) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) } if (this.state.typeofuser == "Retailer") { let id = this.state.id const am = supplychain.methods.sell(this.state.sid).send({ from: r[0] }).then(re => { // console.log(re.transactionHash) this.Auth.fetch('http://localhost:5000/api/sell', { method: 'POST', body: JSON.stringify({ tid: re.transactionHash, medname: this.state.passmedname, sid: this.state.sid, acc: r[0] }) }).then(res => { this.setState({ results: res, loading: false }) // console.log(this.state) this.Auth.fetch('http://localhost:5000/api/updatenot', { method: 'POST', body: JSON.stringify({ Id: id, med: 1 //send id and remove from notifs }) }).then(res => { this.setState({ results: res, id: '' }) // console.log(this.state) window.location.reload(); }) .catch(err => { // console.log(err) }) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) } }).catch(err => { // console.log(err) this.setState({ loading: false }) }) this.setState() }) } constructor(props) { super(props) this.Auth = new AuthService() this.state = { mytry: true, id: '', loading: false, addmedi: false, userName: '', notifi: false, showForward: false, typeofuser: '', Name: '', results: [], notif: [], medname: '', manuname: '', sid: '', eid: '', to: '', toname: '', medlist: [], color: ['rgba(252, 222, 251,0.1)'], accountName: '', showeid: '', maxeid: '', passmedname: '' } } fillRange = (start, end) => { var a = new Array(end - start + 1); var i = 0; for (i = 0; i <= (end - start); i++) a[i] = Number(start) + i; return a }; handleChange = (e) => { let x = e.target.name this.setState( { [x]: e.target.value } ) this.getTrans() } mytryHandler = () => { this.getTrans() this.setState({ mytry: true }); this.setState({ addmedi: false }); this.setState({ notifi: false }); } adddmediHandler = () => { this.setState({ mytry: false }); this.setState({ addmedi: true }); this.setState({ notifi: false }); } notifiHandler = () => { this.setState({ mytry: false }); this.setState({ addmedi: false }); this.setState({ notifi: true }); } acceptHandler = (sid, eid, from, id) => { // alert("Please accept the transaction in metamask and reject if any error") swal({ title: "Please Note", text: "Please accept the transaction in metamask and reject if any error", icon: "success", dangerMode: true, }).then(willDe => { this.setState({ loading: true }) const a = web3.eth.getAccounts().then(r => { // console.log(from) if (this.state.typeofuser == "Distributer") { const am = supplychain.methods.acceptdist(sid, eid, from).send({ from: r[0] }).then(re => { this.setState({ showForward: true, loading: false }); this.Auth.fetch('http://localhost:5000/api/acceptmeds', { method: 'POST', body: JSON.stringify({ //send id Id: id }) }).then(res => { this.getNotifs() this.setState({ results: res }) // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) } if (this.state.typeofuser == "Retailer") { const am = supplychain.methods.setretaildetails(sid, eid, from).send({ from: r[0] }).then(re => { this.setState({ showForward: true, loading: false }); this.Auth.fetch('http://localhost:5000/api/acceptmeds', { method: 'POST', body: JSON.stringify({ //send id Id: id }) }).then(res => { this.getNotifs() this.setState({ results: res }) // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) } }).catch(err => { // console.log(err) }) }) } receiveHandler = (sid, eid, from, id) => { const allLine = this.fillRange(sid, eid); swal({ title: "Please Note", text: "Please accept the transaction in metamask and reject if any error", icon: "success", dangerMode: true, }).then(willDe => { this.setState({ loading: true }) const a = web3.eth.getAccounts().then(r => { // console.log(from) if (this.state.typeofuser == "Distributer") { const am = supplychain.methods.rdist(sid, eid, from).send({ from: r[0] }).then(re => { this.Auth.fetch('http://localhost:5000/api/acceptmeds', { method: 'POST', body: JSON.stringify({ //send id Id: id }) }).then(res => { this.getNotifs() this.setState({ results: res, loading: false }) // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) } else if (this.state.typeofuser == "Manufacturer") { const am = supplychain.methods.rman(sid, eid, from).send({ from: r[0] }).then(re => { this.Auth.fetch('http://localhost:5000/api/acceptmeds', { method: 'POST', body: JSON.stringify({ //send id Id: id }) }).then(res => { this.getNotifs() this.setState({ results: res, loading: false }) // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) } }).catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) }) } declineHandler = (sid, eid, from, id, medname) => { const allLine = this.fillRange(sid, eid); console.log("this is med name", medname) swal({ title: "Please Note", text: "Please accept the transaction in metamask and reject if any error", icon: "success", dangerMode: true, }).then(willde => { this.setState({ loading: true }) const a = web3.eth.getAccounts().then(r => { // console.log(from) const am = supplychain.methods.decline(sid, eid, from).send({ from: r[0] }).then(re => { this.setState({ showForward: true }); this.Auth.fetch('http://localhost:5000/api/rejectmeds', { method: 'POST', body: JSON.stringify({ //send id Id: id, sid: sid, eid: eid, medlist: allLine, medname: medname, tid: re.transactionHash, }) }).then(res => { this.getNotifs() this.setState({ results: res, loading: false }) this.setState({}) // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) }).catch(err => { // console.log(err) }) }) // alert("Please accept the transaction in metamask and reject if any error") } forwardHandler = (id, medlist, sid, passmedname) => { this.setState({ id: id, sid: sid }) let a = medlist.length; var b = "Max " + medlist[a - 1]; this.setState({ showeid: b }) // console.log(medlist) this.setState({ medlist: medlist }) this.setState({ addmedi: true }); this.setState({ notifi: false, passmedname: passmedname }); } backTrackHandler = (id, sid, eid, from, medlist, medname) => { const allLine = this.fillRange(sid, eid); swal({ title: "Please Note", text: "Please accept the transaction in metamask and reject if any error", icon: "success", dangerMode: true, }).then(willDe => { this.setState({ loading: true }) const a = web3.eth.getAccounts().then(r => { // console.log(from) if (this.state.typeofuser == "Distributer") { const am = supplychain.methods.backtrack(sid, eid).send({ from: r[0] }).then(re => { this.Auth.fetch('http://localhost:5000/api/backtrack', { method: 'POST', body: JSON.stringify({ //send id //send id Id: id, sid: sid, eid: eid, medlist: allLine, medname: medname, tid: re.transactionHash, }) }).then(res => { this.getNotifs() this.setState({ results: res, loading: false }) // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) this.setState({ loading: false }) }) } }).catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) }) } logout = () => { this.Auth.logout() this.setState() } render() { if (this.state.loading === true) { return (<div className="Loader"><img className="Image" /></div>) } else { // this.getTrans() let disp = ( <div className="NURD"> <h3 className="NUN">No Transaction Data</h3> </div> ); let notif = '' let sb = (<div> <input type="text" name='Name' className="searchinput speclassi" placeholder="Enter Transaction Id" onChange={this.handleChange} style={{ float: 'left', textIndent: 8 }}></input><GoSearch style={{ float: 'left', marginTop: 10, marginLeft: -30, fontSize: 22, opacity: 0.8 }} /><br /><br /> </div>) var colcou = -1; if (this.state.results.length > 0) { this.state.results = this.state.results.filter((send) => { return send.transid.indexOf(this.state.Name) !== -1; }); } if (this.state.results.length) { sb = (<div> <input type="text" name='Name' className="searchinput speclassi" placeholder="Enter Transaction Id" onChange={this.handleChange} style={{ float: 'left', textIndent: 8 }}></input><GoSearch style={{ float: 'left', marginTop: 10, marginLeft: -30, fontSize: 22, opacity: 0.8 }} /><br /><br /> </div>); disp = this.state.results.map(r => { // console.log("This i want", r); var res = r.dot.split("T"); var resdate = res[0]; let daychange = resdate.split('-'); let year = daychange[0]; let month = daychange[1]; let date = daychange[2]; // console.log(date); var res1 = res[1].split(".") var restime = res1[0]; // console.log(restime); let hourminsec = restime.split(':') let hour = parseInt(hourminsec[0]) let min = parseInt(hourminsec[1]) let sec = parseInt(hourminsec[2]) min = min + 30; if (min > 60) { min = min - 60; hour = hour + 1; } hour = hour + 5; if (hour > 24) { if (date != 31) { date = date + 1; } else { date = 1; } hour = hour - 24; } daychange[0] = year.toString(); daychange[1] = month.toString(); daychange[2] = date.toString(); resdate = daychange.join('-'); hourminsec[0] = hour.toString(); hourminsec[1] = min.toString(); hourminsec[2] = sec.toString(); restime = hourminsec.join(':') // console.log(restime); if (colcou === 1) { colcou = 0; } else { colcou = colcou + 1; } if (r.Toname === undefined) { r.Toname = "Customer" } return (<Col sm={4}> <Card style={{ marginBottom: 50 }} border="secondary" className="detailbox"> <Card.Header style={{ fontWeight: 550 }}>{r.transid}</Card.Header> <Card.Body style={{ backgroundColor: this.state.color[colcou] }}> {/* <Card.Title>{r.transid}</Card.Title> */} <Card.Text> { r.medname != undefined ? <div> <p className="CardTitle">Medicine Name : </p><p className="CardContent" style={{ color: 'blue', fontWeight: 500 }}>{r.medname}</p> </div> : <p></p> } <p className="CardTitle">From : </p><p className="CardContent">{r.name}</p> <p className="CardTitle">Address : </p><p className="CardContent">{r.from}</p> <p className="CardTitle">To : </p><p className="CardContent">{r.Toname}</p> { r.to !== undefined ? <div> <p className="CardTitle">Address : </p><p className="CardContent">{r.to}</p> </div> : null } <p className="CardTitle">Sid : </p><p className="CardContent"> {r.sid}</p> { r.eid !== undefined ? <div> <p className="CardTitle">Eid : </p><p className="CardContent">{r.eid}</p> </div> : null } <p className="CardTitle">Number Of Meds : </p><p className="CardContent">{r.meds}</p> </Card.Text> </Card.Body> <Card.Footer> <small className="text-muted "><p className="CardTitle">Trancastion date & time:</p><p className="CardContent">{resdate} {restime}</p></small> </Card.Footer> </Card> </Col> ) }) } notif = ( <div className="NURD"> <h3 className="NUN" style={{ marginTop: 45 }}>No User Notifications</h3> </div> ); var count = 0; var colco = -1; if (this.state.notif.length) { notif = this.state.notif.map(r => { if (r.accepted == false) { count = count + 1; } if (colco === 1) { colco = 0; } else { colco = colco + 1; } if (r.Toname == undefined) { r.Toname = "Customer" } if (r.msg == undefined) { // console.log("This is Proper medicine"); return (<Col sm={4}><Card style={{ marginBottom: 50 }} border="secondary" className="detailbox"> <Card.Header style={{ fontWeight: 550 }}>{r.transid}</Card.Header> <Card.Body style={{ backgroundColor: this.state.color[colco] }}> {/* <Card.Title>{r.transid}</Card.Title> */} <Card.Text> { // console.log(r) } { r.medname != undefined ? <div> <p className="CardTitle">Medicine Name : </p><p className="CardContent" style={{ color: 'blue', fontWeight: 500 }}>{r.medname}</p> </div> : <p></p> } <p className="CardTitle">From : </p><p className="CardContent">{r.name}</p> <p className="CardTitle">Address : </p><p className="CardContent">{r.from}</p> <p className="CardTitle">To : </p><p className="CardContent">{r.Toname}</p> <p className="CardTitle">Address: </p><p className="CardContent">{r.to}</p> <p className="CardTitle">Sid : </p><p className="CardContent">{r.sid}</p> <p className="CardTitle">Eid : </p><p className="CardContent">{r.eid}</p> <p className="CardTitle">Number Of Meds : </p><p className="CardContent">{r.meds}</p> </Card.Text> </Card.Body> <Card.Footer> { r.accepted === false ? <div> <Button variant="outline-success" className="abut" onClick={() => this.acceptHandler(r.sid, r.eid, r.from, r._id)} value={r}>Accept</Button><Button variant="outline-danger" className="rejectBut abut" onClick={() => this.declineHandler(r.sid, r.eid, r.from, r._id, r.medname)} value={r}>Decline</Button> </div> : <Button variant="outline-primary" className="abut" onClick={() => { this.forwardHandler(r._id, r.medlist, r.sid, r.medname) }}>Forward</Button> } </Card.Footer> </Card></Col> ) } else { // console.log("Declined ", r.msg); // console.log("Type of user active ", this.state.typeofuser) let btou = ''; if (this.state.typeofuser !== "Manufacturer") { btou = (<Button variant="outline-primary" className="abut" onClick={() => { this.backTrackHandler(r._id, r.sid, r.eid, r.from, r.medlist, r.medname) }}>BackTrack</Button>) } return (<Col sm={4}><Card style={{ marginBottom: 50 }} border="secondary" className="detailbox"> <Card.Header style={{ fontWeight: 550 }}>{r.transid}</Card.Header> <Card.Body style={{ backgroundColor: this.state.color[colco] }}> {/* <Card.Title>{r.transid}</Card.Title> */} <Card.Text> { // console.log(r) } { r.medname != undefined ? <div> <p className="CardTitle">Medicine Name : </p><p className="CardContent" style={{ color: 'blue', fontWeight: 500 }}>{r.medname}</p> </div> : <p></p> } <p className="CardTitle">From : </p><p className="CardContent">{r.name}</p> <p className="CardTitle">Address : </p><p className="CardContent">{r.from}</p> <p className="CardTitle">To : </p><p className="CardContent">{r.Toname}</p> <p className="CardTitle">Address: </p><p className="CardContent">{r.to}</p> <p className="CardTitle">Sid : </p><p className="CardContent">{r.sid}</p> <p className="CardTitle">Eid : </p><p className="CardContent">{r.eid}</p> <p className="CardTitle">Number Of Meds : </p><p className="CardContent">{r.meds}</p> </Card.Text> </Card.Body> <Card.Footer> { r.accepted === false ? <div> <Button variant="outline-success" className="abut" onClick={() => this.receiveHandler(r.sid, r.eid, r.from, r._id)} value={r}>Receive</Button> </div> : btou } </Card.Footer> </Card></Col> ) } // console.log("This is count ",count,r.accepted); // console.log("This is notifi", r); }) } let nav = '' if (this.state.typeofuser !== 'Retailer') nav = <Nav.Link eventKey={1} href="" onClick={this.adddmediHandler}>Add Medicine</Nav.Link> else { nav = <Nav.Link eventKey={1} href="" onClick={this.adddmediHandler}>Sell Medicine</Nav.Link> } if (this.state.typeofuser === 'Distributer') nav = '' var noN = '' let nav1 = '' // if (this.state.typeofuser !== 'Manufacturer') nav1 = <Nav.Link eventKey={4} href="" onClick={this.notifiHandler}>Notification { count === 0 ? <sup style={{ fontWeight: 550, color: 'red', fontSize: 16 }}>{noN} </sup> : <sup style={{ fontWeight: 550, color: 'red', fontSize: 15 }}>{count} </sup> } </Nav.Link> return ( <div className="mainhomediv"> <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark"> <Navbar.Brand href="" className="IconS">Medicare</Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav className="mr-auto"> </Nav> <Nav> {nav} <Nav.Link eventKey={2} href="" onClick={this.mytryHandler}> My Transaction </Nav.Link> {nav1} <Nav.Link eventKey={3} href="/" style={{ 'color': 'white', fontWeight: 550 }} onClick={this.logout}>LogOut <FiLogOut style={{ fontSize: 20, marginBottom: 3 }} /></Nav.Link> </Nav> </Navbar.Collapse> </Navbar> { this.state.mytry === true ? <Container style={{ marginTop: 50 }}> <Row> <Col sm> {/* <input type="text" name='Name' className="searchinput speclassi" placeholder="Enter Transaction Id" onChange={this.handleChange} style={{ float: 'left', textIndent: 8 }}></input><GoSearch style={{ float: 'left', marginTop: 10, marginLeft: -30, fontSize: 22, opacity: 0.8 }} /><br /><br /> */} {sb} </Col> <Col sm> <span className="WelcomeUser">Welcome {this.state.typeofuser} {this.state.accountName.toUpperCase()}</span> </Col> </Row> <br /> <br /> <Row> {disp} </Row> </Container> : null } { this.state.addmedi === true ? this.state.typeofuser == 'Manufacturer' ? <Container style={{ marginTop: 50 }} className="addmedi"> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">Medicine Name:</span> </Col> <Col sm={9}> <input type="text" name='medname' required onChange={this.handleChange} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">Start Id:</span> </Col> <Col sm={9}> <input type="text" name='maxeid' required value={this.state.maxeid} style={{ textIndent: 10 }} placeholder="Fetching id for you..........." /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">End Id:</span> </Col> <Col sm={9}> <input type="text" name='eid' required onChange={this.handleChange} style={{ textIndent: 10 }} placeholder="Must be greater than Start id" /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan"> Distributer Address :</span> </Col> <Col sm={9}> <input type="text" name='to' required onChange={this.handleChange} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">Distributer Name:</span> </Col> <Col sm={9}> <input type="text" name='toname' required onChange={this.handleChange} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">Expiry date(in days):</span> </Col> <Col sm={9}> <input type="text" name='expire' required onChange={this.handleChange} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > </Col> <Col sm={9}> <Button variant="outline-primary" className="addmedibutt" onClick={this.addmed}>Add This Medicine</Button> </Col> </Row> <br /> </Container> : this.state.typeofuser == 'Distributer' ? <Container style={{ marginTop: 50 }} className="addmedi"> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">Start Id:</span> </Col> <Col sm={9}> <input type="text" name='sid' required onChange={this.handleChange} value={this.state.sid} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">End Id:</span> </Col> <Col sm={9}> <input type="text" name='eid' required onChange={this.handleChange} placeholder={this.state.showeid} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan"> Retailer Address { console.log(this.state)}:</span> </Col> <Col sm={9}> <input type="text" name='to' required onChange={this.handleChange} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">Retailer Name:</span> </Col> <Col sm={9}> <input type="text" name='toname' required onChange={this.handleChange} style={{ textIndent: 10 }} /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > </Col> <Col sm={9}> <Button variant="outline-primary" className="addmedibutt" onClick={this.addmed}>Add This Medicine</Button> </Col> </Row></Container> : this.state.typeofuser == 'Retailer' ? <Container style={{ marginTop: 50 }} className="addmedi"> <Row className="addmedirow"></Row> <Row className="addmedirow"> <Col sm={3} > <span className="addmediformspan">Med Id</span> </Col> <Col sm={9}> <input type="text" name='sid' required value={this.state.sid} onChange={this.handleChange} style={{ textIndent: 10 }} placeholder="Click on Forward From Notification to sell" /><br /><br /> </Col> </Row> <Row className="addmedirow"> <Col sm={3} > </Col> <Col sm={9}> <Button variant="outline-primary" className="addmedibutt" onClick={this.addmed}>Sell Medicine</Button> </Col> </Row></Container> : null : null } { this.state.notifi === true ? <Container style={{ marginTop: 50 }}> <Row> {/* <Col sm={3}> */} {notif} {/* </Col> */} </Row> </Container> : null } </div> ); } } } export default withAuth(Home)<file_sep>/Website/frontend/src/Admin_Home/Admin_Home.js import React, { Component } from 'react'; import './Admin_Home.css'; import { FiLogOut } from 'react-icons/fi'; import { FaRegUser, FaIndustry, FaServicestack } from 'react-icons/fa'; import { MdStore } from 'react-icons/md'; import { Nav, Navbar, Card, Container, Col, Row, Button } from 'react-bootstrap'; import AuthService from '../AuthService/AuthService.js'; import withAuth from '../withAuth' import supplychain from '../supplychain'; import web3 from '../web3'; import swal from 'sweetalert'; const img = require('../assets/loader.gif'); class Admin_Home extends Component { componentWillMount() { this.getUsers() this.getDisplayUsers() } getDisplayUsers = () => { // console.log("results"); this.Auth.fetch('http://localhost:5000/api/displayallusers', { method: 'POST', body: JSON.stringify({ }) }).then(res => { this.setState({ displayuserlist: res }) // console.log(this.state) }) .catch(err => { // console.log(err) }) } getUsers = () => { this.Auth.fetch('http://localhost:5000/api/getalluser', { method: 'POST', body: JSON.stringify({ }) }).then(res => { this.setState({ userList: res }) if (res.length > 0) { this.setState({ showInput: true }) } else { this.setState({ showInput: false }) } this.setState({ userListP: res }) // console.log(this.state) }) .catch(err => { // console.log(err) }) } constructor(props) { super(props) this.Auth = new AuthService() this.state = { Name: '', userList: [], userListP: [], results: [], displayuserlist: [], myMed: false, myUser: true, loading: false, displayUser: false, manudis: false, distdis: false, retadis: false, showInput: false } } logout = () => { this.Auth.logout() this.setState() } myUserHandler = () => { this.setState({ myUser: true }); this.setState({ myMed: false }); this.setState({ displayUser: false }); } myMedHandler = () => { this.setState({ myMed: true }); this.setState({ myUser: false }); this.setState({ displayUser: false }); } displayUserHandler = () => { this.setState({ displayUser: true }); this.setState({ myUser: false }); this.setState({ myMed: false }); } manuDisplay = () => { // console.log("You Clicked manufacturer"); this.setState({ manudis: true }); this.setState({ distdis: false }); this.setState({ retadis: false }); } distDisplay = () => { // console.log("You Clicked distributer"); this.setState({ manudis: false }); this.setState({ distdis: true }); this.setState({ retadis: false }); } retaDisplay = () => { // console.log("You Clicked retailer"); this.setState({ manudis: false }); this.setState({ distdis: false }); this.setState({ retadis: true }); } acceptHandler = (id, userName, typeofuser, address) => { // console.log("accept") swal({ title: "Please Note", text: "Please accept the transaction in metamask and reject if any error", icon: "success", dangerMode: true, }).then(willde => { this.setState({ loading: true }) const a = web3.eth.getAccounts().then(r => { // console.log(this.state.typeofuser) const am = supplychain.methods.setuser(typeofuser, address, userName).send({ from: r[0] }).then(re => { this.Auth.fetch('http://localhost:5000/api/accept', { method: 'POST', body: JSON.stringify({ Id: id //send id and remove from notifs }) }).then(res => { this.setState({ loading: false }) this.getUsers() // console.log(this.state) }) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err); this.setState({ loading: false }) }) }) .catch(err => { // console.log(err) }) }) } declineHandler = (id) => { this.Auth.fetch('http://localhost:5000/api/reject', { method: 'POST', body: JSON.stringify({ Id: id //send id and remove from notifs }) }).then(res => { this.setState({}) this.getUsers() this.getDisplayUsers() // console.log(this.state) }) .catch(err => { // console.log(err) }) } handleChange = (e) => { let x = e.target.name this.setState( { [x]: e.target.value } ) if (e.target.value == '') { // console.log("INSIDE") this.getUsers() } } render() { if (this.state.loading === true) { return (<div className="Loader"><img src={img} className="Image" /></div>) } else { let disp = ( <div className="NURD"> <h3 className="NUR">No new user request</h3> </div> ); let dispmed = ( <div className="NURD"> <h3 className="NUR">No Expired Medicines</h3> </div> ); // let dispI = (<div> // <input type="text" name='Name' className="searchinput" placeholder="Enter Username" onChange={this.handleChange} style={{ textIndent: 12 }} /><br /><br /> // </div>) let dispI = ''; let dispmedI = ''; let manuc = 0; let distc = 0; let retac = 0; let dispmanuuser = ''; let dispdistuser = ''; let dispretauser = ''; if (this.state.showInput) { dispI = ( <div> <input type="text" name='Name' className="searchinput" placeholder="Enter Name" onChange={this.handleChange} style={{ textIndent: 12 }} /><br /><br /> </div> ) } if (this.state.myUser) { // console.log(this.state.myUser) this.state.userList = this.state.userList.filter((send) => { return send.name.indexOf(this.state.Name) !== -1; }); // dispI = ( // <div> // <input type="text" name='Name' className="searchinput" placeholder="Enter Name" onChange={this.handleChange} style={{ textIndent: 12 }} /><br /><br /> // </div> // ) if (this.state.userList.length) { console.log(this.state.userList) disp = this.state.userList.map(r => { // console.log(r) return ( <Col sm={4}><Card style={{ marginBottom: 50 }} border="secondary" className="DisCard"> <Card.Body> <Card.Title>{r.name}</Card.Title> <Card.Text> <p className="CardTitle">Address :</p> <p className="CardContent">{r.address}</p> <p className="CardTitle">Username :</p> <p className="CardContent">{r.userName}</p> <p className="CardTitle">Account Type :</p> <p className="CardContent">{r.typeofuser}</p> </Card.Text> </Card.Body> <Card.Footer> <div > <Button variant="outline-success" className="abut" onClick={() => this.acceptHandler(r._id, r.userName, r.typeofuser, r.address)}>Accept</Button> <Button variant="outline-danger" className="rejectBut abut" onClick={() => this.declineHandler(r._id)}>Decline</Button> </div> </Card.Footer> </Card></Col> ) }) } } if (this.state.displayuserlist.length) { // console.log("this is all users", this.state.displayuserlist) dispmanuuser = this.state.displayuserlist.map(r => { if (r.typeofuser == "Manufacturer") { manuc = manuc + 1; return (<Col sm={4}><Card style={{ marginBottom: 50 }} border="secondary" className="DisCard"> <Card.Body> <Card.Title>{r.name}</Card.Title> <Card.Text> <p className="CardTitle">Address : </p> <p className="CardContent">{r.address}</p> <p className="CardTitle">Username : </p><p className="CardContent">{r.userName}</p> <p className="CardTitle"> Account Type :</p> <p className="CardContent">{r.typeofuser}</p> <p className="CardTitle"> Phone :</p> <p className="CardContent">{r.phone}</p> </Card.Text> </Card.Body> {/* <Card.Footer> </Card.Footer> */} </Card></Col> ) } }) dispdistuser = this.state.displayuserlist.map(r => { if (r.typeofuser == "Distributer") { distc = distc + 1; return (<Col sm={4}><Card style={{ marginBottom: 50 }} border="secondary" className="DisCard"> <Card.Body> <Card.Title>{r.name}</Card.Title> <Card.Text> <p className="CardTitle">Address : </p> <p className="CardContent">{r.address}</p> <p className="CardTitle">Username : </p><p className="CardContent">{r.userName}</p> <p className="CardTitle"> Account Type :</p> <p className="CardContent">{r.typeofuser}</p> <p className="CardTitle"> Phone :</p> <p className="CardContent">{r.phone}</p> </Card.Text> </Card.Body> {/* <Card.Footer> </Card.Footer> */} </Card></Col> ) } }) dispretauser = this.state.displayuserlist.map(r => { if (r.typeofuser == "Retailer") { retac = retac + 1; return (<Col sm={4}><Card style={{ marginBottom: 50 }} border="secondary" className="DisCard"> <Card.Body> <Card.Title>{r.name}</Card.Title> <Card.Text> <p className="CardTitle">Address : </p> <p className="CardContent">{r.address}</p> <p className="CardTitle">Username : </p><p className="CardContent">{r.userName}</p> <p className="CardTitle"> Account Type :</p> <p className="CardContent">{r.typeofuser}</p> <p className="CardTitle"> Phone :</p> <p className="CardContent">{r.phone}</p> </Card.Text> </Card.Body> {/* <Card.Footer> </Card.Footer> */} </Card></Col> ) } }) } return ( <div className="maindiv"> <Navbar collapseOnSelect expand="lg" bg="dark" variant="dark"> <Navbar.Brand href="">Medicare</Navbar.Brand> <Navbar.Toggle aria-controls="responsive-navbar-nav" /> <Navbar.Collapse id="responsive-navbar-nav"> <Nav className="mr-auto"> </Nav> <Nav> <Nav.Link eventKey={1} href="" onClick={this.myUserHandler}> Home </Nav.Link> {/* <Nav.Link eventKey={2} href="" onClick={this.myMedHandler}> Expired Med </Nav.Link> */} <Nav.Link eventKey={4} href="" onClick={this.displayUserHandler}> Users </Nav.Link> <Nav.Link eventKey={3} href="/" style={{ 'color': 'white', fontWeight: 550 }} onClick={this.logout}>LogOut <FiLogOut style={{ fontSize: 20, marginBottom: 3 }} /></Nav.Link> </Nav> </Navbar.Collapse> </Navbar> { this.state.myUser === true ? <Container style={{ marginTop: 50 }}> <Row> <Col sm> {/* <input type="text" name='Name' className="searchinput" placeholder="Enter Username" onChange={this.handleChange} style={{ textIndent: 12}}/><br /><br /> */} {dispI} </Col> <Col sm> </Col> </Row> <br /> <br /> <Row> {disp} </Row> </Container> : null } { this.state.myMed === true ? <Container style={{ marginTop: 50 }}> <Row> <Col sm> <input type="text" name='Name' className="searchinput" placeholder="Enter Medicine by id" onChange={this.handleChange} style={{ textIndent: 12 }} /><br /><br /> </Col> <Col sm> </Col> </Row> <br /> <br /> <Row> {dispmed} </Row> </Container> : null } { this.state.displayUser === true ? <Container style={{ marginTop: 50 }}> <Row> <Col sm> </Col> <Col sm> <Card className="text-center" style={{ border: '1px solid ', height: '82%' }}> <Card.Body > <Card.Title><FaRegUser style={{ float: 'left', fontSize: 30, marginTop: -5 }} />Total Users: {this.state.displayuserlist.length} </Card.Title> </Card.Body> </Card> </Col> <Col sm> </Col> </Row> <br /> <br /> <Row> <Col sm> <div className="disbox" onClick={this.manuDisplay}> <div className="dbfd"> <FaIndustry className="dbfdlogo" /> <p>Manufacturer</p> </div> <div className="dbsd"> <h4>{manuc}</h4> </div> </div> </Col> <Col sm> <div className="disbox" onClick={this.distDisplay}> <div className="dbfd"> <FaServicestack className="dbfdlogo" /> <p>Distributers</p> </div> <div className="dbsd"> <h4>{distc}</h4> </div> </div> </Col> <Col sm> <div className="disbox" onClick={this.retaDisplay}> <div className="dbfd"> <MdStore className="dbfdlogo" /> <p>Retailers</p> </div> <div className="dbsd"> <h4>{retac}</h4> </div> </div> </Col> </Row> <br /> <br /> { this.state.manudis === true ? <Row> {dispmanuuser} </Row> : null } { this.state.distdis === true ? <Row> {dispdistuser} </Row> : null } { this.state.retadis === true ? <Row> {dispretauser} </Row> : null } </Container> : null } </div> ); } } } export default withAuth(Admin_Home)<file_sep>/Website/frontend/src/supplychain.js import web3 from './web3'; //const address = '0x7B56A9A6e7c20d865D7486Da64310BEE0bC8Ee1a'; //const address = '0x34d848c48EEc33C040Ea2Ea0B5F30dF90972d1f3'; //const address = '0x9ee9ca71adb5bf25eab0a6383300e1a94a45b8b4'; const address = '0x74A104CA9ABD573FD43C38E77Acb732B6665426A'; const abi=[ { "constant": false, "inputs": [ { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" }, { "name": "_from", "type": "address" } ], "name": "acceptdist", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" } ], "name": "backtrack", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" }, { "name": "_from", "type": "address" } ], "name": "decline", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" }, { "name": "_from", "type": "address" } ], "name": "rdist", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" }, { "name": "_from", "type": "address" } ], "name": "rman", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "_id", "type": "uint256" } ], "name": "sell", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "_to", "type": "address" }, { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" } ], "name": "setdistdetails", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "_medName", "type": "string" }, { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" }, { "name": "_to", "type": "address" }, { "name": "expiryd", "type": "uint256" }, { "name": "expirydate", "type": "string" } ], "name": "setmed", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "sid", "type": "uint256" }, { "name": "lid", "type": "uint256" }, { "name": "_dist", "type": "address" } ], "name": "setretaildetails", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "_role", "type": "string" }, { "name": "_user", "type": "address" }, { "name": "name", "type": "string" } ], "name": "setuser", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "id", "type": "uint256" } ], "name": "checkex", "outputs": [ { "name": "res", "type": "bool" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "_id", "type": "uint256" } ], "name": "getmed", "outputs": [ { "name": "medName", "type": "string" }, { "name": "mname", "type": "string" }, { "name": "dname", "type": "string" }, { "name": "rname", "type": "string" }, { "name": "soldstatus", "type": "bool" }, { "name": "expsts", "type": "bool" }, { "name": "expdate", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "readd", "type": "address[]" }, { "name": "medname", "type": "string" } ], "name": "stockcheck", "outputs": [ { "name": "st", "type": "uint24[]" } ], "payable": false, "stateMutability": "view", "type": "function" } ] // const abi = [ // { // "constant": false, // "inputs": [ // { // "name": "sid", // "type": "uint256" // }, // { // "name": "lid", // "type": "uint256" // }, // { // "name": "_from", // "type": "address" // } // ], // "name": "acceptdist", // "outputs": [], // "payable": false, // "stateMutability": "nonpayable", // "type": "function" // }, // { // "constant": false, // "inputs": [ // { // "name": "_id", // "type": "uint256" // } // ], // "name": "sell", // "outputs": [], // "payable": false, // "stateMutability": "nonpayable", // "type": "function" // }, // { // "constant": false, // "inputs": [ // { // "name": "_to", // "type": "address" // }, // { // "name": "sid", // "type": "uint256" // }, // { // "name": "lid", // "type": "uint256" // } // ], // "name": "setdistdetails", // "outputs": [], // "payable": false, // "stateMutability": "nonpayable", // "type": "function" // }, // { // "constant": false, // "inputs": [ // { // "name": "_medName", // "type": "string" // }, // { // "name": "sid", // "type": "uint256" // }, // { // "name": "lid", // "type": "uint256" // }, // { // "name": "_to", // "type": "address" // }, // { // "name": "expiryd", // "type": "uint256" // } // ], // "name": "setmed", // "outputs": [ // { // "name": "st", // "type": "int8" // } // ], // "payable": false, // "stateMutability": "nonpayable", // "type": "function" // }, // { // "constant": false, // "inputs": [ // { // "name": "sid", // "type": "uint256" // }, // { // "name": "lid", // "type": "uint256" // }, // { // "name": "_dist", // "type": "address" // } // ], // "name": "setretaildetails", // "outputs": [], // "payable": false, // "stateMutability": "nonpayable", // "type": "function" // }, // { // "constant": false, // "inputs": [ // { // "name": "_role", // "type": "string" // }, // { // "name": "_user", // "type": "address" // }, // { // "name": "name", // "type": "string" // } // ], // "name": "setuser", // "outputs": [], // "payable": false, // "stateMutability": "nonpayable", // "type": "function" // }, // { // "constant": true, // "inputs": [ // { // "name": "id", // "type": "uint256" // } // ], // "name": "checkex", // "outputs": [ // { // "name": "res", // "type": "bool" // } // ], // "payable": false, // "stateMutability": "view", // "type": "function" // }, // { // "constant": true, // "inputs": [ // { // "name": "_id", // "type": "uint256" // } // ], // "name": "getmed", // "outputs": [ // { // "name": "medName", // "type": "string" // }, // { // "name": "manufacture", // "type": "address" // }, // { // "name": "mname", // "type": "string" // }, // { // "name": "d", // "type": "address" // }, // { // "name": "dname", // "type": "string" // }, // { // "name": "rname", // "type": "string" // }, // { // "name": "soldstatus", // "type": "bool" // } // ], // "payable": false, // "stateMutability": "view", // "type": "function" // } // ] export default new web3.eth.Contract(abi, address); <file_sep>/Website/backend/Routes/setdist.js const express = require("express"); const mongoose = require("mongoose"); var bodyParser = require('body-parser') const bcrypt = require('bcryptjs'); const verifyToken = require('../Helpers/verifytoken') const saltRounds = 10; const us = require("underscore"); var validator = require("email-validator"); const User = require("../Models/User") const Trans = require('../Models/Transaction') const Meds = require('../Models/Meds') const router = express.Router(); router.use(bodyParser()) router.use(bodyParser.urlencoded({ extended: true })); router.use(bodyParser.json()) router.use(verifyToken) router.post('/', (req, res) => { const username = req.user.userName if (req.body.acc == undefined) { res.send().json({ "msg": "login in to meta mask" }); } console.log(req.body.acc); const trans = new Trans({ medname: req.body.medname, transid: req.body.tid, name: username, from: req.body.acc, to: req.body.to, Toname: req.body.toname, sid: req.body.sid, eid: req.body.eid, meds: req.body.eid - req.body.sid + 1 , dot: Date.now(), accepted: false }) trans.save() .then( resu => { // console.log(resu); res.status(200).send(resu); } ) .catch(err => { // console.log(err) }) }); module.exports = router;<file_sep>/Website/backend/Routes/rejectmed.js const express = require('express'); const verifyToken = require('../Helpers/verifytoken') const bodyParser = require('body-parser') const router = express.Router() const Trans = require('../Models/Transaction') router.use(bodyParser()) router.use(bodyParser.json()) router.use(bodyParser.urlencoded({ extended: true })) router.use(verifyToken) router.post('/', (req, res) => { // console.log(req.body.Id) const re1 = Trans.findOneAndDelete({ _id: req.body.Id }, { accepted: false }).then((updatedDoc1) => { // console.log("reject *****************************") // console.log(updatedDoc1) res.status(200).send(updatedDoc1); const username = req.user.userName const trans = new Trans({ transid: req.body.tid, name: username, from: updatedDoc1.to, to: updatedDoc1.from, sid: req.body.sid, eid: req.body.eid, medname: req.body.medname, medlist: req.body.medlist , dot: Date.now(), accepted: false, Toname: updatedDoc1.name, exp: updatedDoc1.exp , meds: req.body.medlist.length, msg: 'Your has been declined by the reciever' }) trans.save() .then( resu => { // console.log(resu); res.status(200).send(resu); } ) .catch(err => { // console.log(err) }) }).catch(err => { // console.log(err) }) }); module.exports = router<file_sep>/Website/frontend/src/login.js import React, { Component } from 'react'; import './login.css'; import { FaUserAlt, FaKey } from 'react-icons/fa'; import swal from 'sweetalert'; import { Form, Button } from 'react-bootstrap'; import AuthService from './AuthService/AuthService' import datalist from 'react-datalist'; class login extends Component { constructor(props) { super(props) this.state = { login: true, signup: false, userName: '', password: '', phone: '', email: '', LcNo: '', Location: '', name: '', data: ['<NAME>', 'Delhi', 'Banglore', 'Jodpur', 'Aurangabad', 'Pune', 'Nagpur', 'Vasai-Virar', 'Navghar', 'Nasik', 'Gujrat', 'Panjab', 'Chennai'], address: '', UserType: 'Distributer', formErrors: { email: '', password: '', phone: '', first: '', user: '' }, emailValid: false, passwordValid: false, phoneValid: false, firstValid: false, formValid1: false, formValid2: false, userValid: false, checkforusername: '' } this.Auth = new AuthService(); } validateField(fieldName, value) { let fieldValidationErrors = this.state.formErrors; let emailValid = this.state.emailValid; let passwordValid = this.state.passwordValid; let phoneValid = this.state.phoneValid; let firstValid = this.state.firstValid; let userValid = this.state.userValid; switch (fieldName) { case 'email': emailValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i); fieldValidationErrors.email = emailValid ? '' : 'Email is invalid'; break; case 'password': passwordValid = value.length >= 6; fieldValidationErrors.password = passwordValid ? '' : 'Password is too short'; break; case 'phone': phoneValid = value.match(/^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$/) fieldValidationErrors.phone = phoneValid ? '' : 'Phone No. is invalid'; break; case 'name': firstValid = value.length > 3 fieldValidationErrors.first = firstValid ? '' : 'First name is too small'; break; case 'userName': userValid = value.length > 4 fieldValidationErrors.user = userValid ? '' : 'Username is too small'; break; default: break; } this.setState({ formErrors: fieldValidationErrors, emailValid: emailValid, phoneValid: phoneValid, firstValid: firstValid, passwordValid: passwordValid, userValid: userValid }, this.validateForm); } validateForm() { // console.log(this.state) this.setState({ formValid1: this.state.firstValid && this.state.emailValid && this.state.phoneValid && this.state.userValid && this.state.passwordValid, }); } handleFormSubmit1 = (e) => { // console.log(this.state) e.preventDefault(); // console.log(this.state.LcNo); this.Auth.fetch('http://localhost:5000/api/signup', { method: 'POST', body: JSON.stringify({ "email": this.state.email, "password": <PASSWORD>, "userName": this.state.userName, "name": this.state.name, "LcNo": this.state.LcNo, 'phone': this.state.phone, "address": this.state.address, "location": this.state.Location, "userType": this.state.UserType }) }).then(res => { // console.log("signup", res) this.props.history.replace('/') }) .catch(err => { // console.log('signup', err) }) } handleFormSubmit = (e) => { // e.preventDefault(); // this.Auth.login(this.state.username, this.state.password) e.preventDefault(); // console.log(this.state) this.Auth.login(this.state.userName, this.state.password) .then(res => { if (this.state.userName === 'admin') this.props.history.replace('/Admin'); else this.props.history.replace('/'); }) .catch(err => { if (err == "TypeError: Cannot read property 'json' of undefined") { // console.log("I did it") swal({ title: "Please Note", text: "Wrong Username or Password", icon: "warning", dangerMode: true, }).then(willbe => { window.location.reload(); }) // alert(err); } else if (err == "TypeError: Failed to fetch") { // console.log(err) // alert(err); } // console.log("This is err", err) }) } handleChange = (e) => { let x = e.target.name let value = e.target.value this.setState( { [x]: e.target.value }, () => { this.validateField(x, value) } ) } handleUsernameChange = (e) => { let x = e.target.name let value = e.target.value this.setState( { [x]: e.target.value }, () => { this.validateField(x, value) } ) this.Auth.fetch('http://localhost:5000/api/checkforusername', { method: 'POST', body: JSON.stringify({ "username": value, }) }).then(res => { // console.log("signup", res) // console.log(res.length) if (res.length > 0) { this.setState({ checkforusername: 'Username already exist' }) } else { this.setState({ checkforusername: '' }) } }) .catch(err => { // console.log('signup', err) }) } handleThisChange = (e) => { this.setState( { UserType: e.target.value } ) } componentWillMount() { if (this.Auth.loggedIn()) this.props.history.replace('/'); } loginstateHandler = () => { this.setState({ login: false }); this.setState({ signup: true }); } signupstateHandler = () => { this.setState({ login: true }); this.setState({ signup: false }); } render() { return ( <div className="loginMainDiv"> <div className="LFirst"> <header className="toolbar"> <nav className="nevigation_menu"> <div className="Llogo_style"> <p className="MYAPPNAME">Medicare</p> </div> </nav> </header> </div> { this.state.login === true ? <div className="LSecond"> <div className="Logindiv"> <div className="TopDesc"> <h3>Login</h3><hr /> </div> <div className="Lformdiv"> <form> <div> <span style={{ float: 'left', marginRight: 250 }}>Username:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}></span> <input type="text" name='userName' required onChange={this.handleChange} style={{ border: 'none', textIndent: 35 }} /><br /><br /> <p style={{ marginTop: -56, fontSize: 17, marginLeft: 10, opacity: 0.7, width: 20 }}><FaUserAlt /></p> </div> <div> <span style={{ float: 'left', marginRight: 250 }}>Password:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}></span> <input type="<PASSWORD>" name='password' required onChange={this.handleChange} style={{ border: 'none', textIndent: 35 }} /><br /><br /> <p style={{ marginTop: -56, fontSize: 17, marginLeft: 10, opacity: 0.7, width: 20 }}><FaKey /></p> </div> <Button type="submit" variant="primary" className="formbut" onClick={this.handleFormSubmit}>Sign In</Button><br /><br /> </form> </div> <hr /> <div className="Lredirectdiv"> <p>Not a member</p><p className="clickonme" onClick={this.loginstateHandler}>Sign Up</p> </div> </div> </div> : null } { this.state.signup === true ? <div className="LSecond"> <div className="Logindiv"> <div className="TopDesc"> <h3>Sign Up</h3><hr /> </div> <div className="Lformdiv"> <form> <div> <span style={{ float: 'left', marginRight: 240 }}>Name:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}>{this.state.formErrors.first}</span> <input type="text" name='name' required onChange={this.handleChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> </div> <div> <span style={{ float: 'left', marginRight: 200 }}>Username:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}>{this.state.formErrors.user}</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}>{this.state.checkforusername}</span> <input type="text" name='userName' required onChange={this.handleUsernameChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> </div> <div> <span style={{ float: 'left', marginRight: 245 }}>Email:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}>{this.state.formErrors.email}</span> <input type="text" name='email' required onChange={this.handleChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> </div> <div> <span style={{ float: 'left' }}>MetaMask Address:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}></span> <input type="text" name='address' required onChange={this.handleChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> </div> <div> <span style={{ float: 'left', marginRight: 230 }}>Phone:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}>{this.state.formErrors.phone}</span> <input type="text" name='phone' required onChange={this.handleChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> </div> <Form.Group controlId="exampleForm.ControlSelect1"> <span style={{ float: 'left', marginRight: 200, marginBottom: 16 }}>UserType:</span> <Form.Control as="select" style={{ border: 'none', }} value={this.state.UserType} onChange={this.handleThisChange}> <option>Manufacturer</option> <option>Distributer</option> <option>Retailer</option> </Form.Control> </Form.Group> <div> <span style={{ float: 'left' }}>Lisence No.:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}></span> <input type="text" name='LcNo' required onChange={this.handleChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> </div> <div> <span style={{ float: 'left' }}>Location:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}></span> <input type="text" name='Location' list="data" required onChange={this.handleChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> <datalist id="data" > {this.state.data.map(k => <option key={k} value={k} /> )} </datalist> </div> <div> <span style={{ float: 'left', marginRight: 200 }}>Password:</span> <span style={{ 'color': 'red', float: 'left', fontSize: 16 }}>{this.state.formErrors.password}</span> <input type="password" name='password' required onChange={this.handleChange} style={{ border: 'none', textIndent: 8 }} /><br /><br /> </div> <Button type="submit" variant="primary" className="formbut" disabled={!this.state.formValid1} onClick={this.handleFormSubmit1}>Sign Up</Button><br /><br /> </form> </div> <hr /> <div className="Lredirectdiv"> <p>Already a member</p><p className="clickonme" onClick={this.signupstateHandler}>Sign In</p> </div> </div> </div> : null} </div> ); } } export default login
9eb5bbdc2facd78331461cefe364fe69360aebf3
[ "JavaScript", "Markdown" ]
10
JavaScript
VVK-3/Medicare-App-and-Website
60e2dcd3f9a40da752f4b656066d4dca08a4aafe
71b23c3460c6cb2aece5374cb991022f29c809b7
refs/heads/main
<file_sep>#!/bin/bash TodaysDate=$(date +"%m-%d-%Y") result=${PWD##*/} apacheFolder=/data/data/com.termux/files/home/Apache-configure/ home=$HOME apache="Apache-configure" welcome () { echo "Hello" echo " " echo " " echo "Navigating to your ${home}/${apache} folder if we arent there already!!" echo " " sleep 0.8 } dirCheck () { if [ $result == $apache ] ; then echo "You already there." echo " " sleep 2 echo "Moving on..." echo " " sleep 2 setCL_Choice else echo "Going to your $home/$apache folder..." echo " " cd $apacheFolder sleep 2 echo "$PWD" && ls && sleep 4 echo "done" echo " " fi } rememberCLChoice () { if [ ! -z $CL_Choice ] ; then value=$CL_Choice fi ### echo "\nWould you like to see a changelog?: ${value}" if [ -z "$value" ] ; then echo "Looks like this is your first time running the script." echo " " sleep 2 read -p "Would you like to view a changelog?: " CL_Choice echo "Alright!" sed -i "7 i\does_user_want_cl=$CL_Choice" $HOME/cl.sh echo " " sleep 2 else echo "$value" fi } # Welcome them. welcome # Check their directory dirCheck # Remember their choice rememberCLChoice
97a1e6bff746faea9a82dacfab59c4f5e38bc71c
[ "Shell" ]
1
Shell
HiFiiDev/Apache-configure
02bf828b243e097590171d6ea1072cb67e1de394
395b7a1d0920a2201d93cd6b973dc1cf2eed992e
refs/heads/master
<repo_name>BHAUTIK04/YoutubeDownloader<file_sep>/requirements.txt certifi==2018.4.16 chardet==3.0.4 click==6.7 docopt==0.6.2 Flask==1.0.2 google-api-python-client==1.6.7 httplib2==0.11.3 idna==2.6 itsdangerous==0.24 Jinja2==2.10 MarkupSafe==1.0 oauth2client==4.1.2 pyasn1==0.4.2 pyasn1-modules==0.2.1 requests==2.18.4 rsa==3.4.2 six==1.11.0 uritemplate==3.0.0 urllib3==1.22 Werkzeug==0.14.1 youtube-mp3==0.1.2 <file_sep>/art.py from flask import Flask from flask import request from flask import render_template from flask import send_file import json import time from googleapiclient.discovery import build from googleapiclient.errors import HttpError app = Flask(__name__) app.config["TEMPLATES_AUTO_RELOAD"] = True DEVELOPER_KEY = '' YOUTUBE_API_SERVICE_NAME = 'youtube' YOUTUBE_API_VERSION = 'v3' @app.route("/") def index(): return render_template("index.html") @app.route("/search", methods = ["POST", "GET"]) def search(): if request.method == "POST": print(type(request.form)) req_data = request.form.get("search", "youtube") print(req_data) youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY) search_response = youtube.search().list(q=req_data, part='id,snippet', maxResults=25).execute() videos = [] count = 0 #print(json.dumps(search_response)) # print(i["snippet"]["publishedAt"].split("T")[0]) for i in search_response["items"]: v_data = {} if i["id"]["kind"] == "youtube#video" and count < 10 : v_data["thumbnails"] = i["snippet"]["thumbnails"]['high']['url'] v_data["published_at"] = i["snippet"]["publishedAt"].split("T")[0] v_data["title"] = i["snippet"]["title"] v_data["description"] = i["snippet"]["description"] v_data["video_id"] = i["id"]["videoId"] videos.append(v_data) count += 1 # print(videos) # time.sleep(20) return json.dumps(videos) elif request.method == "GET": return render_template("search.html") @app.route("/download/<video_id>",methods=["GET"]) def downloadAudio(video_id): file_name = '/tmp/taj.mp3' print(video_id) time.sleep(10) return send_file(file_name, mimetype='audio/mpeg3', attachment_filename='video_id.mp3')
07f642465d73e410a2ff7d040e80c6116b423bf5
[ "Python", "Text" ]
2
Text
BHAUTIK04/YoutubeDownloader
e6d323eee7e286e6b26b7429235a9c4c33110bc4
483627dee1edd9b0e8ce5a6f92d4dc31244d345c
refs/heads/master
<file_sep>import * as Yup from "yup"; const diagnosisValidationSchema = Yup.object().shape({ answers: Yup.array() .of(Yup.number().oneOf([0, 1], "Wykryto brakującą odpowiedź")) .required("Odpowiedzi są wymagane"), }); export default diagnosisValidationSchema; <file_sep>import React from "react"; import { StyleSheet, TouchableOpacity, ViewPropTypes } from "react-native"; import PropTypes from "prop-types"; import FontForgeIcon from "./FontForgeIcon"; import { Colors } from "../../constants/styles"; const CircleButton = ({ style, onPress, icon, size, color }) => { return ( <TouchableOpacity style={[styles.button, style]} onPress={onPress}> <FontForgeIcon name={icon} size={size} color={color} /> </TouchableOpacity> ); }; const styles = StyleSheet.create({ button: { justifyContent: "center", alignItems: "center", }, }); CircleButton.defaultProps = { style: {}, color: Colors.PINK_MEDIUM, }; CircleButton.propTypes = { icon: PropTypes.string.isRequired, onPress: PropTypes.func.isRequired, size: PropTypes.number.isRequired, style: ViewPropTypes.style, color: PropTypes.string, }; export default CircleButton; <file_sep>import React from "react"; import { StyleSheet, View, Text, ViewPropTypes } from "react-native"; import { TouchableOpacity } from "react-native-gesture-handler"; import PropTypes from "prop-types"; import { Colors, Typography } from "../../constants/styles"; import FontForgeIcon from "../common/FontForgeIcon"; const ButtonWithLabel = ({ style, onPress, size, color, icon, label }) => { return ( <TouchableOpacity onPress={onPress} style={[styles.button, style]}> <View style={styles.menuIcon}> <FontForgeIcon name={icon} size={size} color={color} style={styles.instaIcon} /> <Text style={[styles.instaText, { color }]}>{label}</Text> </View> </TouchableOpacity> ); }; const styles = StyleSheet.create({ button: { flex: 1, }, menuIcon: { flex: 1, flexDirection: "column", margin: 20, }, instaIcon: { alignSelf: "center", }, instaText: { color: Colors.PINK, fontSize: Typography.FONT_SIZE_12, fontFamily: Typography.FONT_FAMILY_REGULAR, alignSelf: "center", paddingTop: 5, }, }); ButtonWithLabel.defaultProps = { style: {}, color: Colors.PINK, }; ButtonWithLabel.propTypes = { style: ViewPropTypes.style, onPress: PropTypes.func.isRequired, size: PropTypes.number.isRequired, color: PropTypes.string, icon: PropTypes.string.isRequired, label: PropTypes.string.isRequired, }; export default ButtonWithLabel; <file_sep>import sys import csv import sqlite3 if len(sys.argv) < 4: print('python3 importCsvToDb.py path_to_db path_to_csv table_name') else: path_to_db = sys.argv[1] path_to_csv = sys.argv[2] table_name = sys.argv[3] conn = sqlite3.connect(path_to_db) c = conn.cursor() with open(path_to_csv,'r', encoding='utf-8') as csv_table: csv_reader = csv.reader(csv_table, delimiter=',') column_names = ','.join(next(csv_reader)) to_db = [record for record in csv_reader] c.executemany(f"INSERT INTO {table_name} ({column_names}) VALUES (?, ?);", to_db) conn.commit() conn.close() <file_sep>import { StyleSheet } from "react-native"; import { Colors, Typography } from "./index"; export default StyleSheet.create({ titleText: { marginLeft: 30, marginBottom: 20, color: Colors.PURPLE, fontSize: Typography.FONT_SIZE_16, fontFamily: Typography.FONT_FAMILY_BOLD, }, subtitleText: { color: Colors.PURPLE, marginLeft: 30, paddingTop: 10, fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_REGULAR, }, listItemFieldText: { flex: 1, color: Colors.PURPLE, fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_REGULAR, alignSelf: "flex-start", marginLeft: 50, marginRight: 20, paddingTop: 7, }, nestedListItemFieldText: { flex: 1, color: Colors.PURPLE, fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_REGULAR, alignSelf: "flex-start", marginLeft: 70, paddingTop: 7, }, commentFieldText: { flex: 1, color: Colors.PURPLE, fontSize: Typography.FONT_SIZE_12, fontFamily: Typography.FONT_FAMILY_REGULAR, alignSelf: "flex-start", marginLeft: 50, marginRight: 20, paddingTop: 7, }, choice: { marginRight: 15, marginLeft: 60, }, }); <file_sep>import React, { useContext } from "react"; import PropTypes from "prop-types"; import { Alert, StyleSheet } from "react-native"; import DiagnosisForm from "../../components/diagnosisForm/DiagnosisForm"; import DiagnosisContainer from "./DiagnosisContainer"; import useDiagnosisForm from "../../modules/hooks/useDiagnosisForm"; import TextButton from "../../components/common/TextButton"; import { DiagnosisContext } from "../../modules/context/DiagnosisContext"; const MajorQuestionsForm = ({ navigation, route }) => { const { addAnswers, addModuleQuestions, modules } = useContext( DiagnosisContext ); const { moduleCode } = route.params; const moduleAnswers = modules[moduleCode].majorAnswers; const { minMajorTrue } = modules[moduleCode]; const isMinor = 0; const [questions, defaultAnswers] = useDiagnosisForm(moduleCode, isMinor); const answers = moduleAnswers || defaultAnswers; const goOnDetailsQuestions = (answersValues) => { return answersValues.reduce((a, b) => a + b, 0) >= minMajorTrue; }; const onSubmit = (answersValues) => { if (goOnDetailsQuestions(answersValues)) { addAnswers(moduleCode, answersValues, isMinor); addModuleQuestions(moduleCode, questions, isMinor); navigation.navigate("Minor", { moduleCode, majorAnswers: answersValues }); } else { Alert.alert( "Informacja", "Pacjent nie spełnia warunków podstawowych modułu", [ { text: "Ok", style: "cancel", onPress: () => { navigation.goBack(); }, }, ] ); } }; return ( <DiagnosisContainer module={module}> <DiagnosisForm onSubmit={onSubmit} questions={questions} answers={answers} footerComponent={ <TextButton onPress={onSubmit} text="Sprawdź warunki podstawowe" /> } footerComponentStyle={styles.footerComponentStyle} /> </DiagnosisContainer> ); }; const styles = StyleSheet.create({ footerComponentStyle: { marginTop: 20, }, }); MajorQuestionsForm.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, goBack: PropTypes.func.isRequired, }).isRequired, route: PropTypes.shape({ params: PropTypes.shape({ moduleCode: PropTypes.string.isRequired, }).isRequired, }).isRequired, }; export default MajorQuestionsForm; <file_sep>import React from "react"; import PropTypes from "prop-types"; import { Text } from "react-native"; import FormField from "./fields/FormField"; import MultiChoice from "./fields/MultiChoice"; import Select from "./fields/Select"; import CheckboxForm from "./fields/CheckboxForm"; import RadioButton from "./fields/RadioButton"; import formStyles from "../../constants/styles/formStyles"; const PsychiatricAssessmentForm = ({ handleChange, handleBlur }) => { return ( <> <Text style={styles.subtitleText}>Wygląd</Text> <Text style={styles.listItemFieldText}> {"> "} ogólny wygląd badanego </Text> <FormField name="general_appearance" onChangeText={handleChange("general_appearance")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("general_appearance")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} strój</Text> <MultiChoice name="outfit_choice" options={[ "bez istotnych cech charaktery­stycznych (adekwatny, zadbany, czysty, schludny)", "nieadekwatny", "zaniedbany", "nadmiernie wyrazisty, kolorowy", ]} /> <Text style={styles.listItemFieldText}> {"> "} stopień zadbania o wygląd </Text> <FormField name="appearance_care" onChangeText={handleChange("appearance_care")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("appearance_care")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} wszystkie niezwykłe cechy lub gesty </Text> <FormField name="unusual_features_gestures" onChangeText={handleChange("unusual_features_gestures")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("unusual_features_gestures")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Relacja z badającym</Text> <Text style={styles.listItemFieldText}> {"> "} czy chętnie zgadza się na badanie? </Text> <Select name="agree_examination_choice" leftText="tak" rightText="nie" /> <FormField name="agree_examination" onChangeText={handleChange("agree_examination")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("agree_examination")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} czy jest ufny?</Text> <Select name="trusting_choice" leftText="tak" rightText="nie" /> <FormField name="trusting" onChangeText={handleChange("trusting")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("trusting")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} czy jest agresywny?</Text> <Select name="aggressive_choice" leftText="tak" rightText="nie" /> <FormField name="aggressive" onChangeText={handleChange("aggressive")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("aggressive")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} czy skraca dystans?</Text> <Select name="distance_shorten_choice" leftText="tak" rightText="nie" /> <FormField name="distance_shorten" onChangeText={handleChange("distance_shorten")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("distance_shorten")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} czy seksualizuje kontakt? </Text> <Select name="sexualizing_contact_choice" leftText="tak" rightText="nie" /> <FormField name="sexualizing_contact" onChangeText={handleChange("sexualizing_contact")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("sexualizing_contact")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} czy łatwo się irytuje? </Text> <Select name="irritated_easily_choice" leftText="tak" rightText="nie" /> <FormField name="irritated_easily" onChangeText={handleChange("irritated_easily")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("irritated_easily")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} czy wzbudza lęk?</Text> <Select name="fear_cause_choice" leftText="tak" rightText="nie" /> <FormField name="fear_cause" onChangeText={handleChange("fear_cause")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("fear_cause")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} czy wzbudza irytację?</Text> <Select name="irritate_choice" leftText="tak" rightText="nie" /> <FormField name="irritate" onChangeText={handleChange("irritate")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("irritate")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Orientacja</Text> <Text style={styles.listItemFieldText}> {"> "} zachowana orientacja autopsychiczna </Text> <Select name="autopsychic_orientation_choice" leftText="tak" rightText="nie" /> <FormField name="autopsychic_orientation" onChangeText={handleChange("autopsychic_orientation")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("autopsychic_orientation")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} zachowana orientacja allopsychiczna </Text> <Select name="allopsychic_orientation_choice" leftText="tak" rightText="nie" /> <FormField name="allopsychic_orientation" onChangeText={handleChange("allopsychic_orientation")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("allopsychic_orientation")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Sposób odpowiadania na pytania</Text> <MultiChoice name="answer_questions_choice" options={[ "bez uchwytnych trudności poznawczych", "trudności w rozumieniu pytań", "odpowiedzi zdawkowe", "odpowiedzi wyczerpujące", "pamięć prawidłowa", "trudność w przypominaniu faktów", ]} /> <FormField name="answer_questions" onChangeText={handleChange("answer_questions")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("answer_questions")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Mowa</Text> <Text style={styles.listItemFieldText}>{"> "} akcent</Text> <CheckboxForm name="accent_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="accent" onChangeText={handleChange("accent")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("accent")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} dialekt</Text> <CheckboxForm name="dialect_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="dialect" onChangeText={handleChange("dialect")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("dialect")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} szybkość mowy</Text> <CheckboxForm name="speech_speed_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="speech_speed" onChangeText={handleChange("speech_speed")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("speech_speed")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} ton mowy</Text> <CheckboxForm name="speech_tone_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="speech_tone" onChangeText={handleChange("speech_tone")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("speech_tone")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} upośledzenia mowy</Text> <CheckboxForm name="speech_impairment_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="speech_impairment" onChangeText={handleChange("speech_impairment")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("speech_impairment")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} cechy afazji</Text> <CheckboxForm name="aphasia_features_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="aphasia_features" onChangeText={handleChange("aphasia_features")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("aphasia_features")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}> Sposób poruszania się, przyjmowane pozy </Text> <MultiChoice name="moving_way_choice" options={["manieryzmy", "pobudzenie", "zahamowanie psychoruchowe"]} /> <FormField name="moving_way" onChangeText={handleChange("moving_way")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("moving_way")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Zaburzenia uwagi</Text> <RadioButton name="attention_disorders_choice" options={[ "nie stwierdza się", "zaburzenia koncentracji uwagi", "poważne zaburzenia koncentra­cji uwagi", ]} /> <FormField name="attention_disorders" onChangeText={handleChange("attention_disorders")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("attention_disorders")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Zaburzenia pamięci</Text> <MultiChoice name="memory_impairment_choice" options={[ "nie stwierdza się", "znaczne zaburzenia pamięci", "nasilone zaburzenia pamięci", "zaburzenia zapamiętywania", "zaburzenia pamięci świeżej", "zaburzenia pamięci dawnej", ]} /> <FormField name="memory_impairment" onChangeText={handleChange("memory_impairment")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("memory_impairment")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Nastrój</Text> <RadioButton name="mood_choice" options={[ "wyrównany", "nieznacznie obniżony", "obniżony", "znacznie obniżony", "nieznacznie podwyższony", "podwyższony", "znacznie podwyższony", "dysforyczny", ]} /> <FormField name="mood" onChangeText={handleChange("mood")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("mood")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Napęd psychoruchowy</Text> <RadioButton name="psychomotor_drive_choice" options={[ "wyrównany", "nieznacznie obniżony", "obniżony", "znacznie obniżony", "nieznacznie podwyższony", "podwyższony", "znacznie podwyższony", ]} /> <FormField name="psychomotor_drive" onChangeText={handleChange("psychomotor_drive")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("psychomotor_drive")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Afekt</Text> <MultiChoice name="affect_choice" options={[ "dostosowany", "niedostosowany", "żywy/prawidłowo modulowany", "blady", "stępiały", "płaski", "labilny", ]} /> <FormField name="affect" onChangeText={handleChange("affect")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("affect")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Lęk</Text> <Text style={styles.listItemFieldText}>{"> "} niepokój</Text> <MultiChoice name="anxiety_choice" options={[ "nie stwierdza się", "lęk wolno płynący", "lęk napadowy", "lęk fobijny", "somatyczne objawy lęku", "zaznaczony niepokój psycho­ruchowy", ]} /> <FormField name="anxiety" onChangeText={handleChange("anxiety")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("anxiety")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Zaburzenia treści myślenia</Text> <Text style={styles.listItemFieldText}>{"> "} urojenia</Text> <MultiChoice name="delusions_choice" options={[ "nie stwierdza się", "winy i grzeszności", "niższości", "zubożenia", "nihilistyczne", "hipochondryczne", "owładnięcia", "kontroli", "oddziaływania (wpływu)", "nasyłanie myśli", "odciąganie (zabieranie) myśli", "rozgłaśnianie (odsłonięcie) myśli", "wielkościowe", "odnoszące (ksobne)", "prześladowcze", "niewierności małżeńskiej", "urojeniowa zazdrość", "erotyczne, zakochania", "religijne i posłannicze", "natręctwa (obsesje)", "idee nadwartościowe", ]} /> <FormField name="delusions" onChangeText={handleChange("delusions")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("delusions")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Zaburzenia spostrzegania</Text> <Text style={styles.listItemFieldText}> {"> "} halucynacje, pseudohalucyjnacje </Text> <MultiChoice name="hallucinations_choice" options={[ "nie stwierdza się", "słuchowe", "głosy komentujące", "głosy prowadzące dialog", "ugłośnienie myśli", "echo myśli", "wzrokowe", "fotopsje", "węchowe", "dotykowe", "smakowe", "czucia ustrojowego", "parahalucynacje (halucynoidy)", "hipnagogiczne", "hipnapompiczne", "depersonalizacje", "derealizacje", ]} /> <FormField name="hallucinations" onChangeText={handleChange("hallucinations")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("hallucinations")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} iluzje</Text> <MultiChoice name="illusions_choice" options={[ "nie stwierdza się", "słuchowe", "wzrokowe", "węchowe", "dotykowe", "smakowe", "czucia ustrojowego", ]} /> <FormField name="illusions" onChangeText={handleChange("illusions")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("illusions")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} inne</Text> <MultiChoice name="perception_disorders_choice" options={["nie stwierdza się", "pareidolie", "makropsje", "mikropsje"]} /> <FormField name="perception_disorders" onChangeText={handleChange("perception_disorders")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("perception_disorders")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Zaburzenia toku myślenia</Text> <MultiChoice name="abnormal_thinking_choice" options={[ "nie stwierdza się", "przyspieszenie", "spowolnienie", "otamowanie", "niedokojarzenie", "rozkojarzenie", "splątanie", "perseweracje", "werbigeracje", "ambiwalencja", "zorientowany na cela badania", "dygresyjny", "nadmiernie szczegółowy", "zahamowania", "echolalie", "gonitwa myśli", "dezorganizacja myślenia", ]} /> <FormField name="abnormal_thinking" onChangeText={handleChange("abnormal_thinking")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("abnormal_thinking")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Zaburzenia krytycyzmu i wyglądu</Text> <MultiChoice name="criticism_disturbance_choice" options={[ "zachowany wgląd i krytycyzm", "częściowo zachowany wgląd i krytycyzm", "brak wglądu i bezkrytycyzm", "ego-dystoniczny charakter objawów", "ego-syntoniczny charakter objawów", ]} /> <FormField name="criticism_disturbance" onChangeText={handleChange("criticism_disturbance")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("criticism_disturbance")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Aktywność złożona</Text> <MultiChoice name="complex_activity_choice" options={[ "natrętne czynności (kompulsje)", "automatyzmy", "stereotypie", "manieryzmy", ]} /> <FormField name="complex_activity" onChangeText={handleChange("complex_activity")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("complex_activity")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Parakinezy katatoniczne</Text> <MultiChoice name="catatonic_parakinesis_choice" options={[ "zastyganie", "stupor", "gibkość woskowa", "negatywizm czynny", "negatywizm bierny", "sztywność", ]} /> <FormField name="catatonic_parakinesis" onChangeText={handleChange("catatonic_parakinesis")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("catatonic_parakinesis")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}> Ocena pozostałych funkcji poznawczych </Text> <Text style={styles.listItemFieldText}>{"> "} zapamiętywanie</Text> <Text style={styles.commentFieldText}> (w wypadku podejrzenia otępienia) </Text> <CheckboxForm name="memorizing_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="memorizing" onChangeText={handleChange("memorizing")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("memorizing")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} uwaga i liczenie</Text> <Text style={styles.commentFieldText}> (w wypadku podejrzenia otępienia) </Text> <CheckboxForm name="attention_counting_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="attention_counting" onChangeText={handleChange("attention_counting")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("attention_counting")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} przypominanie</Text> <Text style={styles.commentFieldText}> (w wypadku podejrzenia otępienia) </Text> <CheckboxForm name="reminding_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="reminding" onChangeText={handleChange("reminding")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("reminding")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} zdolności językowe</Text> <Text style={styles.commentFieldText}> (w wypadku podejrzenia otępienia) </Text> <CheckboxForm name="language_skills_difficulties" text="bez uchwytnych trudności" style={styles.choice} /> <FormField name="language_skills" onChangeText={handleChange("language_skills")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("language_skills")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}> Myśli i plany suicydalne lub homicydalne </Text> <Text style={styles.listItemFieldText}>{"> "} myśli rezygnacyjne</Text> <Select name="resignation_thoughts_choice" leftText="obecne" rightText="nieobecne" /> <FormField name="resignation_thoughts" onChangeText={handleChange("resignation_thoughts")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("resignation_thoughts")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} myśli samobójcze</Text> <Select name="suicide_thoughts_choice" leftText="obecne" rightText="nieobecne" /> <FormField name="suicide_thoughts" onChangeText={handleChange("suicide_thoughts")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("suicide_thoughts")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} plany i tendencje samobójcze </Text> <Select name="suicidal_plans_choice" leftText="obecne" rightText="nieobecne" /> <FormField name="suicidal_plans" onChangeText={handleChange("suicidal_plans")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("suicidal_plans")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} fantazje o zabójstwie</Text> <Select name="murder_fantasies_choice" leftText="obecne" rightText="nieobecne" /> <FormField name="murder_fantasies" onChangeText={handleChange("murder_fantasies")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("murder_fantasies")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} plany zabójstwa</Text> <Select name="murder_plans_choice" leftText="obecne" rightText="nieobecne" /> <FormField name="murder_plans" onChangeText={handleChange("murder_plans")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("murder_plans")} keyboardType="default" multiline numberOfLines={2} /> </> ); }; const styles = formStyles; PsychiatricAssessmentForm.propTypes = { handleChange: PropTypes.func.isRequired, handleBlur: PropTypes.func.isRequired, }; export default PsychiatricAssessmentForm; <file_sep>import React, { useState } from "react"; import { View, Text, StyleSheet, TouchableOpacity, ViewPropTypes, } from "react-native"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import FormError from "./FormError"; import { Colors, Typography } from "../../../constants/styles"; import FontForgeIcon from "../../common/FontForgeIcon"; const CheckboxForm = ({ name, text, style }) => { const { setFieldValue, errors, touched } = useFormikContext(); const [isChecked, setChecked] = useState(false); const leftIcon = isChecked ? "checked" : "unchecked"; return ( <> <View style={styles.container}> <TouchableOpacity style={style} onPress={() => { setFieldValue(name, !isChecked); setChecked(!isChecked); }} > <FontForgeIcon name={leftIcon} size={38} color={Colors.PINK_MEDIUM} style={styles.icon} /> </TouchableOpacity> <Text style={styles.text}>{text}</Text> </View> <FormError error={errors[name]} visible={touched[name]} /> </> ); }; const styles = StyleSheet.create({ container: { backgroundColor: Colors.GRAY_VERY_LIGHT, flexDirection: "row", padding: 7, alignSelf: "center", right: 30, marginTop: 5, }, icon: { alignSelf: "flex-start", }, text: { width: "55%", fontSize: Typography.FONT_SIZE_13, fontFamily: Typography.FONT_FAMILY_REGULAR, color: Colors.BLACK, borderBottomWidth: 0, alignSelf: "center", }, }); CheckboxForm.defaultProps = { style: { marginRight: 15 }, }; CheckboxForm.propTypes = { name: PropTypes.string.isRequired, text: PropTypes.string.isRequired, style: ViewPropTypes.style, }; export default CheckboxForm; <file_sep>import React from "react"; import { View, Text, StyleSheet } from "react-native"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import FormError from "./FormError"; import { Colors, Typography } from "../../../constants/styles"; import * as Constants from "../../../constants/values/constants"; import FontForgeIcon from "../../common/FontForgeIcon"; const regularIconColor = Colors.PINK_MEDIUM; const placeholderTextColor = Colors.PURPLE_LIGHT; const regularTextColor = Colors.BLACK; const BmiForm = ({ name, leftIcon, value }) => { const { setFieldValue, errors, touched, values } = useFormikContext(); const getIconColorStyle = () => { if (values.bmi > 0 && values.bmi < Constants.BMI_UNDERWEIGHT_VALUE) return Colors.BMI_UNDERWEIGHT; if (values.bmi >= Constants.BMI_OVERWEIGHT_VALUE) { return Colors.BMI_OVERWEIGHT; } return regularIconColor; }; const getTextStyle = () => { if (values.bmi === "0") return { color: placeholderTextColor, }; if (values.bmi > 0 && values.bmi < Constants.BMI_UNDERWEIGHT_VALUE) return { color: Colors.BMI_UNDERWEIGHT, fontWeight: Typography.FONT_WEIGHT_BOLD, }; if (values.bmi >= Constants.BMI_OVERWEIGHT_VALUE) { return { color: Colors.BMI_OVERWEIGHT, fontWeight: Typography.FONT_WEIGHT_BOLD, }; } return { color: regularTextColor, }; }; return ( <> <View style={styles.container}> {leftIcon && ( <FontForgeIcon name={leftIcon} size={38} color={getIconColorStyle()} style={styles.icon} /> )} <Text style={[styles.input, getTextStyle()]} onChangeText={(text) => setFieldValue(name, text)} > {value} </Text> </View> <FormError error={errors[name]} visible={touched[name]} /> </> ); }; const styles = StyleSheet.create({ container: { backgroundColor: Colors.GRAY_VERY_LIGHT, flexDirection: "row", padding: 7, alignSelf: "center", right: 30, }, icon: { marginRight: 15, }, input: { width: "55%", fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_LIGHT, padding: 12, left: -12, }, }); BmiForm.defaultProps = { leftIcon: null, }; BmiForm.propTypes = { name: PropTypes.string.isRequired, leftIcon: PropTypes.string, value: PropTypes.string.isRequired, }; export default BmiForm; <file_sep>import { StyleSheet } from "react-native"; import { Colors, Typography } from "./index"; export default StyleSheet.create({ cardItem: { backgroundColor: Colors.GRAY_VERY_LIGHT, padding: 6, marginVertical: 6, marginHorizontal: 10, borderRadius: Typography.BORDER_RADIUS, ...Typography.BOX_SHADOW, }, }); <file_sep>import { Alert } from "react-native"; const backAction = ({ navigation, navigationRouteName, message }) => ({ beforeRemove: (e) => { const { action } = e.data; if ( !action.payload || !action.payload.name || action.payload.name !== navigationRouteName ) { e.preventDefault(); Alert.alert("", message, [ { text: "Kontynuuj", style: "cancel", onPress: () => {}, }, { text: "Przerwij", style: "destructive", onPress: () => { navigation.navigate(navigationRouteName); }, }, ]); } else navigation.dispatch(e.data.action); }, }); // eslint-disable-next-line import/prefer-default-export export { backAction }; <file_sep>import React, { cloneElement } from "react"; import PropTypes from "prop-types"; import { FlatList, ViewPropTypes } from "react-native"; import { Formik, FieldArray } from "formik"; import DiagnosisQuestionItem from "./QuestionItem"; import diagnosisValidationSchema from "../../constants/validationSchemas/diagnosisValidationSchema"; const DiagnosisForm = ({ questions, answers, footerComponent, footerComponentStyle, }) => { return ( <Formik enableReinitialize initialValues={{ answers }} validationSchema={diagnosisValidationSchema} validateOnChange validateOnBlur={false} onSubmit={() => {}} > {({ values, handleSubmit, isValid }) => ( <FieldArray name="answers"> {() => { return ( <FlatList data={questions} keyExtractor={(question) => question.content} renderItem={({ item, index }) => ( <DiagnosisQuestionItem question={item} index={index} defaultAnswer={answers[index]} /> )} ListFooterComponentStyle={footerComponentStyle} ListFooterComponent={() => { const { onPress } = footerComponent.props; return cloneElement(footerComponent, { ...footerComponent.props, onPress: () => { handleSubmit(); if (isValid) { onPress(values.answers); } }, }); }} /> ); }} </FieldArray> )} </Formik> ); }; DiagnosisForm.defaultProps = { footerComponentStyle: {}, }; DiagnosisForm.propTypes = { questions: PropTypes.arrayOf( PropTypes.shape({ content: PropTypes.string.isRequired, }) ).isRequired, answers: PropTypes.oneOfType([ PropTypes.arrayOf(undefined), PropTypes.arrayOf(PropTypes.number), ]).isRequired, footerComponent: PropTypes.element.isRequired, footerComponentStyle: ViewPropTypes.style, }; export default DiagnosisForm; <file_sep>export const BMI_UNDERWEIGHT_VALUE = 18.5; export const BMI_OVERWEIGHT_VALUE = 25; export const PATIENT_CODE_REGEX = /^$|([a-tA-T]|[v-zV-Z])\d[a-zA-Z0-9](\.[a-zA-Z0-9]{1,4})?$/; export const PESEL_REGEX = /^[0-9]{11}$/; export const DATE_REGEX = /^(0[1-9]|[12][0-9]|3[01])([- /.]|( - ))(0[1-9]|1[012])([- /.]|( - ))(19|20)\d\d$/; export const PHONE_REGEX = /^[0-9+]{8,13}$/; <file_sep>import * as React from "react"; import { ViewPropTypes } from "react-native"; import { Colors } from "../../constants/styles"; import FontForgeIcon from "./FontForgeIcon"; const ProfileIcon = ({ style }) => { return ( <FontForgeIcon name="doctor_profile" size={30} color={Colors.PURPLE_VERY_LIGHT} style={style} /> ); }; export default ProfileIcon; ProfileIcon.defaultProps = { style: {}, }; ProfileIcon.propTypes = { style: ViewPropTypes.style, }; <file_sep>import React from "react"; import { StyleSheet, TouchableOpacity, ViewPropTypes } from "react-native"; import PropTypes from "prop-types"; import FontForgeIcon from "./FontForgeIcon"; import { Colors } from "../../constants/styles"; const getOpacity = (disabled) => { return { opacity: disabled ? 0.2 : 1, }; }; const AppButton = ({ onPress, icon, disabled, iconStyle }) => { return ( <TouchableOpacity style={styles.button} onPress={onPress} disabled={disabled} > <FontForgeIcon name={icon} size={80} color={Colors.PURPLE} style={[styles.icon, getOpacity(disabled), iconStyle]} /> </TouchableOpacity> ); }; const styles = StyleSheet.create({ button: { justifyContent: "center", alignSelf: "flex-end", alignItems: "center", width: "25%", }, icon: { alignSelf: "flex-end", marginTop: 17, marginRight: 17, }, }); AppButton.defaultProps = { disabled: false, iconStyle: {}, }; AppButton.propTypes = { icon: PropTypes.string.isRequired, onPress: PropTypes.func.isRequired, disabled: PropTypes.bool, iconStyle: ViewPropTypes.style, }; export default AppButton; <file_sep>import React, { useEffect } from "react"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import FormField from "./FormField"; const Pesel = ({ name, leftIcon, keyboardType, placeholder, calculateDependentValue, }) => { const { setFieldValue, values } = useFormikContext(); if (calculateDependentValue != null) useEffect(() => { setFieldValue("date_of_birth", calculateDependentValue(values.pesel)); }, [values.pesel]); return ( <> <FormField name={name} leftIcon={leftIcon} keyboardType={keyboardType} placeholder={placeholder} /> </> ); }; Pesel.defaultProps = { leftIcon: null, calculateDependentValue: null, }; Pesel.propTypes = { name: PropTypes.string.isRequired, leftIcon: PropTypes.string, keyboardType: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, calculateDependentValue: PropTypes.func, }; export default Pesel; <file_sep>import * as React from "react"; import { StyleSheet, ViewPropTypes } from "react-native"; import { Colors, Typography } from "../../constants/styles"; import FontForgeIcon from "./FontForgeIcon"; const BackIcon = ({ style }) => { return ( <FontForgeIcon name="back" size={32} color={Colors.PURPLE_VERY_LIGHT} style={[styles.icon, style]} /> ); }; export default BackIcon; const styles = StyleSheet.create({ icon: { fontWeight: Typography.FONT_WEIGHT_BOLD, transform: [{ rotate: "352deg" }], }, }); BackIcon.defaultProps = { style: {}, }; BackIcon.propTypes = { style: ViewPropTypes.style, }; <file_sep>import React, { useContext, useState } from "react"; import { StyleSheet } from "react-native"; import PropTypes from "prop-types"; import { Formik } from "formik"; import { PhysicalExaminationContext } from "../../modules/context/PhysicalExaminationContext"; import AppButton from "../../components/common/AppButton"; import physicalExaminationValidationSchema from "../../constants/validationSchemas/physicalExaminationValidationSchema"; import PhysicalExaminationForm from "../../components/forms/PhysicalExaminationForm"; import FormContainer from "../../components/forms/FormContainer"; const PhysicalExamination = ({ route, navigation }) => { const { physicalExaminationId, psychiatricAssessmentId } = route.params; const { patientsPhysicalExamination, updatePhysicalExamination } = useContext( PhysicalExaminationContext ); const [isNextButtonDisabled, setNextButtonDisabled] = useState(false); const initialState = patientsPhysicalExamination.find( (physicalExamination) => physicalExamination.id === physicalExaminationId ); const onButtonPressed = async (values) => { setNextButtonDisabled(true); const physicalExamination = values; const result = await updatePhysicalExamination(physicalExamination); if (result) { navigation.navigate("PsychiatricAssessment", { psychiatricAssessmentId, }); } // TODO: Show alert with info what is wrong }; return ( <FormContainer style={styles.container}> <Formik initialValues={initialState} enableReinitialize validationSchema={physicalExaminationValidationSchema} onSubmit={(values) => onButtonPressed(values)} > {({ handleChange, handleSubmit, isValid, handleBlur, isSubmitting, }) => ( <> <PhysicalExaminationForm handleBlur={handleBlur} handleChange={handleChange} /> <AppButton icon="next_btn" onPress={handleSubmit} disabled={!isValid || isSubmitting || isNextButtonDisabled} /> </> )} </Formik> </FormContainer> ); }; const styles = StyleSheet.create({ container: { paddingTop: 15, }, }); PhysicalExamination.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, }).isRequired, route: PropTypes.shape({ params: PropTypes.shape({ physicalExaminationId: PropTypes.number.isRequired, psychiatricAssessmentId: PropTypes.number.isRequired, }), }).isRequired, }; export default PhysicalExamination; <file_sep>import React, { createContext, useEffect, useReducer } from "react"; import PropTypes from "prop-types"; import physicalExaminationReducer, { PHYSICAL_EXAMINATION_ACTIONS, } from "./PhysicalExaminationReducer"; import patientsPhysicalExamination from "../../constants/data/patientsPhysicalExamination"; import { database, TABLES } from "../database/database"; export const PhysicalExaminationContext = createContext({ patientsPhysicalExamination: [], }); const initialState = { patientsPhysicalExamination }; function PhysicalExaminationProvider({ children }) { const [state, dispatch] = useReducer( physicalExaminationReducer, initialState ); useEffect(() => { const refreshPhysicalExamination = async () => { const physicalExaminations = await database.getAllFromTable( TABLES.physical_examination ); dispatch({ type: PHYSICAL_EXAMINATION_ACTIONS.REFRESH, payload: { physicalExaminations }, }); }; refreshPhysicalExamination(); }, []); const setPhysicalExamination = async (physicalExamination) => { const id = await database.insertObjectToTable( physicalExamination, TABLES.physical_examination ); if (id) { const examinationWithId = physicalExamination; examinationWithId.id = id; dispatch({ type: PHYSICAL_EXAMINATION_ACTIONS.INSERT_OR_UPDATE, payload: { physicalExamination: examinationWithId }, }); } return id; }; const updatePhysicalExamination = async (physicalExamination) => { const result = await database.updateObjectFromTable( physicalExamination, TABLES.physical_examination ); if (result) { dispatch({ type: PHYSICAL_EXAMINATION_ACTIONS.INSERT_OR_UPDATE, payload: { physicalExamination }, }); } return result; }; const value = { ...state, setPhysicalExamination, updatePhysicalExamination, }; return ( <PhysicalExaminationContext.Provider value={value}> {children} </PhysicalExaminationContext.Provider> ); } PhysicalExaminationProvider.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, }; export default PhysicalExaminationProvider; <file_sep>import React from "react"; import { AppLoading } from "expo"; import { useFonts } from "expo-font"; import MainNavigator from "./src/modules/navigation/MainNavigator"; import PatientsContextProvider from "./src/modules/context/PatientsContext"; import BasicDataContextProvider from "./src/modules/context/BasicDataContext"; import PhysicalExaminationProvider from "./src/modules/context/PhysicalExaminationContext"; import PsychiatricAssessmentProvider from "./src/modules/context/PsychiatricAssessmentContext"; import OpenSansLight from "./src/assets/fonts/OpenSans-Light.ttf"; import OpenSansRegular from "./src/assets/fonts/OpenSans-Regular.ttf"; import OpenSansBold from "./src/assets/fonts/OpenSans-Bold.ttf"; import IconFont from "./src/assets/fonts/IconFont.ttf"; import useDatabase from "./src/modules/hooks/useDatabase"; export default function App() { console.log(`Initialize app in ${process.env.NODE_ENV}`); const [fontsLoaded] = useFonts({ "OpenSans-Light": OpenSansLight, "OpenSans-Regular": OpenSansRegular, "OpenSans-Bold": OpenSansBold, IconFont, }); const isDBLoadingCompleted = useDatabase(); if (!fontsLoaded || !isDBLoadingCompleted) { return <AppLoading />; } return ( <PatientsContextProvider> <BasicDataContextProvider> <PhysicalExaminationProvider> <PsychiatricAssessmentProvider> <MainNavigator /> </PsychiatricAssessmentProvider> </PhysicalExaminationProvider> </BasicDataContextProvider> </PatientsContextProvider> ); } <file_sep>import React from "react"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import Select from "./Select"; const PastPsychiatricTreatment = ({ name, leftText, rightText, defaultOption, }) => { const { setFieldValue } = useFormikContext(); const calculateDependentValueWhenFalse = () => { setFieldValue("hospitalization_times", "0"); }; return ( <Select name={name} leftText={leftText} rightText={rightText} defaultOption={defaultOption} calculateDependentValueWhenFalse={calculateDependentValueWhenFalse} /> ); }; PastPsychiatricTreatment.defaultProps = { defaultOption: null, }; PastPsychiatricTreatment.propTypes = { name: PropTypes.string.isRequired, leftText: PropTypes.string.isRequired, rightText: PropTypes.string.isRequired, defaultOption: PropTypes.bool, }; export default PastPsychiatricTreatment; <file_sep>import React, { useState } from "react"; import { View, Text, StyleSheet, TouchableOpacity } from "react-native"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import FormError from "./FormError"; import { Colors, Typography } from "../../../constants/styles"; import FontForgeIcon from "../../common/FontForgeIcon"; const Select = ({ name, leftText, rightText, defaultOption, calculateDependentValueWhenFalse, }) => { const { setFieldValue, errors, touched } = useFormikContext(); const [isChecked, setChecked] = useState(defaultOption); const pressLeft = () => { setChecked(true); setFieldValue(name, true); }; const pressRight = () => { setChecked(false); setFieldValue(name, false); if (calculateDependentValueWhenFalse != null) calculateDependentValueWhenFalse(); }; return ( <> <View style={styles.container}> <TouchableOpacity onPress={pressLeft}> <FontForgeIcon name={ isChecked === false || isChecked == null ? "unchecked" : "checked" } size={38} color={Colors.PINK_MEDIUM} style={styles.icon} /> </TouchableOpacity> <Text style={styles.text}>{leftText}</Text> <TouchableOpacity onPress={pressRight}> <FontForgeIcon name={ isChecked === true || isChecked == null ? "unchecked" : "checked" } size={38} color={Colors.PINK_MEDIUM} style={styles.icon} /> </TouchableOpacity> <Text style={styles.text}>{rightText}</Text> </View> <FormError error={errors[name]} visible={touched[name]} /> </> ); }; const styles = StyleSheet.create({ container: { backgroundColor: Colors.GRAY_VERY_LIGHT, flex: 1, flexDirection: "row", alignItems: "center", justifyContent: "space-between", marginTop: 10, marginLeft: 60, marginRight: 30, }, icon: { flex: 1, alignSelf: "flex-end", marginRight: 5, }, text: { flex: 1, fontSize: Typography.FONT_SIZE_13, fontFamily: Typography.FONT_FAMILY_REGULAR, color: Colors.BLACK, alignSelf: "center", }, }); Select.defaultProps = { defaultOption: null, calculateDependentValueWhenFalse: null, }; Select.propTypes = { name: PropTypes.string.isRequired, leftText: PropTypes.string.isRequired, rightText: PropTypes.string.isRequired, defaultOption: PropTypes.bool, calculateDependentValueWhenFalse: PropTypes.func, }; export default Select; <file_sep>import pandas as pd import json path_to_csv = r"../data/diagnosis_data.csv" df = pd.read_csv(path_to_csv) data = [] modules_codes = df.module_code.unique() for column in df.columns: df[column] = df[column].fillna('null') for module_code in modules_codes: module_data = [{ 'disease_icd10': row.disease_icd10, 'disease_name': row.disease_name, 'diagnosis_conditions': { 'main_cond_1': row.main_cond_1, 'main_cond_2': row.main_cond_2, 'side_cond_1': row.side_cond_1, 'side_cond_2': row.side_cond_2, 'side_cond_3': row.side_cond_3, 'side_cond_4': row.side_cond_4, 'side_cond_5': row.side_cond_5, 'side_cond_6': row.side_cond_6, 'detail_cond': row.detail_cond } } for (index, row) in df.iterrows()] data.append({ 'module_code': module_code, 'module_data': module_data }) with open('data.json', 'w') as o: json.dump(data, o) <file_sep>const patientsPhysicalExamination = [ { id: 1, patient_id: 123456789, general_conditions: "", blood_pressure: "", pulse: "", body_temperature: "", body_build_type: "", skin_appearance: "", skin_colour: "", skin_humidity: "", skin_swelling: "", skin_scars: "", lymphatic_gland_examined: false, head_appearance_choice: "", head_appearance: "", head_percussion_tenderness: "", head_eyeballs: "", ears: "", nose: "", mouth_teeth: "", mucous_membrane_choice: "", mucous_membrane: "", neck_throat_tonsil: "", neck_appearance: "", neck_thyroid_choice: "", neck_thyroid: "", chest_choice: "", chest: "", breath_frequency: "", chest_percussion_choice: "", chest_percussion: "", chest_auscultation_choice: "", chest_auscultation: "", cardiovascular_appearance: "", cardiovascular_efficient: "", cardiovascular_auscultation: "", cardiovascular_pulse_choice: "", cardiovascular_pulse: "", stomach: "", stomach_hernia: "", stomach_painless: "", stomach_auscultation: "", stomach_percussion: "", stomach_physical_examination: "", stomach_symptoms: "", legs_swelling: "", legs_veins: "", locomotor_joint_outline: false, locomotor_limb_mobility: false, muscle_strength_tension: false, nervous_meningeal_signs: "", nervous_focal_damage: "", }, { id: 2, patient_id: 2, general_conditions: "", blood_pressure: "", pulse: "", body_temperature: "", body_build_type: "", skin_appearance: "", skin_colour: "", skin_humidity: "", skin_swelling: "", skin_scars: "", lymphatic_gland_examined: false, head_appearance_choice: "", head_appearance: "", head_percussion_tenderness: "", head_eyeballs: "", ears: "", nose: "", mouth_teeth: "", mucous_membrane_choice: "", mucous_membrane: "", neck_throat_tonsil: "", neck_appearance: "", neck_thyroid_choice: "", neck_thyroid: "", chest_choice: "", chest: "", breath_frequency: "", chest_percussion_choice: "", chest_percussion: "", chest_auscultation_choice: "", chest_auscultation: "", cardiovascular_appearance: "", cardiovascular_efficient: "", cardiovascular_auscultation: "", cardiovascular_pulse_choice: "", cardiovascular_pulse: "", stomach: "", stomach_hernia: "", stomach_painless: "", stomach_auscultation: "", stomach_percussion: "", stomach_physical_examination: "", stomach_symptoms: "", legs_swelling: "", legs_veins: "", locomotor_joint_outline: false, locomotor_limb_mobility: false, muscle_strength_tension: false, nervous_meningeal_signs: "", nervous_focal_damage: "", }, { id: 3, patient_id: 3, general_conditions: "", blood_pressure: "", pulse: "", body_temperature: "", body_build_type: "", skin_appearance: "", skin_colour: "", skin_humidity: "", skin_swelling: "", skin_scars: "", lymphatic_gland_examined: false, head_appearance_choice: "", head_appearance: "", head_percussion_tenderness: "", head_eyeballs: "", ears: "", nose: "", mouth_teeth: "", mucous_membrane_choice: "", mucous_membrane: "", neck_throat_tonsil: "", neck_appearance: "", neck_thyroid_choice: "", neck_thyroid: "", chest_choice: "", chest: "", breath_frequency: "", chest_percussion_choice: "", chest_percussion: "", chest_auscultation_choice: "", chest_auscultation: "", cardiovascular_appearance: "", cardiovascular_efficient: "", cardiovascular_auscultation: "", cardiovascular_pulse_choice: "", cardiovascular_pulse: "", stomach: "", stomach_hernia: "", stomach_painless: "", stomach_auscultation: "", stomach_percussion: "", stomach_physical_examination: "", stomach_symptoms: "", legs_swelling: "", legs_veins: "", locomotor_joint_outline: false, locomotor_limb_mobility: false, muscle_strength_tension: false, nervous_meningeal_signs: "", nervous_focal_damage: "", }, { id: 4, patient_id: 4, general_conditions: "", blood_pressure: "", pulse: "", body_temperature: "", body_build_type: "", skin_appearance: "", skin_colour: "", skin_humidity: "", skin_swelling: "", skin_scars: "", lymphatic_gland_examined: false, head_appearance_choice: "", head_appearance: "", head_percussion_tenderness: "", head_eyeballs: "", ears: "", nose: "", mouth_teeth: "", mucous_membrane_choice: "", mucous_membrane: "", neck_throat_tonsil: "", neck_appearance: "", neck_thyroid_choice: "", neck_thyroid: "", chest_choice: "", chest: "", breath_frequency: "", chest_percussion_choice: "", chest_percussion: "", chest_auscultation_choice: "", chest_auscultation: "", cardiovascular_appearance: "", cardiovascular_efficient: "", cardiovascular_auscultation: "", cardiovascular_pulse_choice: "", cardiovascular_pulse: "", stomach: "", stomach_hernia: "", stomach_painless: "", stomach_auscultation: "", stomach_percussion: "", stomach_physical_examination: "", stomach_symptoms: "", legs_swelling: "", legs_veins: "", locomotor_joint_outline: false, locomotor_limb_mobility: false, muscle_strength_tension: false, nervous_meningeal_signs: "", nervous_focal_damage: "", }, { id: 5, patient_id: 5, general_conditions: "", blood_pressure: "", pulse: "", body_temperature: "", body_build_type: "", skin_appearance: "", skin_colour: "", skin_humidity: "", skin_swelling: "", skin_scars: "", lymphatic_gland_examined: false, head_appearance_choice: "", head_appearance: "", head_percussion_tenderness: "", head_eyeballs: "", ears: "", nose: "", mouth_teeth: "", mucous_membrane_choice: "", mucous_membrane: "", neck_throat_tonsil: "", neck_appearance: "", neck_thyroid_choice: "", neck_thyroid: "", chest_choice: "", chest: "", breath_frequency: "", chest_percussion_choice: "", chest_percussion: "", chest_auscultation_choice: "", chest_auscultation: "", cardiovascular_appearance: "", cardiovascular_efficient: "", cardiovascular_auscultation: "", cardiovascular_pulse_choice: "", cardiovascular_pulse: "", stomach: "", stomach_hernia: "", stomach_painless: "", stomach_auscultation: "", stomach_percussion: "", stomach_physical_examination: "", stomach_symptoms: "", legs_swelling: "", legs_veins: "", locomotor_joint_outline: false, locomotor_limb_mobility: false, muscle_strength_tension: false, nervous_meningeal_signs: "", nervous_focal_damage: "", }, { id: 6, patient_id: 123456789, general_conditions: "", blood_pressure: "", pulse: "", body_temperature: "", body_build_type: "", skin_appearance: "", skin_colour: "", skin_humidity: "", skin_swelling: "", skin_scars: "", lymphatic_gland_examined: false, head_appearance_choice: "", head_appearance: "", head_percussion_tenderness: "", head_eyeballs: "", ears: "", nose: "", mouth_teeth: "", mucous_membrane_choice: "", mucous_membrane: "", neck_throat_tonsil: "", neck_appearance: "", neck_thyroid_choice: "", neck_thyroid: "", chest_choice: "", chest: "", breath_frequency: "", chest_percussion_choice: "", chest_percussion: "", chest_auscultation_choice: "", chest_auscultation: "", cardiovascular_appearance: "", cardiovascular_efficient: "", cardiovascular_auscultation: "", cardiovascular_pulse_choice: "", cardiovascular_pulse: "", stomach: "", stomach_hernia: "", stomach_painless: "", stomach_auscultation: "", stomach_percussion: "", stomach_physical_examination: "", stomach_symptoms: "", legs_swelling: "", legs_veins: "", locomotor_joint_outline: false, locomotor_limb_mobility: false, muscle_strength_tension: false, nervous_meningeal_signs: "", nervous_focal_damage: "", }, ]; export default patientsPhysicalExamination; <file_sep>import React from "react"; import { StyleSheet, Text, View, ViewPropTypes } from "react-native"; import PropTypes from "prop-types"; import FontForgeIcon from "../../common/FontForgeIcon"; import { Colors } from "../../../constants/styles"; import { FONT_REGULAR, FONT_SIZE_14, } from "../../../constants/styles/typography"; const InterviewInfo = ({ style, icon, name, value }) => { return ( <View style={[styles.container, style]}> <FontForgeIcon name={icon} size={32} color={Colors.PINK} /> <Text style={styles.name}>{name}:</Text> <Text style={styles.value}>{value}</Text> </View> ); }; const styles = StyleSheet.create({ container: { flexDirection: "row", alignItems: "center", }, name: { ...FONT_REGULAR, fontSize: FONT_SIZE_14, color: Colors.PURPLE, marginLeft: 4, }, value: { ...FONT_REGULAR, color: Colors.PURPLE, fontSize: FONT_SIZE_14, marginLeft: 4, marginRight: 4, flexShrink: 1, }, }); InterviewInfo.defaultProps = { style: {}, }; InterviewInfo.propTypes = { icon: PropTypes.string.isRequired, name: PropTypes.string.isRequired, value: PropTypes.string.isRequired, style: ViewPropTypes.style, }; export default InterviewInfo; <file_sep>import PropTypes from "prop-types"; import { CodeProp } from "./patientPropTypes"; export const diseasesProbabilityPropTypes = PropTypes.arrayOf( PropTypes.shape({ disease_icd10: CodeProp.isRequired, disease_name: PropTypes.string.isRequired, probability: PropTypes.number.isRequired, conditionsAcc: PropTypes.shape({ main: PropTypes.shape({ allAnswers: PropTypes.number, validAnswers: PropTypes.number, }).isRequired, side: PropTypes.shape({ allAnswers: PropTypes.number, validAnswers: PropTypes.number, }).isRequired, detail: PropTypes.shape({ allAnswers: PropTypes.number, validAnswers: PropTypes.number, }).isRequired, }), }) ); export const modulePropTypes = PropTypes.shape({ name: PropTypes.string.isRequired, code: PropTypes.string.isRequired, }); <file_sep>import React from "react"; import { Text } from "react-native"; import PropTypes from "prop-types"; import FormField from "./fields/FormField"; import Select from "./fields/Select"; import MultiChoice from "./fields/MultiChoice"; import PastPsychiatricTreatment from "./fields/PastPsychiatricTreatment"; import FillForm from "./fields/FillForm"; import RadioButton from "./fields/RadioButton"; import formStyles from "../../constants/styles/formStyles"; const BasicDataForm = ({ handleChange, handleBlur, values }) => { return ( <> <Text style={styles.subtitleText}>Powód i kontekst zgłoszenia</Text> <FormField name="reason_of_report" onChangeText={handleChange("reason_of_report")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("reason_of_report")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Główne dolegliwości</Text> <FormField name="major_ailments" onChangeText={handleChange("major_ailments")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("major_ailments")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}> Obecność myśli i tendencji suicydalnych lub homicydalnych </Text> <Select name="suicidal_thoughts_choice" leftText="Obecne" rightText="Nieobecne" /> <FormField name="suicidal_thoughts" onChangeText={handleChange("suicidal_thoughts")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("suicidal_thoughts")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Inne dolegliwości</Text> <FormField name="other_ailments" onChangeText={handleChange("other_ailments")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("other_ailments")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Przebyte choroby i operacje</Text> <MultiChoice name="past_diseases_choice" options={[ "Poważne urazy głowy", "Zapalenia w obrębie CSN", "Epizody drgawkowe", ]} /> <FormField name="past_diseases" onChangeText={handleChange("past_diseases")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("past_diseases")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Przebieg dotychczasowego leczenia</Text> <Text style={styles.listItemFieldText}> W przeszłości pacjent {" "}_____{" "} psychiatrycznie </Text> <PastPsychiatricTreatment name="past_psychiatric_treatment" leftText="leczył się" rightText="nie leczył się" /> <FillForm name="first_hospitalization" onChangeText={handleChange("first_hospitalization")} placeholder="rok" labelText="Pierwszy raz przyjęty w:" onBlur={handleBlur("first_hospitalization")} keyboardType="numeric" editable={values.past_psychiatric_treatment !== false} /> <FillForm name="hospitalization_times" onChangeText={handleChange("hospitalization_times")} placeholder={values.past_psychiatric_treatment ? "ilość razy" : "0"} labelText="Liczba hospitalizacji: " onBlur={handleBlur("hospitalization_times")} keyboardType="numeric" editable={values.past_psychiatric_treatment !== false} value={values.past_psychiatric_treatment === false ? "0" : null} /> <Text style={styles.listItemFieldText}>{"> "} farmakoterapia</Text> <FormField name="pharmacotherapy" onChangeText={handleChange("pharmacotherapy")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("pharmacotherapy")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} psychoterapia</Text> <FormField name="psychotherapy" onChangeText={handleChange("psychotherapy")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("psychotherapy")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} terapia rodzin</Text> <FormField name="family_therapy" onChangeText={handleChange("family_therapy")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("family_therapy")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Stosowane leki</Text> <Text style={styles.commentFieldText}> (z uwzględnieniem wszystkich leków przyjmowanych obecnie) </Text> <FormField name="medications" onChangeText={handleChange("medications")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("medications")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Uczulenia i osobnicze reakcje</Text> <FormField name="allergies" onChangeText={handleChange("allergies")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("allergies")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Ocena stanu społecznego</Text> <Text style={styles.listItemFieldText}>{"> "} higiena</Text> <FormField name="hygiene" onChangeText={handleChange("hygiene")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("hygiene")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} poziom wykształcenia</Text> <RadioButton name="education_choice" options={[ "podstawowe", "gimnazjum", "średnie", "maturalne", "wyższe", "doktorat", "habilitacja", "profesura", ]} /> <FormField name="education" onChangeText={handleChange("education")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("education")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} status zawodowy</Text> <FormField name="professional_status" onChangeText={handleChange("professional_status")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("professional_status")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} warunki socjalne, materialne, mieszkaniowe </Text> <FormField name="social_conditions" onChangeText={handleChange("social_conditions")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("social_conditions")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} korzystanie z pomocy społecznej </Text> <Select name="social_assistance_choice" leftText="tak" rightText="nie" /> <FormField name="social_assistance" onChangeText={handleChange("social_assistance")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("social_assistance")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} zmiany poziomu funkcjonowania społecznego </Text> <FormField name="social_level_changes" onChangeText={handleChange("social_level_changes")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("social_level_changes")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Wywiad rodzinny i rozwojowy</Text> <Text style={styles.listItemFieldText}> {"> "} istotne dane rozwojowe </Text> <FormField name="development_data" onChangeText={handleChange("development_data")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("development_data")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} sytuacja rodzinna</Text> <FormField name="family_situation" onChangeText={handleChange("family_situation")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("family_situation")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} zmiany sytuacji rodzinnej na przestrzeni ostatnich lat </Text> <FormField name="family_situation_changes" onChangeText={handleChange("family_situation_changes")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("family_situation_changes")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} relacje rodzinne z uwzględnieniem więzi i obszarów konfliktowych </Text> <FormField name="family_relationships" onChangeText={handleChange("family_relationships")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("family_relationships")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} obciążenia dziedziczne </Text> <Text style={styles.commentFieldText}> (w tym zwłaszcza chorobami psychicznymi, uzależnieniami, myślami i tendencjami suicydalnymi lub homicydalnymi) </Text> <FormField name="hereditary_taint" onChangeText={handleChange("hereditary_taint")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("hereditary_taint")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Wywiad środowiskowy</Text> <Text style={styles.listItemFieldText}> {"> "} poziom aktywności fizycznej </Text> <FormField name="physical_activity" onChangeText={handleChange("physical_activity")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("physical_activity")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} samouszkodzenia w wywiadzie </Text> <FormField name="self_mutilation" onChangeText={handleChange("self_mutilation")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("self_mutilation")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} narażenie na zagrożenie zawodowe </Text> <FormField name="occupational_exposure" onChangeText={handleChange("occupational_exposure")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("occupational_exposure")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Używki</Text> <Text style={styles.listItemFieldText}>{"> "} alkohol</Text> <FormField name="alcohol" onChangeText={handleChange("alcohol")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("alcohol")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}>{"> "} nikotyna</Text> <FormField name="nicotine" onChangeText={handleChange("nicotine")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("nicotine")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.listItemFieldText}> {"> "} nielegalne substancje psychoaktywne </Text> <FormField name="psychoactive_substances" onChangeText={handleChange("psychoactive_substances")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("psychoactive_substances")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Dieta</Text> <RadioButton name="diet_choice" options={[ "pacjent nie przestrzega żadnych zasad dietetycznych", "w wywiadzie istotne błędy dietetyczne", "nadmierna podaż kaloryczna", "niedostateczna podaż kaloryczna", "dieta uboga", "dieta cukrzycowa", "dieta niskotłuszczowa", "dieta oszczędzająca", "dieta bezmięsna", "pacjent stosuje dietę zgodną z zaleceniami lekarskimi", "pacjent cierpi na zaburzenia odżywiania w istotny sposób zaburzające codzienną dietę", "pacjent nie przestrzega zaleceń lekarskich co do diety", "dieta zgodna z wyznawaną religią i światopoglądem", ]} /> <FormField name="diet" onChangeText={handleChange("diet")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("diet")} keyboardType="default" multiline numberOfLines={2} /> <Text style={styles.subtitleText}>Wywiad od rodziny</Text> <FormField name="family_interview" onChangeText={handleChange("family_interview")} placeholder="Miejsce do uzupełnienia" onBlur={handleBlur("family_interview")} keyboardType="default" multiline numberOfLines={2} /> </> ); }; const styles = formStyles; BasicDataForm.propTypes = { handleChange: PropTypes.func.isRequired, handleBlur: PropTypes.func.isRequired, values: PropTypes.shape({ past_psychiatric_treatment: PropTypes.bool.isRequired, }).isRequired, }; export default BasicDataForm; <file_sep>import React, { useContext, useState } from "react"; import PropTypes from "prop-types"; import { Alert, FlatList, StyleSheet, Text } from "react-native"; import Result from "../../components/diagnosis/Result"; import DiagnosisContainer from "./DiagnosisContainer"; import { diseasesProbabilityPropTypes } from "../../constants/propTypes/diagnosis"; import { Colors, Typography } from "../../constants/styles"; import TextButton from "../../components/common/TextButton"; import { DiagnosisContext } from "../../modules/context/DiagnosisContext"; const DiagnosisResults = ({ navigation, route }) => { const threshold = 0.33; const { diseasesProbability, moduleCode } = route.params; const filteredDiseasesProbability = diseasesProbability .filter((diseaseProbability) => { return diseaseProbability.probability > threshold; }) .sort((a, b) => parseFloat(b.probability) - parseFloat(a.probability)); const [submitDiagnosis, setDiagnosis] = useState([]); const { addDiagnose } = useContext(DiagnosisContext); const toggleDiagnosis = (diagnosis) => { const newSubmitDiagnosis = submitDiagnosis; const diagnosisIndex = submitDiagnosis.findIndex((diag) => { return diag.disease_icd10 === diagnosis.disease_icd10; }); if (diagnosisIndex === -1) { newSubmitDiagnosis.push(diagnosis); } else { newSubmitDiagnosis.splice(diagnosisIndex); } setDiagnosis(newSubmitDiagnosis); }; const onSubmit = () => { if (submitDiagnosis.length > 0) { addDiagnose(moduleCode, submitDiagnosis); navigation.navigate("ModulesList"); } else { Alert.alert( "", "Nie zatwierdzono żadnej diagnozy. Czy na pewno chcesz zakończyć i powrócić do listy modułów?", [ { text: "Kontynuuj", style: "cancel", onPress: () => {}, }, { text: "Zakończ", style: "destructive", onPress: () => { navigation.navigate("ModulesList"); }, }, ] ); } }; return ( <DiagnosisContainer moduleCode={moduleCode} subTitle="Podsumowanie"> {filteredDiseasesProbability.length > 0 && ( <FlatList data={filteredDiseasesProbability} renderItem={({ item }) => ( <Result onCheckboxPress={() => toggleDiagnosis(item)} item={item} /> )} keyExtractor={(item, index) => index.toString()} ListFooterComponent={ <TextButton onPress={onSubmit} text="Dodaj rozpoznanie" /> } ListFooterComponentStyle={styles.submitButtonStyle} ListHeaderComponent={ <Text style={styles.infoText}> Zaznacz pola, które Twoim zdaniem odpowiadają trafnej diagnozie </Text> } /> )} {filteredDiseasesProbability.length === 0 && ( <Text style={styles.text}> Brak chorób o prawdopodobieństwie większym niż {threshold * 100}% </Text> )} </DiagnosisContainer> ); }; DiagnosisResults.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, }).isRequired, route: PropTypes.shape({ params: PropTypes.shape({ diseasesProbability: diseasesProbabilityPropTypes.isRequired, moduleCode: PropTypes.string.isRequired, }).isRequired, }).isRequired, }; const styles = StyleSheet.create({ submitButtonStyle: { marginTop: 20, }, infoText: { marginBottom: 20, marginHorizontal: 10, color: Colors.PURPLE, ...Typography.FONT_REGULAR, fontSize: Typography.FONT_SIZE_14, }, text: { flex: 1, fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_REGULAR, color: Colors.PURPLE, paddingLeft: 10, }, }); export default DiagnosisResults; <file_sep>import React, { useEffect } from "react"; import { database } from "../database/database"; function useDatabase() { const [isDBLoadingComplete, setDBLoadingComplete] = React.useState(false); useEffect(() => { async function loadDataAsync() { try { await database.initDB(); setDBLoadingComplete(true); } catch (e) { console.warn(e); } } loadDataAsync(); }, []); return isDBLoadingComplete; } export default useDatabase; <file_sep>import PropTypes from "prop-types"; import { PATIENT_CODE_REGEX } from "../values/constants"; export const CodeProp = (props, propName, componentName) => { if ( !PATIENT_CODE_REGEX.test( // eslint-disable-next-line react/destructuring-assignment props[propName] ) ) { return new Error( `Invalid Code: \`${propName}\` supplied to` + ` \`${componentName}\`. Validation failed.` ); } return null; }; export const DiagnosisProptypes = PropTypes.shape({ id: PropTypes.number.isRequired, disease_icd10: CodeProp.isRequired, disease_name: PropTypes.string.isRequired, module_code: PropTypes.string.isRequired, module_name: PropTypes.string.isRequired, timestamp: PropTypes.number.isRequired, }); // TODO: Add guardianship to patient table const Patient = PropTypes.shape({ id: PropTypes.number.isRequired, name: PropTypes.string.isRequired, surname: PropTypes.string.isRequired, sex: PropTypes.string.isRequired, phone: PropTypes.string, weight: PropTypes.number, height: PropTypes.number, bmi: PropTypes.number, pesel: PropTypes.string, date_of_birth: PropTypes.string.isRequired, note: PropTypes.string, person_guard: PropTypes.string, phone_guard: PropTypes.string, diagnosis: PropTypes.arrayOf(DiagnosisProptypes), }); export default Patient; <file_sep>import PropTypes from "prop-types"; const PatientBasicData = PropTypes.shape({ patient_id: PropTypes.number.isRequired, reason_of_report: PropTypes.string, major_ailments: PropTypes.string, suicidal_thoughts_choice: PropTypes.number, suicidal_thoughts: PropTypes.string, other_ailments: PropTypes.string, past_diseases_choice: PropTypes.string, past_diseases: PropTypes.string, past_psychiatric_treatment: PropTypes.number, first_hospitalization: PropTypes.string, hospitalization_times: PropTypes.number, pharmacotherapy: PropTypes.string, psychotherapy: PropTypes.string, family_therapy: PropTypes.string, medications_used: PropTypes.string, allergies: PropTypes.string, hygiene: PropTypes.string, education_choice: PropTypes.string, education: PropTypes.string, professional_status: PropTypes.string, social_conditions: PropTypes.string, social_assistance_choice: PropTypes.number, social_assistance: PropTypes.string, social_level_changes: PropTypes.string, development_data: PropTypes.string, family_situation: PropTypes.string, family_situation_changes: PropTypes.string, family_relationships: PropTypes.string, hereditary_taint: PropTypes.string, physical_activity: PropTypes.string, self_mutilation: PropTypes.string, occupational_exposure: PropTypes.string, alcohol: PropTypes.string, nicotine: PropTypes.string, psychoactive_substances: PropTypes.string, diet_choice: PropTypes.string, diet: PropTypes.string, family_interview: PropTypes.string, }); export default PatientBasicData; <file_sep>import React from "react"; import { View, TextInput, Text, StyleSheet } from "react-native"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import FormError from "./FormError"; import { Colors, Typography } from "../../../constants/styles"; import FontForgeIcon from "../../common/FontForgeIcon"; const FillForm = ({ name, leftIcon, keyboardType, placeholder, labelText, calculateDependentValue, ...otherProps }) => { const { setFieldTouched, setFieldValue, errors, touched, } = useFormikContext(); const leftMargin = () => { return { marginLeft: leftIcon ? 0 : 52, }; }; return ( <> <View style={styles.container}> {leftIcon && ( <FontForgeIcon name="name" size={38} color={Colors.PINK_MEDIUM} style={styles.icon} /> )} <Text style={[styles.labelText, leftMargin()]}>{labelText}</Text> <TextInput style={styles.input} placeholderTextColor={Colors.PURPLE_LIGHT} placeholder={placeholder} onChangeText={(text) => setFieldValue(name, text)} onBlur={() => setFieldTouched(name)} keyboardType={keyboardType} calculateDependentValue={calculateDependentValue} // eslint-disable-next-line react/jsx-props-no-spreading {...otherProps} /> </View> <FormError error={errors[name]} visible={touched[name]} /> </> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: Colors.GRAY_VERY_LIGHT, flexDirection: "row", padding: 7, justifyContent: "center", alignItems: "center", alignSelf: "center", right: 20, }, icon: { marginRight: 15, }, labelText: { fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_REGULAR, color: Colors.BLACK, marginRight: 20, }, input: { width: "16%", fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_LIGHT, color: Colors.BLACK, borderBottomColor: Colors.PURPLE_LIGHT, borderBottomWidth: 2, }, }); FillForm.defaultProps = { leftIcon: null, calculateDependentValue: null, }; FillForm.propTypes = { name: PropTypes.string.isRequired, leftIcon: PropTypes.string, keyboardType: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, labelText: PropTypes.string.isRequired, calculateDependentValue: PropTypes.func, }; export default FillForm; <file_sep>import React, { useState } from "react"; import PropTypes from "prop-types"; import { StyleSheet, Text, View } from "react-native"; import { useFormikContext } from "formik"; import Checkbox from "../common/Checkbox"; import FormError from "../forms/fields/FormError"; import formStyles from "../../constants/styles/formStyles"; import { Colors, Typography } from "../../constants/styles"; const DiagnosisQuestionItem = React.memo( ({ question, index, defaultAnswer }) => { const [answer, setLocalAnswer] = useState(defaultAnswer); const { errors, touched, setFieldValue, values } = useFormikContext(); const setNewAnswer = (newAnswer) => { setLocalAnswer(newAnswer); values.answers.splice(index, 1, newAnswer); setFieldValue("answers", values.answers); }; return ( <View> <Text style={styles.subtitleText}>{question.content}</Text> <View style={styles.answersContainer}> <View style={styles.singleAnswerContainer}> <Checkbox isChecked={answer === 1} onPress={() => setNewAnswer(1)} style={styles.icon} /> <Text style={styles.text}>Tak</Text> </View> <View style={styles.singleAnswerContainer}> <Checkbox isChecked={answer === 0} onPress={() => setNewAnswer(0)} style={styles.icon} /> <Text style={styles.text}>Nie</Text> </View> </View> <FormError error={ !!errors.answers && !!errors.answers[index] ? errors.answers[index] : null } visible={!!touched.answers} /> </View> ); }, (prevProps, nextProps) => prevProps.index === nextProps.index ); const styles = StyleSheet.create({ answersContainer: { backgroundColor: Colors.GRAY_VERY_LIGHT, flex: 2, flexDirection: "row", alignItems: "center", justifyContent: "center", marginTop: 10, marginLeft: 60, marginRight: 30, }, singleAnswerContainer: { flex: 1, flexDirection: "row", alignItems: "center", justifyContent: "center", }, subtitleText: { ...formStyles.subtitleText, marginLeft: 10 }, icon: { flex: 0.4, alignSelf: "flex-end", }, text: { flex: 0.6, fontSize: Typography.FONT_SIZE_13, fontFamily: Typography.FONT_FAMILY_REGULAR, color: Colors.BLACK, }, }); DiagnosisQuestionItem.defaultProps = { defaultAnswer: -1, }; DiagnosisQuestionItem.propTypes = { question: PropTypes.shape({ id: PropTypes.number, content: PropTypes.string.isRequired, }).isRequired, index: PropTypes.number.isRequired, defaultAnswer: PropTypes.oneOf([-1, 0, 1]), }; export default DiagnosisQuestionItem; <file_sep>import * as Yup from "yup"; const physicalExaminationValidationSchema = Yup.object().shape({ general_conditions: Yup.string() .oneOf(["dobry", "średni", "ciężki"]) .required("Stan ogólny jest wymaganym polem") .label("Stan ogólny"), blood_pressure: Yup.string().label("Ciśnienie tętnicze"), pulse: Yup.string().label("Tętno"), body_temperature: Yup.string().label("Ciepłota ciała"), body_build_type: Yup.string() .oneOf(["normosteniczna", "hyposteniczna", "hypersteniczna"]) .required("Budowa ciała jest wymaganym polem") .label("Budowa ciała"), skin_appearance: Yup.string().label("Skóra i tk. podskórna - wygląd"), skin_colour: Yup.string().label("Skóra i tk. podskórna - barwa"), skin_humidity: Yup.string().label("Skóra i tk. podskórna - wilgotność"), skin_swelling: Yup.string().label("Skóra i tk. podskórna - obrzęki"), skin_scars: Yup.string().label("Blizny i ślady po samouszkodzeniach"), lymphatic_gland_examined: Yup.bool() .required("Obwodowe węzły chłonne jest wymaganym polem") .label("Obwodowe węzły chłonne"), head_appearance_choice: Yup.bool().label( "Głowa wysklepiona symetrycznie, prawidłowo" ), head_appearance: Yup.string().label("Głowa - wygląd"), head_percussion_tenderness: Yup.string().label("Głowa - bolesność opukowo"), head_eyeballs: Yup.string().label("Gałki oczne"), ears: Yup.string().label("Uszy"), nose: Yup.string().label("Nos"), mouth_teeth: Yup.string() .oneOf(["nieuporządkowane", "uporządkowane", "zaprotezowane"]) .required("Jama ustna i uzębienie jest wymaganym polem") .label("Jama ustna i uzębienie"), mucous_membrane_choice: Yup.string().label("Błony śluzowe"), mucous_membrane: Yup.string().label("Błony śluzowe"), neck_throat_tonsil: Yup.string().label("Gardło i migdałki"), neck_appearance: Yup.string().label("Szyja - wygląd"), neck_thyroid_choice: Yup.string().label("Tarczyca"), neck_thyroid: Yup.string().label("Tarczyca"), chest_choice: Yup.string().label("Klatka piersiowa"), chest: Yup.string().label("Klatka piersiowa"), breath_frequency: Yup.string().label("Częstość oddechów/min"), chest_percussion_choice: Yup.string() .oneOf(["wypuk jawny", "wypuk stłumiony"]) .label("Klatka piersiowa - opukiwanie"), chest_percussion: Yup.string().label("Klatka piersiowa - opukiwanie"), chest_auscultation_choice: Yup.bool().label( "Klatka piersiowa - osłuchiwanie" ), chest_auscultation: Yup.string().label("Klatka piersiowa - osłuchiwanie"), cardiovascular_appearance: Yup.string().label("Układ krążenia - oglądanie"), cardiovascular_efficient: Yup.string().label("Układ krążenia - wydolny"), cardiovascular_auscultation: Yup.string().label( "Układ krążenia - osłuchiwano" ), cardiovascular_pulse_choice: Yup.bool() .nullable() .label( "Tętno na tt. promieniowych i grzbietowych stopy zgodne z akcją serca" ), cardiovascular_pulse: Yup.string().label( "Tętno na tt. promieniowych i grzbietowych stopy zgodne z akcją serca" ), stomach: Yup.string() .oneOf([ "wysklepiony w poziomie klp", "wysklepiony ponad poziom klp", "poniżej poziomu klp", ]) .required("Brzuch jest wymaganym polem") .label("Brzuch"), stomach_hernia: Yup.string().label("Brzuch - przepukliny"), stomach_painless: Yup.string().label("Brzuch - niebolesny"), stomach_auscultation: Yup.string().label("Brzuch - osłuchowo perystaltyka"), stomach_percussion: Yup.string().label("Brzuch - opukiwanie"), stomach_physical_examination: Yup.string().label("Brzuch - badanie dotykiem"), stomach_symptoms: Yup.string().label("Brzuch - objawy"), legs_swelling: Yup.string().label("Kończyny dolne - obrzęki"), legs_veins: Yup.string().label("Kończyny dolne - układ żylny"), locomotor_joint_outline: Yup.bool() .required("Obrysy stawów jest wymaganym polem") .label("Układ ruchowy - obrysy stawów"), locomotor_limb_mobility: Yup.bool() .required( "Ruchomość bierna i czynna w stawach kończyn jest wymaganym polem" ) .label("Układ ruchowy - ruchomość bierna i czynna w stawach kończyn"), muscle_strength_tension: Yup.bool() .required("Siła i napięcie mięśniowe jest wymaganym polem") .label("Układ ruchowy - siła i napięcie mięśniowe"), nervous_meningeal_signs: Yup.string().label("Układ ruchowy - objawy oponowe"), nervous_focal_damage: Yup.string().label( "Objawy ogniskowego uszkodzenia systemu nerwowego" ), }); export default physicalExaminationValidationSchema; <file_sep>import React from "react"; import { View, TouchableOpacity, StyleSheet } from "react-native"; import PropTypes from "prop-types"; import { Colors } from "../../constants/styles"; import SubtitleLabel from "./SubtitleLabel"; import FontForgeIcon from "../common/FontForgeIcon"; const SubtitleLabelWithButton = ({ subtitle, iconName, onAdd }) => { return ( <View style={styles.subtitleContainer}> <SubtitleLabel subtitle={subtitle} iconName={iconName} /> <TouchableOpacity onPress={onAdd} style={styles.buttonAdd}> <FontForgeIcon name="add" size={20} color={Colors.PINK} /> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ subtitleContainer: { flexDirection: "row", justifyContent: "space-between" }, buttonAdd: { alignSelf: "center", marginRight: 30, marginTop: 12, }, }); SubtitleLabelWithButton.propTypes = { subtitle: PropTypes.string.isRequired, iconName: PropTypes.string.isRequired, onAdd: PropTypes.func.isRequired, }; export default SubtitleLabelWithButton; <file_sep>const diagnosisData = [ { id: 1, code: "AF42.2", name: "depresja", }, { id: 2, code: "BF42.3", name: "nerwica", }, ]; export default diagnosisData; <file_sep>import { useEffect, useState } from "react"; import Builder from "crane-query-builder"; import { TABLES } from "../database/database"; const useDiagnosisConditions = (moduleCode) => { const [diagnosisData, setDiagnosisData] = useState([]); useEffect(() => { const fetchDiagnosisConditionsFromDb = async () => { const diagnosisConditions = await Builder() .table(TABLES.diseases) .where("module_code", moduleCode) .join( TABLES.diagnosis_conditions, `${TABLES.diseases}.id`, "=", `${TABLES.diagnosis_conditions}.disease_id` ) .get(); setDiagnosisData(diagnosisConditions); }; fetchDiagnosisConditionsFromDb(); }, []); return [diagnosisData]; }; export default useDiagnosisConditions; <file_sep>export const PHYSICAL_EXAMINATION_ACTIONS = { INSERT_OR_UPDATE: "INSERT_OR_UPDATE", REFRESH: "REFRESH", }; const physicalExaminationReducer = (state, action) => { switch (action.type) { case PHYSICAL_EXAMINATION_ACTIONS.INSERT_OR_UPDATE: { const { physicalExamination: setPhysicalExamination } = action.payload; const { patientsPhysicalExamination } = state; const physicalExaminationIndex = state.patientsPhysicalExamination.findIndex( (physicalExamination) => { return physicalExamination.id === setPhysicalExamination.id; } ); if (physicalExaminationIndex !== -1) { patientsPhysicalExamination[ physicalExaminationIndex ] = setPhysicalExamination; } else { patientsPhysicalExamination.push(setPhysicalExamination); } return { ...state, patientsPhysicalExamination, }; } case PHYSICAL_EXAMINATION_ACTIONS.REFRESH: { const { physicalExamination } = action.payload; return { ...state, physicalExamination, }; } default: return state; } }; export default physicalExaminationReducer; <file_sep>// eslint-disable-next-line import/prefer-default-export export const parseFormFieldValuesToObject = ( values, keysWithParingFunctions ) => { const object = values; Object.keys(keysWithParingFunctions).forEach((key) => { const parsingFunction = keysWithParingFunctions[key]; object[key] = parsingFunction(values[key]); }); return object; }; <file_sep>import React from "react"; import { View, Text, StyleSheet } from "react-native"; import PropTypes from "prop-types"; import { Colors, Typography } from "../../constants/styles"; import FontForgeIcon from "../common/FontForgeIcon"; const SubtitleLabel = ({ subtitle, iconName }) => { return ( <View style={styles.container}> <Text style={styles.subtitle}>{subtitle}</Text> <FontForgeIcon name={iconName} size={22} color={Colors.PINK} style={styles.leftIcon} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 2, flexDirection: "row", }, subtitle: { marginLeft: 35, marginVertical: 5, paddingTop: 10, color: Colors.PURPLE, fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_BOLD, alignSelf: "center", }, leftIcon: { alignSelf: "center", marginTop: 10, marginLeft: 3, }, }); SubtitleLabel.propTypes = { subtitle: PropTypes.string.isRequired, iconName: PropTypes.string.isRequired, }; export default SubtitleLabel; <file_sep>import React from "react"; import { StyleSheet, Text, View, ViewPropTypes } from "react-native"; import FontForgeIcon from "../../common/FontForgeIcon"; import Patient from "../../../constants/propTypes/patientPropTypes"; import { Colors } from "../../../constants/styles"; import { FONT_REGULAR, FONT_BOLD, FONT_SIZE_16, } from "../../../constants/styles/typography"; const Header = ({ style, patient }) => { return ( <View style={[styles.container, style]}> <Text style={styles.surname}> {patient.surname} <Text style={styles.name}> {patient.name}</Text> </Text> <View style={styles.codeContainer}> <FontForgeIcon name="patient_number" size={32} color={Colors.PINK_MEDIUM} /> <Text style={styles.code}>{patient.id}</Text> </View> </View> ); }; const styles = StyleSheet.create({ container: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", padding: 4, }, codeContainer: { flexDirection: "row", alignItems: "center" }, surname: { ...FONT_BOLD, fontSize: FONT_SIZE_16, color: Colors.PURPLE, flexShrink: 0.5, }, name: { ...FONT_REGULAR, fontSize: FONT_SIZE_16, color: Colors.PURPLE, alignSelf: "center", }, code: { ...FONT_BOLD, fontSize: FONT_SIZE_16, color: Colors.PINK, alignSelf: "center", marginLeft: 8, }, }); Header.defaultProps = { style: {}, }; Header.propTypes = { patient: Patient.isRequired, style: ViewPropTypes.style, }; export default Header; <file_sep>import React, { createContext, useEffect, useReducer } from "react"; import PropTypes from "prop-types"; import Builder from "crane-query-builder"; import reducer, { DIAGNOSIS_ACTIONS } from "./DiagnosisReducer"; import { database, TABLES } from "../database/database"; export const DiagnosisContext = createContext({ modules: {}, patientId: 0, }); function DiagnosisContextProvider({ children, patientId }) { const [state, dispatch] = useReducer(reducer, { patientId }); useEffect(() => { const fetchModulesFromDb = async () => { const fetchedModules = await Builder().table(TABLES.modules).get(); dispatch({ type: DIAGNOSIS_ACTIONS.SET_MODULES, payload: { modules: fetchedModules }, }); }; fetchModulesFromDb(); }, []); const addDiagnose = (moduleCode, diagnosis) => { dispatch({ type: DIAGNOSIS_ACTIONS.ADD_DIAGNOSIS, payload: { moduleCode, diagnosis }, }); }; const setModuleVisited = (moduleCode) => { dispatch({ type: DIAGNOSIS_ACTIONS.SET_VISITED, payload: { moduleCode }, }); }; const addAnswers = (moduleCode, answers, isMinor) => { dispatch({ type: DIAGNOSIS_ACTIONS.ADD_ANSWERS, payload: { moduleCode, answers, isMinor }, }); }; const addModuleQuestions = (moduleCode, questions, isMinor) => { dispatch({ type: DIAGNOSIS_ACTIONS.ADD_MODULE_QUESTIONS, payload: { moduleCode, questions, isMinor }, }); }; const deleteDiagnosis = (moduleCode, diseaseIcd10) => { dispatch({ type: DIAGNOSIS_ACTIONS.DELETE_DIAGNOSIS, payload: { moduleCode, diseaseIcd10 }, }); }; const resetModuleDiagnosis = (moduleCode) => { dispatch({ type: DIAGNOSIS_ACTIONS.RESET_MODULE_DIAGNOSIS, payload: { moduleCode }, }); }; const saveInDB = async () => { const modules = await state.modules; const id = await state.patientId; const diseases = await database.getAllFromTable(TABLES.diseases); for (let i = 0; i < Object.keys(modules).length; i += 1) { const [moduleCode, module] = Object.entries(modules)[i]; for ( let diagnosisIdx = 0; diagnosisIdx < module.diagnosis.length; diagnosisIdx += 1 ) { const { id: diseaseId } = diseases.filter((disease) => { return ( disease.disease_icd10 === module.diagnosis[diagnosisIdx].disease_icd10 ); })[0]; const timestamp = new Date().getTime() / 1000; const patientDiagnosis = { patient_id: id, disease_id: diseaseId, timestamp, }; try { // eslint-disable-next-line no-await-in-loop const diagnosisId = await database.insertObjectToTable( patientDiagnosis, TABLES.patients_diagnosis ); const majorAnswers = module.majorAnswers.map((answer, idx) => { return { diagnosis_id: diagnosisId, answer, question_id: module.majorQuestions[idx].id, }; }); const minorAnswers = module.minorAnswers.map((answer, idx) => { return { diagnosis_id: diagnosisId, answer, question_id: module.minorQuestions[idx].id, }; }); const allAnswers = majorAnswers.concat(minorAnswers); // eslint-disable-next-line no-await-in-loop await database.insertMultipleObjectsToTable( allAnswers, TABLES.diagnosis_answers ); dispatch({ type: DIAGNOSIS_ACTIONS.UPDATE_DIAGNOSIS_DATA, payload: { diagnosisId, diagnosisIdx, timestamp, moduleCode }, }); } catch (e) { return; } } } }; const value = { ...state, setModuleVisited, addDiagnose, addAnswers, saveInDB, deleteDiagnosis, resetModuleDiagnosis, addModuleQuestions, }; return ( <DiagnosisContext.Provider value={value}> {children} </DiagnosisContext.Provider> ); } DiagnosisContextProvider.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, patientId: PropTypes.number.isRequired, }; export default DiagnosisContextProvider; <file_sep>import * as Yup from "yup"; const basicDataValidationSchema = Yup.object().shape({ reason_of_report: Yup.string().label("Powód i kontekst zgłoszenia"), major_ailments: Yup.string().label("Główne dolegliwości"), suicidal_thoughts_choice: Yup.boolean() .nullable() .label("Obecność myśli i tendencji suicydalnych lub homicydalnych"), suicidal_thoughts: Yup.string().label( "Obecność myśli i tendencji suicydalnych lub homicydalnych" ), other_ailments: Yup.string().label("Inne dolegliwości"), past_diseases_choice: Yup.string().label("Przebyte choroby i operacje"), past_diseases: Yup.string().label("Przebyte choroby i operacje"), past_psychiatric_treatment: Yup.boolean() .nullable() .label("Przebyte leczenie psychiatryczne"), first_hospitalization: Yup.string().label("Rok pierwszej hospitalizacji"), hospitalization_times: Yup.number().label("Liczba hospitalizacji"), pharmacotherapy: Yup.string().label("Farmakoterapia"), psychotherapy: Yup.string().label("Psychoterapia"), family_therapy: Yup.string().label("Terapia rodzin"), medications_used: Yup.string().label("Stosowane leki"), allergies: Yup.string().label("Uczulenia i osobnicze reakcje"), hygiene: Yup.string().label("Higiena"), education_choice: Yup.string().label("Poziom wykształcenia"), education: Yup.string().label("Poziom wykształcenia"), professional_status: Yup.string().label("Status zawodowy"), social_conditions: Yup.string().label( "Warunki socjalne, materialne, mieszkaniowe" ), social_assistance_choice: Yup.boolean() .nullable() .label("Korzystanie z pomocy społecznej"), social_assistance: Yup.string().label("Korzystanie z pomocy społecznej"), social_level_changes: Yup.string().label( "Zmiany poziomu funkcjonowania społecznego" ), development_data: Yup.string().label("Istotne dane rozwojowe"), family_situation: Yup.string().label("Sytuacja rodzinna"), family_situation_changes: Yup.string().label( "Zmiany sytuacji rodzinnej na przestrzeni ostatnich lat" ), family_relationships: Yup.string().label( "Relacje rodzinne z uwzględnieniem więzi i obszarów konfliktowych" ), hereditary_taint: Yup.string().label("Obciążenia dziedziczne"), physical_activity: Yup.string().label("Poziom aktywności fizycznej"), self_mutilation: Yup.string().label("Samouszkodzenia w wywiadzie"), occupational_exposure: Yup.string().label("Narażenie na zagrożenie zawodowe"), alcohol: Yup.string().label("Alkohol"), nicotine: Yup.string().label("Nikotyna"), psychoactive_substances: Yup.string().label( "Nielegalne substancje psychoaktywne" ), diet_choice: Yup.string().label("Dieta"), diet: Yup.string().label("Dieta"), family_interview: Yup.string().label("Wywiad od rodziny"), }); export default basicDataValidationSchema; <file_sep>export const BASIC_DATA_ACTIONS = { INSERT_OR_UPDATE: "INSERT_OR_UPDATE", REFRESH: "REFRESH", }; const basicDataReducer = (state, action) => { switch (action.type) { case BASIC_DATA_ACTIONS.INSERT_OR_UPDATE: { const { basicData: setBasicData } = action.payload; const { patientsBasicData } = state; const basicDataIndex = state.patientsBasicData.findIndex((basicData) => { return basicData.id === setBasicData.id; }); if (basicDataIndex !== -1) { patientsBasicData[basicDataIndex] = setBasicData; } else { patientsBasicData.push(setBasicData); } return { ...state, patientsBasicData, }; } case BASIC_DATA_ACTIONS.REFRESH: { const { patientsBasicData } = action.payload; return { ...state, patientsBasicData, }; } default: return state; } }; export default basicDataReducer; <file_sep>export const PRIMARY = "#1779ba"; export const SECONDARY = "#767676"; export const WHITE = "#FFFFFF"; export const BLACK = "#000000"; // COLOR PALETTE export const PURPLE_VERY_LIGHT = "#CCBDDC"; export const PURPLE_LIGHT = "#B6A4C9"; export const PURPLE_MEDIUM = "#724C82"; export const PURPLE = "#482358"; export const PINK_MEDIUM = "#CE8CA1"; export const PINK = "#CA7B95"; export const GREEN = "#67a797"; export const RED = "#cc4b37"; // ACTIONS export const SUCCESS = "#3adb76"; export const WARNING = "#ffae00"; export const ALERT = "#cc4b37"; export const BMI_OVERWEIGHT = "#dc143c"; export const BMI_UNDERWEIGHT = "#2D93AD"; // GRAYSCALE export const GRAY_VERY_LIGHT = "#f2f2f2"; export const GRAY_LIGHT = "#e6e6e6"; export const GRAY_MEDIUM = "#cacaca"; export const GRAY_DARK = "#8a8a8a"; <file_sep>import { createIconSet } from "@expo/vector-icons"; import glyphMap from "../../assets/fonts/glyphMap.json"; import IconFont from "../../assets/fonts/IconFont.ttf"; const FontForgeIcon = createIconSet(glyphMap, "IconFont", IconFont); export default FontForgeIcon; <file_sep>import React, { useContext, useState } from "react"; import PropTypes from "prop-types"; import { Formik } from "formik"; import AppButton from "../../components/common/AppButton"; import { BasicDataContext } from "../../modules/context/BasicDataContext"; import basicDataValidationSchema from "../../constants/validationSchemas/basicDataValidationSchema"; import BasicDataForm from "../../components/forms/BasicDataForm"; import FormContainer from "../../components/forms/FormContainer"; import { parseFormFieldValuesToObject } from "../../modules/utils/Parsers"; const BasicData = ({ route, navigation }) => { const { basicDataId, physicalExaminationId, psychiatricAssessmentId, } = route.params; const { patientsBasicData, updateBasicData } = useContext(BasicDataContext); const [isNextButtonDisabled, setNextButtonDisabled] = useState(false); const initialState = patientsBasicData.find( (basicData) => basicData.id === basicDataId ); const keysWithParserFunctions = { hospitalization_times: (val) => parseInt(val, 10), }; const onButtonPressed = async (values) => { setNextButtonDisabled(true); const basicData = parseFormFieldValuesToObject( values, keysWithParserFunctions ); const result = await updateBasicData(basicData); if (result) { navigation.navigate("PhysicalExamination", { physicalExaminationId, psychiatricAssessmentId, }); } // TODO: Show alert with info what is wrong }; return ( <FormContainer title="Wywiad"> <Formik initialValues={initialState} enableReinitialize validationSchema={basicDataValidationSchema} onSubmit={(values) => onButtonPressed(values)} > {({ handleChange, values, handleSubmit, isValid, handleBlur, isSubmitting, }) => ( <> <BasicDataForm handleBlur={handleBlur} handleChange={handleChange} values={values} /> <AppButton icon="next_btn" onPress={handleSubmit} disabled={!isValid || isSubmitting || isNextButtonDisabled} /> </> )} </Formik> </FormContainer> ); }; BasicData.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, }).isRequired, route: PropTypes.shape({ params: PropTypes.shape({ basicDataId: PropTypes.number.isRequired, physicalExaminationId: PropTypes.number.isRequired, psychiatricAssessmentId: PropTypes.number.isRequired, }), }).isRequired, }; export default BasicData; <file_sep>import React from "react"; import { KeyboardAvoidingView, ScrollView, StyleSheet, Text, View, ViewPropTypes, } from "react-native"; import PropTypes from "prop-types"; import { Colors, Typography } from "../../constants/styles"; const FormContainer = ({ title, children, style }) => { return ( <KeyboardAvoidingView style={styles.backgroundContainer}> <ScrollView style={[styles.container, style]}> <View style={[styles.container, style]}> {title && <Text style={styles.titleText}>{title}</Text>} {children} </View> </ScrollView> </KeyboardAvoidingView> ); }; const styles = StyleSheet.create({ backgroundContainer: { flex: 1, backgroundColor: Colors.PURPLE, }, container: { flex: 1, backgroundColor: Colors.GRAY_VERY_LIGHT, borderTopRightRadius: 50, paddingTop: 22, paddingBottom: 22, }, titleText: { marginLeft: 30, marginBottom: 20, color: Colors.PURPLE, fontSize: Typography.FONT_SIZE_16, fontFamily: Typography.FONT_FAMILY_BOLD, }, }); FormContainer.defaultProps = { title: null, style: {}, }; FormContainer.propTypes = { children: PropTypes.node.isRequired, title: PropTypes.string, style: ViewPropTypes.style, }; export default FormContainer; <file_sep>import React from "react"; import { StyleSheet, View } from "react-native"; import { Colors } from "../../constants/styles"; import ButtonWithLabel from "./ButtonWithLabel"; const BottomMenu = () => { const onButtonPressed = () => {}; return ( <View style={styles.iconContainer}> <ButtonWithLabel label="Historia" onPress={onButtonPressed} icon="history" size={44} /> <ButtonWithLabel label="Nowe badanie" onPress={onButtonPressed} icon="new_examination" size={44} color={Colors.GREEN} /> <ButtonWithLabel label="Wyniki" onPress={onButtonPressed} icon="results" size={44} /> </View> ); }; const styles = StyleSheet.create({ iconContainer: { flex: 1, flexDirection: "row", justifyContent: "center", alignItems: "flex-end", }, }); export default BottomMenu; <file_sep>import { StyleSheet, Text, View } from "react-native"; import PropTypes from "prop-types"; import React, { useContext } from "react"; import { Colors, Typography } from "../../constants/styles"; import { DiagnosisContext } from "../../modules/context/DiagnosisContext"; const DiagnosisContainer = ({ children, moduleCode, subTitle }) => { const { modules } = useContext(DiagnosisContext); const module = modules ? modules[moduleCode] : null; return ( <View style={styles.backgroundContainer}> <View style={styles.container}> {module && ( <> <Text style={styles.moduleName}>{module.name}</Text> </> )} {!!subTitle && ( <> <Text style={styles.subTitle}>{subTitle}</Text> </> )} {children} </View> </View> ); }; const styles = StyleSheet.create({ backgroundContainer: { flex: 1, backgroundColor: Colors.PURPLE, justifyContent: "center", }, container: { flex: 1, backgroundColor: Colors.GRAY_VERY_LIGHT, borderTopRightRadius: 50, paddingTop: 20, justifyContent: "center", padding: 20, }, moduleName: { textTransform: "uppercase", fontSize: Typography.FONT_SIZE_16, fontFamily: Typography.FONT_FAMILY_BOLD, color: Colors.PURPLE, paddingVertical: 5, paddingLeft: 10, }, subTitle: { color: Colors.PURPLE, fontSize: Typography.FONT_SIZE_16, fontFamily: Typography.FONT_FAMILY_BOLD, paddingLeft: 10, marginBottom: 20, }, }); DiagnosisContainer.defaultProps = { moduleCode: "", subTitle: "", }; DiagnosisContainer.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, moduleCode: PropTypes.string, subTitle: PropTypes.string, }; export default DiagnosisContainer; <file_sep>import pandas as pd import json path_to_csv = r"data/modules_data.csv" df = pd.read_csv(path_to_csv) data = [] for column in df.columns: df[column] = df[column].fillna('null') for index, row in df.iterrows(): dict = { 'module_name': row['nazwa'], 'module_code': row['skrot'], 'min_major_true': row['min_liczba_major'] } data.append(dict) with open('modules_data.json', 'w') as o: json.dump(data, o) <file_sep>export const DIAGNOSIS_ACTIONS = { ADD_DIAGNOSIS: "ADD_DIAGNOSIS", ADD_ANSWERS: "ADD_ANSWERS", REMOVE_DIAGNOSIS: "REMOVE_DIAGNOSIS", SET_MODULES: "SET_MODULES", SET_VISITED: "SET_VISITED", DELETE_DIAGNOSIS: "DELETE_DIAGNOSIS", RESET_MODULE_DIAGNOSIS: "RESET_MODULE_DIAGNOSIS", ADD_MODULE_QUESTIONS: "ADD_MODULE_QUESTIONS", UPDATE_DIAGNOSIS_DATA: "UPDATE_DIAGNOSIS_DATA", }; const reducer = (state, action) => { switch (action.type) { case DIAGNOSIS_ACTIONS.SET_MODULES: { const newState = { ...state, modules: {} }; const { modules } = action.payload; modules.forEach((module) => { newState.modules[module.code] = {}; newState.modules[module.code].name = module.name; newState.modules[module.code].wasVisited = false; newState.modules[module.code].diagnosis = []; newState.modules[module.code].minMajorTrue = module.min_major_true; }); return newState; } case DIAGNOSIS_ACTIONS.SET_VISITED: { const { moduleCode } = action.payload; const newState = state; newState.modules[moduleCode].wasVisited = true; return newState; } case DIAGNOSIS_ACTIONS.ADD_ANSWERS: { const { moduleCode, answers, isMinor } = action.payload; const newState = state; if (isMinor) { newState.modules[moduleCode].minorAnswers = answers; } else { newState.modules[moduleCode].majorAnswers = answers; } return newState; } case DIAGNOSIS_ACTIONS.ADD_MODULE_QUESTIONS: { const { moduleCode, questions, isMinor } = action.payload; const newState = state; if (isMinor) { newState.modules[moduleCode].minorQuestions = questions; } else { newState.modules[moduleCode].majorQuestions = questions; } return newState; } case DIAGNOSIS_ACTIONS.ADD_DIAGNOSIS: { const { moduleCode, diagnosis } = action.payload; const newState = state; newState.modules[moduleCode].diagnosis = diagnosis; return newState; } case DIAGNOSIS_ACTIONS.DELETE_DIAGNOSIS: { const { moduleCode, diseaseIcd10 } = action.payload; const newState = state; newState.modules[moduleCode].diagnosis = state.modules[ moduleCode ].diagnosis.filter((diag) => { return diag.disease_icd10 !== diseaseIcd10; }); return newState; } case DIAGNOSIS_ACTIONS.RESET_MODULE_DIAGNOSIS: { const { moduleCode } = action.payload; const newState = state; newState.modules[moduleCode].diagnosis = []; return newState; } case DIAGNOSIS_ACTIONS.UPDATE_DIAGNOSIS_DATA: { const { diagnosisId, diagnosisIdx, timestamp, moduleCode, } = action.payload; const newState = state; newState.modules[moduleCode].diagnosis[diagnosisIdx].id = diagnosisId; newState.modules[moduleCode].diagnosis[ diagnosisIdx ].timestamp = timestamp; return newState; } default: return state; } }; export default reducer; <file_sep>import React from "react"; import { StyleSheet, Text } from "react-native"; import PropTypes from "prop-types"; import { Colors, Typography } from "../../../constants/styles"; const FormError = ({ error, visible }) => { const isVisibleAndHasError = error && visible; return isVisibleAndHasError ? ( <Text style={styles.errorText}>{error}</Text> ) : null; }; const styles = StyleSheet.create({ errorText: { marginLeft: 50, color: Colors.ALERT, fontSize: Typography.FONT_SIZE_14, fontFamily: Typography.FONT_FAMILY_REGULAR, marginBottom: 5, }, }); FormError.defaultProps = { error: "", visible: false, }; FormError.propTypes = { error: PropTypes.string, visible: PropTypes.bool, }; export default FormError; <file_sep>import { boxShadow, scaleFont } from "./mixins"; // FONT FAMILY export const FONT_FAMILY_LIGHT = "OpenSans-Light"; export const FONT_FAMILY_REGULAR = "OpenSans-Regular"; export const FONT_FAMILY_BOLD = "OpenSans-Bold"; // FONT WEIGHT export const FONT_WEIGHT_REGULAR = "400"; export const FONT_WEIGHT_LIGHT = "200"; export const FONT_WEIGHT_BOLD = "700"; // FONT SIZE export const FONT_SIZE_32 = scaleFont(32); export const FONT_SIZE_24 = scaleFont(24); export const FONT_SIZE_20 = scaleFont(20); export const FONT_SIZE_18 = scaleFont(18); export const FONT_SIZE_17 = scaleFont(17); export const FONT_SIZE_16 = scaleFont(16); export const FONT_SIZE_14 = scaleFont(14); export const FONT_SIZE_13 = scaleFont(13); export const FONT_SIZE_12 = scaleFont(12); // LINE HEIGHT export const LINE_HEIGHT_24 = scaleFont(24); export const LINE_HEIGHT_20 = scaleFont(20); export const LINE_HEIGHT_16 = scaleFont(16); // BOX SHADOW export const BOX_SHADOW = boxShadow(); // CORNERS export const BORDER_RADIUS = 20; export const BORDER_RADIUS_SLIGHT = 10; // FONT STYLE export const FONT_REGULAR = { fontFamily: FONT_FAMILY_REGULAR, fontWeight: FONT_WEIGHT_REGULAR, }; export const FONT_LIGHT = { fontFamily: FONT_FAMILY_LIGHT, fontWeight: FONT_WEIGHT_LIGHT, }; export const FONT_BOLD = { fontFamily: FONT_FAMILY_BOLD, fontWeight: FONT_WEIGHT_BOLD, }; <file_sep>## ❓What it is about? Doctor's assistant is a mobile application which supports psychiatrs in their work with patients. The project MVP is being developed as a part of Project Summer AILab&Glider event. The application is being implemented with Expo platform in a managed workflow. The main app feature includes: - 📒 Conducting a medical interview - 💊 Making a diagnose - 👨‍⚕️👩‍⚕️ Patients management <p align="middle"> <img src="/images/patients_list.jpg" width="30%" hspace="10"> <img src="/images/add_patient.jpg" width="30%" hspace="10"> <img src="/images/patient_card.jpg" width="30%"> </p> ## 📱 How to run it? 1. Clone the repository e.g.: ``` git clone https://github.com/Project-Summer-AI-Lab-Glider/doctors-assistant-app.git ``` 2. Install required dependencies. In the main project directory run: ``` yarn install ``` 3. Build the project ``` expo start ``` 4. Run the application on: - Android device: 1. Download Expo app - [Google Play](https://play.google.com/store/apps/details?id=host.exp.exponent&hl=pl) 2. Scan the QR code - if your computer is connected to different network than your smartphone use Tunnel connection. 3. Or Connect device via USB cable (enable USB debbuging before it) - iOS device: 1. Download Expo app - [App Store](https://apps.apple.com/pl/app/expo-client/id982107779?l=pl) 2. Login to app and send a link to your email address from expo page - Android emulator: [Expo docs](https://docs.expo.io/workflow/android-studio-emulator/) - iOS simulator: [Expo docs](https://docs.expo.io/workflow/ios-simulator/) <file_sep>import React, { useContext, useState } from "react"; import { StyleSheet } from "react-native"; import PropTypes from "prop-types"; import { Formik } from "formik"; import { PsychiatricAssessmentContext } from "../../modules/context/PsychiatricAssessmentContext"; import AppButton from "../../components/common/AppButton"; import psychiatricAssessmentValidationSchema from "../../constants/validationSchemas/psychiatricAssessmentValidationSchema"; import FormContainer from "../../components/forms/FormContainer"; import PsychiatricAssessmentForm from "../../components/forms/PsychiatricAssessmentForm"; const PsychiatricAssessment = ({ route, navigation }) => { const { psychiatricAssessmentId } = route.params; const { patientsPsychiatricAssessment, updatePsychiatricAssessment, } = useContext(PsychiatricAssessmentContext); const [isNextButtonDisabled, setNextButtonDisabled] = useState(false); const initialState = patientsPsychiatricAssessment.find( (psychiatricAssessment) => psychiatricAssessment.id === psychiatricAssessmentId ); const onButtonPressed = async (values) => { setNextButtonDisabled(true); const psychiatricAssessment = values; const result = await updatePsychiatricAssessment(psychiatricAssessment); if (result) { navigation.navigate("PatientsList"); } // TODO: Show alert with info what is wrong }; return ( <FormContainer style={styles.container}> <Formik initialValues={initialState} enableReinitialize validationSchema={psychiatricAssessmentValidationSchema} onSubmit={(values) => onButtonPressed(values)} > {({ handleChange, handleSubmit, isValid, handleBlur, isSubmitting, }) => ( <> <PsychiatricAssessmentForm handleChange={handleChange} handleBlur={handleBlur} /> <AppButton icon="next_btn" onPress={handleSubmit} disabled={!isValid || isSubmitting || isNextButtonDisabled} /> </> )} </Formik> </FormContainer> ); }; const styles = StyleSheet.create({ container: { paddingTop: 15, }, }); PsychiatricAssessment.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, }).isRequired, route: PropTypes.shape({ params: PropTypes.shape({ psychiatricAssessmentId: PropTypes.number.isRequired, }), }).isRequired, }; export default PsychiatricAssessment; <file_sep>import React, { useContext } from "react"; import PropTypes from "prop-types"; import { StyleSheet } from "react-native"; import DiagnosisForm from "../../components/diagnosisForm/DiagnosisForm"; import calculateDiseasesProbability from "../../modules/diagnosis/calculateDiseasesProbability"; import DiagnosisContainer from "./DiagnosisContainer"; import useDiagnosisForm from "../../modules/hooks/useDiagnosisForm"; import useDiagnosisConditions from "../../modules/hooks/useDiagnosisConditions"; import AppButton from "../../components/common/AppButton"; import { DiagnosisContext } from "../../modules/context/DiagnosisContext"; const MinorQuestionsForm = ({ navigation, route }) => { const { addAnswers, addModuleQuestions, modules, resetModuleDiagnosis, } = useContext(DiagnosisContext); const { moduleCode, majorAnswers } = route.params; const moduleAnswers = modules[moduleCode].minorAnswers; const isMinor = 1; const [questions, defaultAnswers] = useDiagnosisForm(moduleCode, isMinor); const answers = moduleAnswers || defaultAnswers; const [diagnosisData] = useDiagnosisConditions(moduleCode); const onSubmit = (answersValues) => { const diseasesProbability = calculateDiseasesProbability( majorAnswers, answersValues, moduleCode, diagnosisData ); addAnswers(moduleCode, answersValues, isMinor); addModuleQuestions(moduleCode, questions, isMinor); resetModuleDiagnosis(moduleCode); navigation.navigate("Results", { diseasesProbability, moduleCode }); }; return ( <DiagnosisContainer moduleCode={moduleCode}> <DiagnosisForm onSubmit={onSubmit} questions={questions} answers={answers} footerComponent={ <AppButton icon="next_btn" onPress={onSubmit} iconStyle={styles.submitButtonStyle} /> } /> </DiagnosisContainer> ); }; const styles = StyleSheet.create({ submitButtonStyle: { marginTop: 0, marginRight: 0, }, }); MinorQuestionsForm.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, goBack: PropTypes.func.isRequired, }).isRequired, route: PropTypes.shape({ params: PropTypes.shape({ moduleCode: PropTypes.string.isRequired, majorAnswers: PropTypes.arrayOf(PropTypes.number).isRequired, }).isRequired, }).isRequired, }; export default MinorQuestionsForm; <file_sep>import * as React from "react"; import { createStackNavigator } from "@react-navigation/stack"; import AddPatient from "../../../views/registration/AddPatient"; import BasicData from "../../../views/registration/BasicData"; import PhysicalExamination from "../../../views/registration/PhysicalExamination"; import PsychiatricAssessment from "../../../views/registration/PsychiatricAssessment"; import HeaderOptions from "../HeaderOptions"; import { backAction } from "../Listeners"; const Stack = createStackNavigator(); export const Routes = [ { name: "AddPatient", component: AddPatient, title: "Dane Osobowe", }, { name: "BasicData", component: BasicData, title: "Informacje podstawowe", }, { name: "PhysicalExamination", component: PhysicalExamination, title: "Badanie fizykalne", }, { name: "PsychiatricAssessment", component: PsychiatricAssessment, title: "Badanie psychiatryczne", }, ]; const initialRoute = Routes[0]; const RegistrationNavigator = () => { return ( <Stack.Navigator initialRouteName={initialRoute.name} screenOptions={HeaderOptions} > {Routes.map(({ name, component, title }) => ( <Stack.Screen name={name} key={name} component={component} options={{ title, }} listeners={({ navigation }) => backAction({ navigation, navigationRouteName: "PatientsList", message: "Czy na pewno chcesz przerwać wywiad i powrócić do listy pacjentów? Nowy pacjent nie zostanie dodany.", }) } /> ))} </Stack.Navigator> ); }; export default RegistrationNavigator; <file_sep>import React, { useEffect, useState } from "react"; import { StyleSheet, View } from "react-native"; import PropTypes from "prop-types"; import { SearchBar } from "react-native-elements"; import { Colors } from "../constants/styles"; import List from "../components/patientsList"; import FontForgeIcon from "../components/common/FontForgeIcon"; import CircleButton from "../components/common/CircleButton"; import { PatientsContext } from "../modules/context/PatientsContext"; import { BasicDataContext } from "../modules/context/BasicDataContext"; const MINIMUM_SEARCH_STRING_LENGTH = 3; const PatientsList = ({ navigation }) => { const { patients } = React.useContext(PatientsContext); const { patientsBasicData } = React.useContext(BasicDataContext); const [filteredPatients, setFilteredPatients] = useState(patients); const [search, setSearch] = useState(""); useEffect(() => { setFilteredPatients(patients); setSearch(""); }, [patients]); const onSearchChange = (searchString) => { setSearch(searchString); const searchLowerCase = searchString.toLowerCase(); let newPatients = patients; if (search.length >= MINIMUM_SEARCH_STRING_LENGTH) { newPatients = patients.filter((patient) => { const nameFilter = patient.name.toLowerCase().includes(searchLowerCase); const surnameFilter = patient.surname .toLowerCase() .includes(searchLowerCase); return nameFilter || surnameFilter; }); } setFilteredPatients(newPatients); }; const addNewPatientBtPressed = () => { navigation.navigate("Registration"); }; return ( <View style={styles.backgroundContainer}> <View style={styles.container}> <View style={styles.searchHeader}> <FontForgeIcon name="search" size={32} color={Colors.PINK} /> <SearchBar containerStyle={{ backgroundColor: "transparent", borderTopColor: "transparent", borderBottomColor: "transparent", flex: 1, }} inputContainerStyle={{ backgroundColor: "transparent", }} inputStyle={{ backgroundColor: "transparent", borderBottomColor: Colors.PURPLE, borderBottomWidth: 2, }} searchIcon={null} value={search} onChangeText={onSearchChange} placeholder="<NAME>..." clearIcon={{ size: 32, color: Colors.PINK }} /> <CircleButton icon="add" size={32} onPress={addNewPatientBtPressed} /> </View> <List navigation={navigation} patients={filteredPatients} patientsBasicData={patientsBasicData} /> </View> </View> ); }; const styles = StyleSheet.create({ backgroundContainer: { flex: 1, backgroundColor: Colors.PURPLE, justifyContent: "center", }, container: { flex: 1, backgroundColor: Colors.GRAY_VERY_LIGHT, borderTopRightRadius: 50, paddingTop: 16, justifyContent: "center", }, searchHeader: { flexDirection: "row", alignItems: "center", paddingHorizontal: 18, }, }); PatientsList.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, }).isRequired, }; export default PatientsList; <file_sep>import * as Yup from "yup"; import { DATE_REGEX, PATIENT_CODE_REGEX, PESEL_REGEX, PHONE_REGEX, } from "../values/constants"; const personalDataValidationSchema = Yup.object().shape({ name: Yup.string().required("Imię jest wymaganym polem").label("Imię"), surname: Yup.string() .required("Nazwisko jest wymaganym polem") .label("Nazwisko"), sex: Yup.string().oneOf(["male", "female"]).required().label("Płeć"), code: Yup.string() .matches(PATIENT_CODE_REGEX, "Kod musi być w formacie ICD-10") .label("Kod rozpoznania"), pesel: Yup.string() .matches(PESEL_REGEX, "Nieprawidłowy Pesel") .label("Pesel"), date_of_birth: Yup.string() .nullable() .matches( DATE_REGEX, "Nieprawidłowy format daty. Data musi być w formacie 01-01-1900" ) .required("Data urodzenia jest wymaganym polem") .label("Data urodzenia"), weight: Yup.number().integer("Waga musi być liczbą całkowitą").label("Waga"), height: Yup.number() .integer("Wzrost musi być liczbą całkowitą wyrażoną w cm") .label("Wzrost"), bmi: Yup.number().label("Bmi"), note: Yup.string().label("Notatka"), phone: Yup.string() .matches(PHONE_REGEX, "Nieprawidłowy nr telefonu") .label("Telefon"), person_guard: Yup.string().label("Osoba upoważniona"), phone_guard: Yup.string() .matches(PHONE_REGEX, "Nieprawidłowy nr telefonu") .label("Telefon do osoby upoważnionej"), guardianship: Yup.boolean(), }); export default personalDataValidationSchema; <file_sep>import React, { useContext } from "react"; import PropTypes from "prop-types"; import { FlatList, StyleSheet, View } from "react-native"; import { Colors } from "../../constants/styles"; import ModuleItem from "./Item"; import TextButton from "../common/TextButton"; import { DiagnosisContext } from "../../modules/context/DiagnosisContext"; const ModulesList = ({ onItemPress, onFinishPress }) => { const { modules } = useContext(DiagnosisContext); const moduleCodes = Object.keys(modules !== undefined ? modules : {}); return ( <FlatList data={moduleCodes} keyExtractor={(module) => module} renderItem={({ item: moduleCodeItem }) => ( <ModuleItem moduleCode={moduleCodeItem} onPress={() => onItemPress(moduleCodeItem)} /> )} ItemSeparatorComponent={({ highlighted }) => ( <View style={[styles.separator, highlighted && { marginLeft: 0 }]} /> )} ListFooterComponentStyle={styles.listFooterComponentStyle} ListFooterComponent={ <TextButton onPress={onFinishPress} text="Zakończ diagnozę" /> } /> ); }; const styles = StyleSheet.create({ separator: { height: 1, backgroundColor: Colors.PURPLE_LIGHT, width: "90%", marginLeft: 20, }, listFooterComponentStyle: { marginTop: 20 }, }); ModulesList.propTypes = { onItemPress: PropTypes.func.isRequired, onFinishPress: PropTypes.func.isRequired, }; export default ModulesList; <file_sep>import React, { useEffect } from "react"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import FormField from "./FormField"; const Weight = ({ name, leftIcon, keyboardType, placeholder, calculateDependentValue, }) => { const { setFieldValue, values } = useFormikContext(); if (calculateDependentValue != null) useEffect(() => { setFieldValue( "bmi", calculateDependentValue(values.height, values.weight) ); }, [values.height, values.weight]); return ( <> <FormField name={name} leftIcon={leftIcon} keyboardType={keyboardType} placeholder={placeholder} /> </> ); }; Weight.defaultProps = { leftIcon: null, calculateDependentValue: null, }; Weight.propTypes = { name: PropTypes.string.isRequired, leftIcon: PropTypes.string, keyboardType: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, calculateDependentValue: PropTypes.func, }; export default Weight; <file_sep>export const PSYCHIATRIC_ASSESSMENT_ACTIONS = { INSERT_OR_UPDATE: "INSERT_OR_UPDATE", REFRESH: "REFRESH", }; const psychiatricAssessmentReducer = (state, action) => { switch (action.type) { case PSYCHIATRIC_ASSESSMENT_ACTIONS.INSERT_OR_UPDATE: { const { psychiatricAssessment: setPsychiatricAssessment, } = action.payload; const { patientsPsychiatricAssessment } = state; const psychiatricAssessmentIndex = state.patientsPsychiatricAssessment.findIndex( (psychiatricAssessment) => { return psychiatricAssessment.id === setPsychiatricAssessment.id; } ); if (psychiatricAssessmentIndex !== -1) { patientsPsychiatricAssessment[ psychiatricAssessmentIndex ] = setPsychiatricAssessment; } else { patientsPsychiatricAssessment.push(setPsychiatricAssessment); } return { ...state, patientsPsychiatricAssessment, }; } case PSYCHIATRIC_ASSESSMENT_ACTIONS.REFRESH: { const { psychiatricAssessment } = action.payload; return { ...state, psychiatricAssessment, }; } default: return state; } }; export default psychiatricAssessmentReducer; <file_sep>const patientsData = [ { id: 123456798, name: "Robert", surname: "Lewandowski", sex: "male", pesel: "", date_of_birth: "", weight: 77, height: 182, bmi: 4, note: "", phone: "2342342342", person_guard: "", phone_guard: "", }, { id: 2, name: "Krzysiu", surname: "Krawczyk", sex: "male", pesel: "", date_of_birth: "", weight: 107, height: 176, bmi: 4, note: "", phone: "2342342342", person_guard: "", phone_guard: "", }, { id: 3, name: "Robert", surname: "Burneika", sex: "male", pesel: "", date_of_birth: "", weight: 122, height: 183, bmi: 2, note: "", phone: "2342342342", person_guard: "", phone_guard: "", }, { id: 4, name: "Andrzej", surname: "Duda", sex: "male", pesel: "", date_of_birth: "", weight: 86, height: 177, bmi: 4, note: "", phone: "2342342342", person_guard: "", phone_guard: "", }, { id: 5, name: "Gosia", surname: "Andrzejewicz", sex: "female", pesel: "", date_of_birth: "", weight: 77, height: 182, bmi: 4, note: "", phone: "2342342342", person_guard: "", phone_guard: "", }, { id: 123456789, name: "Tomasz", surname: "Tabaluga", sex: "male", pesel: "90113000000", date_of_birth: "30-11-1990", weight: 77, height: 182, bmi: 4, note: "Pacjent zgłosił się na SOR. Został już przewieziony do szpitala uniwersyteckiego. Pacjent zgłosił się na SOR. Został już przewieziony do szpitala uniwersyteckiego. Pacjent zgłosił się na SOR. Został już przewieziony do szpitala uniwersyteckiego. ", phone: "111222333", person_guard: "<NAME>", phone_guard: "999888777", }, ]; export default patientsData; <file_sep>import dateFormat from "dateformat"; export const calculateDateOfBirthValue = (pesel) => { const peselArray = Array.from(pesel).map(Number); if (peselArray.length === 11) { let year = 1900 + peselArray[0] * 10 + peselArray[1]; if (peselArray[2] >= 2 && peselArray[2] < 8) year += Math.floor(peselArray[2] / 2) * 100; if (peselArray[2] >= 8) year -= 100; const month = (peselArray[2] % 2) * 10 + peselArray[3]; const day = peselArray[4] * 10 + peselArray[5]; const dateOfBirth = new Date(year, month - 1, day); return dateFormat(dateOfBirth, "dd - mm - yyyy"); } return ""; }; export const calculateBmiValue = (height, weight) => { if (height && weight > 10) { const heightInMeters = height / 100; const bmi = weight / (heightInMeters * heightInMeters); return `${parseFloat(bmi, 10).toFixed(2)}`; } return "0"; }; export const calculateAge = (dateOfBirth) => { if (dateOfBirth) { const from = dateOfBirth.split(/-| - /); const birthdateTimeStamp = new Date(from[2], from[1] - 1, from[0]); const ageDate = Date.now() - birthdateTimeStamp; // This is the difference in milliseconds return Math.floor(ageDate / 31557600000); // Divide to get difference in years } return ""; }; <file_sep>import React, { useState, useEffect } from "react"; import { View, Text, StyleSheet, TouchableOpacity } from "react-native"; import { useFormikContext } from "formik"; import PropTypes from "prop-types"; import FormError from "./FormError"; import { Colors, Typography } from "../../../constants/styles"; import FontForgeIcon from "../../common/FontForgeIcon"; const MultiChoice = ({ name, options }) => { const { setFieldValue, errors, touched } = useFormikContext(); const [optionsChecked, setOptionsChecked] = useState([]); const fieldValue = optionsChecked.join(";"); useEffect(() => { setFieldValue(name, fieldValue); }, [fieldValue]); return ( <> <View style={styles.container}> {options.map((option) => { return ( <View key={option} style={styles.choice}> {optionsChecked.includes(option) ? ( <TouchableOpacity onPress={() => { setOptionsChecked( optionsChecked.filter((e) => e !== option) ); }} > <FontForgeIcon name="checked" size={38} color={Colors.PINK_MEDIUM} style={styles.icon} /> </TouchableOpacity> ) : ( <TouchableOpacity onPress={() => { setOptionsChecked([...optionsChecked, option]); }} > <FontForgeIcon name="unchecked" size={38} color={Colors.PINK_MEDIUM} style={styles.icon} /> </TouchableOpacity> )} <Text style={styles.text}>{option}</Text> </View> ); })} </View> <FormError error={errors[name]} visible={touched[name]} /> </> ); }; const styles = StyleSheet.create({ container: { backgroundColor: Colors.GRAY_VERY_LIGHT, flex: 1, flexDirection: "column", alignItems: "flex-start", justifyContent: "flex-start", alignSelf: "flex-start", marginTop: 12, marginLeft: 60, }, choice: { flex: 1, flexDirection: "row", }, icon: { flex: 1, alignSelf: "center", marginRight: 10, }, text: { flex: 1, fontSize: Typography.FONT_SIZE_13, fontFamily: Typography.FONT_FAMILY_REGULAR, color: Colors.BLACK, alignSelf: "center", }, }); MultiChoice.propTypes = { name: PropTypes.string.isRequired, options: PropTypes.arrayOf(PropTypes.string).isRequired, }; export default MultiChoice; <file_sep>import React, { createContext, useEffect, useReducer } from "react"; import PropTypes from "prop-types"; import psychiatricAssessmentReducer, { PSYCHIATRIC_ASSESSMENT_ACTIONS, } from "./PsychiatricAssessmentReducer"; import patientsPsychiatricAssessment from "../../constants/data/patientsPsychiatricAssessment"; import { database, TABLES } from "../database/database"; export const PsychiatricAssessmentContext = createContext({ patientsPsychiatricAssessment: [], }); const initialState = { patientsPsychiatricAssessment }; function PsychiatricAssessmentProvider({ children }) { const [state, dispatch] = useReducer( psychiatricAssessmentReducer, initialState ); useEffect(() => { const refreshPsychiatricAssessment = async () => { const psychiatricAssessment = await database.getAllFromTable( TABLES.psychiatric_assessment ); dispatch({ type: PSYCHIATRIC_ASSESSMENT_ACTIONS.REFRESH, payload: { psychiatricAssessment }, }); }; refreshPsychiatricAssessment(); }, []); const setPsychiatricAssessment = async (psychiatricAssessment) => { const id = await database.insertObjectToTable( psychiatricAssessment, TABLES.psychiatric_assessment ); if (id) { const assessmentWithId = psychiatricAssessment; assessmentWithId.id = id; dispatch({ type: PSYCHIATRIC_ASSESSMENT_ACTIONS.INSERT_OR_UPDATE, payload: { psychiatricAssessment: assessmentWithId }, }); } return id; }; const updatePsychiatricAssessment = async (psychiatricAssessment) => { const result = await database.updateObjectFromTable( psychiatricAssessment, TABLES.psychiatric_assessment ); if (result) { dispatch({ type: PSYCHIATRIC_ASSESSMENT_ACTIONS.INSERT_OR_UPDATE, payload: { psychiatricAssessment }, }); } return result; }; const value = { ...state, setPsychiatricAssessment, updatePsychiatricAssessment, }; return ( <PsychiatricAssessmentContext.Provider value={value}> {children} </PsychiatricAssessmentContext.Provider> ); } PsychiatricAssessmentProvider.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, }; export default PsychiatricAssessmentProvider; <file_sep>import React, { useContext, useState } from "react"; import PropTypes from "prop-types"; import { Formik } from "formik"; import personalDataValidationSchema from "../../constants/validationSchemas/personalDataValidationSchema"; import { PatientsContext } from "../../modules/context/PatientsContext"; import AddPatientForm from "../../components/forms/AddPatientForm"; import AppButton from "../../components/common/AppButton"; import FormContainer from "../../components/forms/FormContainer"; import { parseFormFieldValuesToObject } from "../../modules/utils/Parsers"; import { initialBasicData, initialPatient, initialPhysicalExamination, initialPsychiatricAssessment, } from "../../constants/values/initalFormValues"; import { BasicDataContext } from "../../modules/context/BasicDataContext"; import { PsychiatricAssessmentContext } from "../../modules/context/PsychiatricAssessmentContext"; import { PhysicalExaminationContext } from "../../modules/context/PhysicalExaminationContext"; const AddPatient = ({ navigation }) => { const { addPatient } = useContext(PatientsContext); const { setBasicData } = useContext(BasicDataContext); const { setPsychiatricAssessment } = useContext(PsychiatricAssessmentContext); const { setPhysicalExamination } = useContext(PhysicalExaminationContext); const [isNextButtonDisabled, setNextButtonDisabled] = useState(false); const initialState = initialPatient; const keysWithParserFunctions = { weight: (val) => parseInt(val, 10), height: (val) => parseInt(val, 10), bmi: (val) => parseFloat(Math.round(val * 100) / 100), }; const onButtonPressed = async (values) => { setNextButtonDisabled(true); const patient = parseFormFieldValuesToObject( values, keysWithParserFunctions ); patient.id = await addPatient(patient); if (patient.id) { const basicData = initialBasicData; basicData.patient_id = patient.id; basicData.id = await setBasicData(basicData); const physicalExamination = initialPhysicalExamination; physicalExamination.patient_id = patient.id; physicalExamination.id = await setPhysicalExamination( physicalExamination ); const psychiatricAssessment = initialPsychiatricAssessment; psychiatricAssessment.patient_id = patient.id; psychiatricAssessment.id = await setPsychiatricAssessment( psychiatricAssessment ); if (basicData.id && physicalExamination.id && psychiatricAssessment.id) { navigation.navigate("BasicData", { basicDataId: basicData.id, physicalExaminationId: physicalExamination.id, psychiatricAssessmentId: psychiatricAssessment.id, }); } } }; return ( <FormContainer title="<NAME>"> <Formik initialValues={initialState} enableReinitialize validationSchema={personalDataValidationSchema} onSubmit={(values) => onButtonPressed(values)} > {({ handleChange, values, handleSubmit, isValid = true, handleBlur, isSubmitting, }) => ( <> <AddPatientForm handleBlur={handleBlur} handleChange={handleChange} values={values} /> <AppButton icon="next_btn" onPress={handleSubmit} disabled={!isValid || isSubmitting || isNextButtonDisabled} /> </> )} </Formik> </FormContainer> ); }; AddPatient.propTypes = { navigation: PropTypes.shape({ navigate: PropTypes.func.isRequired, }).isRequired, }; export default AddPatient;
a057a95bea413b00f4ac806118ee5f47ede36816
[ "JavaScript", "Python", "Markdown" ]
68
JavaScript
aI-lab-glider/doctors-assistant-app
1336910adef8272c572a2273e32dee4ad49dac2e
8901aefdc78a8deb5db1d10e6d81787f8e9c2c69
refs/heads/master
<repo_name>ScottMorris/sampleBusinessNetwork<file_sep>/README.md # Scott's hyperledger composer network for Product management<file_sep>/lib/product.js /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @param {org.example.transaction.ProductNote} tx The product note transaction * @transaction */ function addProductNote(tx) { var pid = getCurrentParticipant().getIdentifier(); var product = tx.Product; addNote(product, tx.Note, pid); return updateProduct(product) .then(function () { return emitAssetEvent('ProductNotesEvent'); }) } /** * @param {org.example.transaction.ProductCreation} tx The new product def * @transaction */ function createProduct(tx) { return getAssetRegistry('org.example.asset.Product') .then(function (productRegistry) { var factory = getFactory(); var product = factory.newResource('org.example.asset', 'Product', tx.Name) //product.Id = tx.Name; product.ProductManager = tx.ProductManager; product.Name = tx.Name; product.Description = tx.Description; product.CreatedDate = tx.CreatedDate; product.ExpiryDate = tx.ExpiryDate; return productRegistry.add(product); }) .then(function () { return emitAssetEvent('ProductCreationEvent'); }) } /** * @param {org.example.transaction.ProductAssignment} tx The product definition * @transaction */ function assignPeopleToProduct(tx) { var product = tx.Product; if (tx.ProductManager) product.ProductManager = tx.ProductManager; if (tx.MarketingManager) product.MarketingManager = tx.MarketingManager; if(tx.ShippingManager) product.ShippingManager = tx.ShippingManager; return updateProduct(product); } /** * @param {org.example.transaction.ProductDefinition} tx The product definition * @transaction */ function updateProductDefinition(tx) { var product = tx.Product; product.Name = tx.Name; product.Description = tx.Description; product.CreatedDate = tx.CreatedDate; product.ExpiryDate = tx.ExpiryDate; product.Sku = tx.Sku; return updateProduct(product); } /** * @param {org.example.transaction.ProductPricing} tx The product pricing info * @transaction */ function updateProductPricing(tx) { var pid = getCurrentParticipant().getIdentifier(); var product = tx.Product; product.UnitPrice = tx.UnitPrice; addNote(product, tx.Reason, pid); return updateProduct(product) .then(function (){ return emitAssetEvent('ProductPricingEvent'); }); } /** * @param {org.example.transaction.ProductApproval} tx The product approval info * @transaction */ function updateProductApproval(tx) { var pid = getCurrentParticipant().getIdentifier(); var product = tx.Product; if (product.ProductManager && pid == product.ProductManager.getIdentifier()) product.ProductManagerApproved = tx.IsApproved; else throw Error("There is no logic to record your approval"); addNote(product, tx.Reason, pid); product.AvailableForSale = product.ProductManagerApproved; if (product.AvailableForSale) emitAssetEvent('ProductAvailableForSaleEvent'); return updateProduct(product) .then(function (){ return emitAssetEvent('ProductApprovalEvent'); }); } /** * @param {org.example.transaction.ProductMarketing} tx The product marketing info * @transaction */ function updateProductMarketing(tx) { var product = tx.Product; product.MarketingMaterial = tx.MarketingMaterial; product.Tags = tx.Tags; return updateProduct(product); } /** * @param {org.example.transaction.ProductShipment} tx The product shipment info * @transaction */ function updateProductShipment(tx) { var product = tx.Product; product.DestinationAddress = tx.DestinationAddress; product.DeliveryInstructions = tx.DeliveryInstructions; return updateProduct(product); } ////////////////////// Helper functions //////////////////////// function addNote(product, note, author) { if (note) { var factory = getFactory(); var n = factory.newConcept('org.example.asset', 'Note'); n.EffectiveDate = new Date(); n.Message = note; n.Author = author; if (!product.Notes) product.Notes = []; product.Notes.push(n); } } function updateProduct(product) { // Get the asset registry for the asset. return getAssetRegistry('org.example.asset.Product') .then(function (assetRegistry) { // Update the asset in the asset registry. return assetRegistry.update(product); }); } function emitAssetEvent(eventName) { var factory = getFactory(); var ev = factory.newEvent('org.example.asset', eventName); return emit(ev); }
8e9db1fba3a6cc7c4d1c1b15f79adb65fe44ac48
[ "Markdown", "JavaScript" ]
2
Markdown
ScottMorris/sampleBusinessNetwork
af40ae395c28977e4e1cb8fbb5b6dc3a173350ae
47ef4d38fd29ed122c5f77622d2077f9a2e984a2
refs/heads/main
<file_sep>function Converter() { var valorElemento = document.getElementById("valor"); var valor = valorElemento.value; var valorEmDolarNumerico = parseFloat(valor); var valorDolarHoje = 5.23; console.log(valorEmDolarNumerico / valorDolarHoje); }
cacfafa9894f670d28e40b8183efb793cc20b35e
[ "JavaScript" ]
1
JavaScript
EngCaioMonteiro/Conversor-de-moedas
64b433b9f286ad0f3927c808e83a15ccdc6829f5
f9173c023675246404c212f052b55c4fa33a6888
refs/heads/master
<file_sep>#include <SPI.h> #include <Ethernet.h> #include <ArdOSC.h> byte myMac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte myIp[] = { 192, 168, 132, 177 }; int destPort=12000; byte destIp[] = { 192, 168, 132, 145 }; OSCClient client; //create new osc message OSCMessage global_mes; int v3=10; float v4=10.0; char str1[]="simple send 1!"; int v1=0; float v2=0.0; //Analog pin 1 for reading in the analog voltage from the MaxSonar device. int anPin = 0; //variables needed to store values int arraysize = 5; //quantity of values to find the median (sample size). Needs to be an odd number int rangevalue[] = {0, 0, 0, 0, 0}; //declare an array to store the samples. not necessary to zero the array values here, it just makes the code clearer int midpoint = arraysize/2; //midpoint of the array is the medain value in a sorted array void setup(){ Ethernet.begin(myMac ,myIp); //This opens up a serial connection to shoot the results back to the PC console Serial.begin(9600); printArray(rangevalue, arraysize); delay(5000); //wait a while to open serial monitor window } void loop(){ pinMode(anPin, INPUT); //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information. //Maxbotix does not recommend averaging readings as the occasional value can be wildly inaccurate and skew the average //A median sort is the preferred method. for(int i = 0; i < arraysize; i++) { //array pointers go from 0 to 4 //Used to read in the analog voltage output that is being sent by the MaxSonar device. //The MaxSonar Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in //The Arduino will map input voltages between 0 and 5 volts into integer values between 0 and 1023. //This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. //Therefore, one unit from the arduino's ADC represents 0.5 inches rangevalue[i] = analogRead(anPin); Serial.print("i, value "); Serial.print(i); Serial.print(" , "); Serial.print(rangevalue[i]); Serial.println(); delay(10); //wait between analog samples } Serial.print("unsorted "); printArray(rangevalue, arraysize); Serial.println(); isort(rangevalue, arraysize); Serial.print("sorted "); printArray(rangevalue, arraysize); Serial.println(); // now show the medaian range int midpoint = arraysize/2; //midpoint of the array is the medain value in a sorted array //note that for an array of 5, the midpoint is element 2, as the first element is element 0 Serial.print("median range value "); Serial.print(rangevalue[midpoint]); Serial.println(); Serial.println(); delay(1 00); //wait a while so you can read the values on the serial monitor global_mes.setAddress(destIp,destPort); global_mes.beginMessage("/ard/send1"); global_mes.addArgInt32(rangevalue[midpoint]); global_mes.addArgFloat(v2); global_mes.addArgString(str1); client.send(&global_mes); global_mes.flush(); //object data clear } void send2(){ //loacal_mes,str is release by out of scope OSCMessage loacal_mes; loacal_mes.setAddress(destIp,destPort); loacal_mes.beginMessage("/ard/send2"); loacal_mes.addArgInt32(v3); loacal_mes.addArgFloat(v4); char str[]="simple send2 !!"; loacal_mes.addArgString(str); client.send(&loacal_mes); v3++; v4 += 0.1; } //********************************************************************************* // sort function void isort(int *a, int n) // *a is an array pointer function { for (int i = 1; i < n; ++i) { int j = a[i]; int k; for (k = i - 1; (k >= 0) && (j < a[k]); k--) { a[k + 1] = a[k]; } a[k + 1] = j; } } //*********************************************************************************** //function to print array values void printArray(int *a, int n) { for (int i = 0; i < n; i++) { Serial.print(a[i], DEC); Serial.print(' '); } Serial.println(); } <file_sep>//Use of many MaxSonar with Daisy Chaining with Constantly Looping in analog mode with arduino // http://www.maxbotix.com/documents/LV_Chaining_Constantly_Looping_AN_Out.pdf const int sensorCount = 4; int rangePin[] = {0, 1, 2, 3}; const int rxPin = 8; const int preReadDelayUs = 50; const int toggleDelayUs = 30; boolean bwPinState = HIGH; int bwPin[] = {3, 4, 7}; int bwCount = 3; //variables needed to store values const int arraysize = 10; //quantity of values to find the median (sample size). Needs to be an odd number const int midpoint = arraysize/2; //midpoint of the array is the medain value in a sorted array int rangevalue[sensorCount][arraysize]; //declare an array to store the samples. not necessary to zero the array values here, it just makes the code clearer //********************************************************************************************* void setup() { for (int i = 0; i < bwCount; i++ ) { pinMode(bwPin[i], OUTPUT); digitalWrite(bwPin[i], bwPinState); } //This opens up a serial connection to shoot the results back to the PC console Serial.begin(9600); // init readings buffer for ( int sensor = 0; sensor < sensorCount; sensor++) { printArray(rangevalue[sensor], arraysize); for (int reading = 0; reading < arraysize; reading++ ) { rangevalue[sensor][reading] = 0; } } toggleRx(); delay(3000); //wait a while to open serial monitor window } //******************************************************************************** void loop() { //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information. //Maxbotix does not recommend averaging readings as the occasional value can be wildly inaccurate and skew the average //A median sort is the preferred method. for(int i = 0; i < arraysize; i++) { //toggleRx(); // delay(50); //wait between analog samples for ( int sensor = 0; sensor < sensorCount; sensor++) { rangevalue[sensor][i] = analogRead(rangePin[sensor]); } } for ( int sensor = 0; sensor < sensorCount; sensor++) { isort(rangevalue[sensor], arraysize); if(0 != sensor) Serial.print(","); Serial.print(rangevalue[sensor][midpoint]); } Serial.println(); delay(40); //wait a while so you can read the values on the serial monitor return; } //end of loop() //********************************************************************************* // sort function void isort(int *a, int n) // *a is an array pointer function { for (int i = 1; i < n; ++i) { int j = a[i]; int k; for (k = i - 1; (k >= 0) && (j < a[k]); k--) { a[k + 1] = a[k]; } a[k + 1] = j; } } //*********************************************************************************** //function to print array values void printArray(int *a, int n) { for (int i = 0; i < n; i++) { Serial.print(a[i], DEC); Serial.print(' '); } Serial.println(); } void toggleRx() { digitalWrite(rxPin, HIGH); delayMicroseconds(toggleDelayUs); pinMode(rxPin, INPUT); return; } <file_sep>#include <SPI.h> #include <Ethernet.h> #include <ArdOSC.h> byte myMac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte myIp[] = { 192, 168, 132, 177 }; int serverPort = 10000; int destPort=12000; char oscadr[]="/ard/aaa"; OSCServer server; OSCClient client; int anPin = 0; //variables needed to store values int arraysize = 5; //quantity of values to find the median (sample size). Needs to be an odd number int rangevalue[] = {0, 0, 0, 0, 0}; //declare an array to store the samples. not necessary to zero the array values here, it just makes the code clearer int midpoint = arraysize/2; void setup(){ Serial.begin(9600); Ethernet.begin(myMac ,myIp); server.begin(serverPort); //set callback function server.addCallback(oscadr,&func1); printArray(rangevalue, arraysize); delay(5000); //wait a while to open serial monitor window } void loop(){ pinMode(anPin, INPUT); //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information. //Maxbotix does not recommend averaging readings as the occasional value can be wildly inaccurate and skew the average //A median sort is the preferred method. for(int i = 0; i < arraysize; i++) { //array pointers go from 0 to 4 //Used to read in the analog voltage output that is being sent by the MaxSonar device. //The MaxSonar Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in //The Arduino will map input voltages between 0 and 5 volts into integer values between 0 and 1023. //This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. //Therefore, one unit from the arduino's ADC represents 0.5 inches rangevalue[i] = analogRead(anPin); /* Serial.print("i, value "); Serial.print(i); Serial.print(" , "); Serial.print(rangevalue[i]); Serial.println(); */ delay(10); //wait between analog samples } /* Serial.print("unsorted "); printArray(rangevalue, arraysize); Serial.println(); */ isort(rangevalue, arraysize); /* Serial.print("sorted "); printArray(rangevalue, arraysize); Serial.println(); */ // now show the medaian range // int midpoint = arraysize/2; //midpoint of the array is the medain value in a sorted array //note that for an array of 5, the midpoint is element 2, as the first element is element 0 Serial.print("median range value "); Serial.print(rangevalue[midpoint]); Serial.println(); Serial.println(); if(server.aviableCheck()>0){ Serial.println("alive! "); } } void func1(OSCMessage *_mes){ logIp(_mes); logOscAddress(_mes); //get source ip address byte *sourceIp = _mes->getIpAddress(); //get 1st argument(int32) int tmpI=_mes->getArgInt32(0); //get 2nd argument(float) float tmpF=_mes->getArgFloat(1); //get 3rd argument(string) int strSize=_mes->getArgStringSize(2); char tmpStr[strSize]; //string memory allocation _mes->getArgString(2,tmpStr); //create new osc message OSCMessage newMes; //set destination ip address & port no newMes.setAddress(sourceIp,destPort); //set argument newMes.beginMessage(oscadr); newMes.addArgInt32(rangevalue[midpoint]); newMes.addArgFloat(tmpF+0.1); newMes.addArgString(tmpStr); //send osc message client.send(&newMes); } void logIp(OSCMessage *_mes){ byte *ip = _mes->getIpAddress(); Serial.print("IP:"); Serial.print(ip[0],DEC); Serial.print("."); Serial.print(ip[1],DEC); Serial.print("."); Serial.print(ip[2],DEC); Serial.print("."); Serial.print(ip[3],DEC); Serial.print(" "); } void logOscAddress(OSCMessage *_mes){ Serial.println(_mes->getOSCAddress()); } //********************************************************************************* // sort function void isort(int *a, int n) // *a is an array pointer function { for (int i = 1; i < n; ++i) { int j = a[i]; int k; for (k = i - 1; (k >= 0) && (j < a[k]); k--) { a[k + 1] = a[k]; } a[k + 1] = j; } } //*********************************************************************************** //function to print array values void printArray(int *a, int n) { for (int i = 0; i < n; i++) { Serial.print(a[i], DEC); Serial.print(' '); } Serial.println(); } <file_sep>// <NAME> // and // vsquaredlabs all rights reserved (c) 2012 // ////// // // intent: detect people and population of a space // impl: this arduino interfaces with 4 sonar sensors // and transfer the data over a network using OSC // // OSC libraries part of arduino base #include <SPI.h> #include <Ethernet.h> // OSC lib from https://github.com/recotana/ArdOSC #include <ArdOSC.h> // network setup byte myMac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; byte myIp[] = { 192, 168, 132, 177 }; // not sure these are strictly required ??? int destPort=12000; byte destIp[] = { 192, 168, 132, 145 }; OSCClient client; //Use of many Simultaneous MaxSonar sonar modules in analog mode with arduino const int sensorCount = 4; int rangePin[] = {0, 1, 2, 3}; const int rxPin = 6; const int preReadDelayUs = 50; const int toggleDelayUs = 30; boolean bwPinState = HIGH; int bwPin[] = {3, 4, 7}; int bwCount = 3; //variables needed to store values const int arraysize = 10; //quantity of values to find the median (sample size). Needs to be an odd number const int midpoint = arraysize/2; //midpoint of the array is the medain value in a sorted array int rangevalue[sensorCount][arraysize]; void setup(){ Ethernet.begin(myMac ,myIp); for (int i = 0; i < bwCount; i++ ) { pinMode(bwPin[i], OUTPUT); digitalWrite(bwPin[i], bwPinState); } //This opens up a serial connection to shoot the results back to the PC console Serial.begin(9600); // init readings buffer for ( int sensor = 0; sensor < sensorCount; sensor++) { printArray(rangevalue[sensor], arraysize); for (int reading = 0; reading < arraysize; reading++ ) { rangevalue[sensor][reading] = 0; } } delay(3000); //wait a while to open serial monitor window } void loop(){ //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information. //Maxbotix does not recommend averaging readings as the occasional value can be wildly inaccurate and skew the average //A median sort is the preferred method. for ( int sensor = 0; sensor < sensorCount; sensor++) { for(int i = 0; i < arraysize; i++) { toggleRx(); // delay(50); //wait between analog samples rangevalue[sensor][i] = analogRead(rangePin[sensor]); /* Serial.print("i, value "); Serial.print(i); Serial.print(" , "); Serial.print(rangevalue[i]); Serial.println(); */ } // Serial.print("unsorted "); // printArray(rangevalue[sensor], arraysize); // Serial.println(); isort(rangevalue[sensor], arraysize); // Serial.print("sorted "); // printArray(rangevalue[sensor], arraysize); // Serial.println(); /* Serial.print("median range value "); Serial.print(rangevalue[sensor][midpoint]); Serial.println(); Serial.println(); */ } // end of sensor loop send(0,rangevalue[0][midpoint]); return; } //********************************************************************************* // crafts and sends the OSC payload void send(int sensor, int reading){ //loacal_mes,str is release by out of scope OSCMessage loacal_mes; loacal_mes.setAddress(destIp,destPort); loacal_mes.beginMessage("/sonar/send" + sensor); loacal_mes.addArgInt32(reading); client.send(&loacal_mes); } //********************************************************************************* // sort function void isort(int *a, int n) // *a is an array pointer function { for (int i = 1; i < n; ++i) { int j = a[i]; int k; for (k = i - 1; (k >= 0) && (j < a[k]); k--) { a[k + 1] = a[k]; } a[k + 1] = j; } return; } //*********************************************************************************** //function to print array values void printArray(int *a, int n) { for (int i = 0; i < n; i++) { Serial.print(a[i], DEC); Serial.print(' '); } Serial.println(); return; } //*********************************************************************************** //toggles sonar rx pins trigger next reading void toggleRx() { digitalWrite(rxPin, HIGH); delayMicroseconds(toggleDelayUs); digitalWrite(rxPin, LOW); // delayMicroseconds(preReadDelayUs); return; } <file_sep>//Use of MaxSonar EZ1 sonar module in analog mode with arduino // median filter of five consecutive readings to eliminate spikes // // <NAME>, Nov. 12, 2010 //borrowing an idea from the Arduino Forum on array sort //http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1283456170/12 //the "insert sort" code is from whistler // //take 5 readings and store them in an array rangevalue[] //using an "ascending insert sort" rearrange the array values in ascending order //choose the middle element in the array, which will by definition be the median of the set of values // //Analog pin 1 for reading in the analog voltage from the MaxSonar device. int anPin = 0; //variables needed to store values int arraysize = 5; //quantity of values to find the median (sample size). Needs to be an odd number int rangevalue[] = {0, 0, 0, 0, 0}; //declare an array to store the samples. not necessary to zero the array values here, it just makes the code clearer //********************************************************************************************* void setup() { //This opens up a serial connection to shoot the results back to the PC console Serial.begin(9600); printArray(rangevalue, arraysize); delay(5000); //wait a while to open serial monitor window } //******************************************************************************** void loop() { pinMode(anPin, INPUT); //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information. //Maxbotix does not recommend averaging readings as the occasional value can be wildly inaccurate and skew the average //A median sort is the preferred method. for(int i = 0; i < arraysize; i++) { //array pointers go from 0 to 4 //Used to read in the analog voltage output that is being sent by the MaxSonar device. //The MaxSonar Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in //The Arduino will map input voltages between 0 and 5 volts into integer values between 0 and 1023. //This yields a resolution between readings of: 5 volts / 1024 units or, .0049 volts (4.9 mV) per unit. //Therefore, one unit from the arduino's ADC represents 0.5 inches rangevalue[i] = analogRead(anPin); Serial.print("i, value "); Serial.print(i); Serial.print(" , "); Serial.print(rangevalue[i]); Serial.println(); delay(10); //wait between analog samples } Serial.print("unsorted "); printArray(rangevalue, arraysize); Serial.println(); isort(rangevalue, arraysize); Serial.print("sorted "); printArray(rangevalue, arraysize); Serial.println(); // now show the medaian range int midpoint = arraysize/2; //midpoint of the array is the medain value in a sorted array //note that for an array of 5, the midpoint is element 2, as the first element is element 0 Serial.print("median range value "); Serial.print(rangevalue[midpoint]); Serial.println(); Serial.println(); delay(3000); //wait a while so you can read the values on the serial monitor } //end of loop //********************************************************************************* // sort function void isort(int *a, int n) // *a is an array pointer function { for (int i = 1; i < n; ++i) { int j = a[i]; int k; for (k = i - 1; (k >= 0) && (j < a[k]); k--) { a[k + 1] = a[k]; } a[k + 1] = j; } } //*********************************************************************************** //function to print array values void printArray(int *a, int n) { for (int i = 0; i < n; i++) { Serial.print(a[i], DEC); Serial.print(' '); } Serial.println(); }
07a0f5230ffef283a5155babc9305d2c81fbf7a8
[ "C++" ]
5
C++
mpinner/v2
f4d1ad8c9d2c021ec45ecabde579c8152007d732
9adc2091306435cf4e492589ed48485b900216bd
refs/heads/master
<repo_name>kenisbeauty/Umbee<file_sep>/config/routes.rb Rails.application.routes.draw do devise_for :users resources :listings root :to => 'static_pages#home' get '/listings', to: 'listings#index' get '/help', to: 'static_pages#help' get '/about', to: 'static_pages#about' get '/contact', to: 'static_pages#contact' get '/host', to: 'static_pages#host' get '/listings/new', to: 'listings#new' # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end <file_sep>/app/helpers/listings_helper.rb module ListingsHelper def get_home_types return ["apartment", "house", "villa", "dorm"] end def get_room_types return ["entire home", "private room", "shared room"] end def get_maximum_guests return ["for 1 guest", "for 2 guest", "for 3 guest", "for 4 guest" ,"for 5 guest", "for 6 guest", "for 7 guest"] end def get_amenities return ["select","pool", "internet", "smoke detector", "kitchen", "heating", "Iron", "Wifi"] end end<file_sep>/db/migrate/20170418092650_create_listings.rb class CreateListings < ActiveRecord::Migration[5.0] def change create_table :listings do |t| t.string :name t.string :address t.integer :price t.date :availability_from, :null=>false t.date :availability_to, :null=>false t.string :home_type, :null=>false, :default=>'house' t.string :room_type, :null=>false, :default=>'entire home' t.string :description t.string :amenites t.string :maximum_guest, :null=>false, :default=>1 t.timestamps end end end <file_sep>/test/controllers/listings_controller_test.rb require 'test_helper' class ListingsControllerTest < ActionDispatch::IntegrationTest setup do @listing = listings(:one) end test "should get index" do get listings_url assert_response :success end test "should get new" do get new_listing_url assert_response :success end test "should create listing" do assert_difference('Listing.count') do post listings_url, params: { listing: { address: '3, elfinstone road, aberdeen', amenites: 'iron', availability_from: '2017-04-20', availability_to:'2017-04-04', description:'the home is beautiful', home_type:'entire home', maximum_guest: '2 guest', name:'ocean wave', price: '$40', room_type:'apartment' , image: 'default.jpg' } } end assert_redirected_to listing_url(Listing.last) end test "should show listing" do get listing_url(@listing) assert_response :success end test "should get edit" do get edit_listing_url(@listing) assert_response :success end test "should update listing" do patch listing_url(@listing), params: { listing: { address: '3, elfinstone road, aberdeen', amenites: 'iron', availability_from: '2017-04-20', availability_to:'2017-04-04', description:'the home is beautiful', home_type:'entire home', maximum_guest: '2 guest', name:'ocean wave', price: '$40', room_type:'apartment' , image: 'default.jpg' } } assert_redirected_to listing_url(@listing) end test "should destroy listing" do assert_difference('Listing.count', -1) do delete listing_url(@listing) end assert_redirected_to listings_url end end <file_sep>/app/models/listing.rb class Listing < ApplicationRecord mount_uploader :image, ImageUploader validates :name, :address, :description, :availability_from, :home_type, :room_type, :maximum_guest, :availability_to, :amenites, presence: true validates :price, numericality: { greater_than: 0} private # Validates the size of an uploaded picture. def image_size if image.size > 5.megabytes errors.add(:image, "should be less than 5MB") end end end
b4deef19a9bb2f453bf749954ecdef59eb12ea4c
[ "Ruby" ]
5
Ruby
kenisbeauty/Umbee
3bc1c90269045f59b37251facf62033e7624004e
a321d0c6af121242b3171fde724a10fb38919619
refs/heads/master
<file_sep>// // AROError.swift // // Created by <NAME> // Copyright (c) 2016 <NAME>. All rights reserved. // Released under the MIT license. // import Alamofire import ObjectMapper public enum AROError: Error { case requestFailed(response: DataResponse<String>) case parseSuccessResponseFailed(response: DataResponse<String>) } <file_sep>// // ApiRequestable.swift // // Created by <NAME> // Copyright (c) 2016 <NAME>. All rights reserved. // Released under the MIT license. // import Foundation import Alamofire import RxSwift import ObjectMapper public protocol RequestStatusObservable { var requestStatus: BehaviorSubject<RequestState> { get } } public protocol RequestableDelegate { func requestable(_ requestable:ApiRequestable, didSendRequest request: DataRequest) func requestable(_ requestable:ApiRequestable, didUploadRequest request: UploadRequest) func requestable(_ requestable:ApiRequestable, didReceiveResponse response: DataResponse<String>) } public protocol ApiRequestable { func request<ResponseParser: ResponseParserProtocol>( sessionManager: SessionManager, url: URLConvertible, method: HTTPMethod, parameters: Parameters?, parameterEncoding: ParameterEncoding, headers: HTTPHeaders?, responseParser: ResponseParser, delegate: RequestableDelegate?) -> Observable<ResponseParser.SuccessResponse> func uploadRequest<ResponseParser: ResponseParserProtocol>( sessionManager: SessionManager, multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold: UInt64, to: URLConvertible, method: HTTPMethod, headers: HTTPHeaders?, responseParser: ResponseParser, delegate: RequestableDelegate?) -> Observable<ResponseParser.SuccessResponse> func updateRequestStatus(_ requestState: RequestState) } public extension ApiRequestable { public func request<ResponseParser: ResponseParserProtocol>( sessionManager: SessionManager, url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, parameterEncoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil, responseParser: ResponseParser, delegate: RequestableDelegate? = nil) -> Observable<ResponseParser.SuccessResponse> { return callApiTask( sessionManager: sessionManager, url: url, method: method, parameters: parameters, parameterEncoding: parameterEncoding, headers: headers, responseParser: responseParser, delegate: delegate ) .flatMap { self.parseSuccessResponseTask(responseParser: responseParser, response: $0) } .do( onError: { _ in self.updateRequestStatus(.error) }, onCompleted: { self.updateRequestStatus(.success) } ) } public func uploadRequest<ResponseParser: ResponseParserProtocol>( sessionManager: SessionManager, multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold: UInt64 = SessionManager.multipartFormDataEncodingMemoryThreshold, to: URLConvertible, method: HTTPMethod = .post, headers: HTTPHeaders? = nil, responseParser: ResponseParser, delegate: RequestableDelegate? = nil) -> Observable<ResponseParser.SuccessResponse> { return callUploadApiTask( sessionManager: sessionManager, multipartFormData: multipartFormData, usingThreshold: usingThreshold, to: to, method: method, headers: headers, responseParser: responseParser, delegate: delegate ) .flatMap { self.parseSuccessResponseTask(responseParser: responseParser, response: $0) } .do( onError: { _ in self.updateRequestStatus(.error) }, onCompleted: { self.updateRequestStatus(.success) } ) } public func updateRequestStatus(_ requestState: RequestState) { } private func callApiTask<ResponseParser: ResponseParserProtocol>( sessionManager: SessionManager, url: URLConvertible, method: HTTPMethod, parameters: Parameters?, parameterEncoding: ParameterEncoding, headers: HTTPHeaders?, responseParser: ResponseParser, delegate: RequestableDelegate?) -> Observable<DataResponse<String>> { return Observable.create { observer in self.updateRequestStatus(.requesting) let dataRequest = sessionManager.request( url, method: method, parameters: parameters, encoding: parameterEncoding, headers: headers ) .validate() .responseString(completionHandler: { response in self.handleResponse(response: response, responseParser: responseParser, observer: observer, delegate: delegate) }) delegate?.requestable(self, didSendRequest: dataRequest) return Disposables.create() } } private func callUploadApiTask<ResponseParser: ResponseParserProtocol>( sessionManager: SessionManager, multipartFormData: @escaping (MultipartFormData) -> Void, usingThreshold: UInt64, to url: URLConvertible, method: HTTPMethod, headers: HTTPHeaders?, responseParser: ResponseParser, delegate: RequestableDelegate?) -> Observable<DataResponse<String>> { return Observable.create { observer in self.updateRequestStatus(.requesting) let encodingCompletion:((SessionManager.MultipartFormDataEncodingResult) -> Void)? = { (result) in switch result { case .success(request: let request, streamingFromDisk: _, streamFileURL: _): delegate?.requestable(self, didUploadRequest: request) request.validate() .responseString(completionHandler: { response in self.handleResponse(response: response, responseParser: responseParser, observer: observer, delegate: delegate) }) case .failure(let error): observer.onError(error) } } do { let urlRequest = try URLRequest(url: url, method: method, headers: headers) sessionManager.upload( multipartFormData: multipartFormData, usingThreshold: usingThreshold, with: urlRequest, encodingCompletion: encodingCompletion ) } catch { DispatchQueue.main.async { encodingCompletion?(.failure(error)) } } return Disposables.create() } } private func handleResponse<ResponseParser: ResponseParserProtocol>(response: DataResponse<String>, responseParser: ResponseParser, observer: AnyObserver<DataResponse<String>>, delegate:RequestableDelegate?) { guard response.result.isSuccess else { if let result = responseParser.parseErrorResponse(response: response) { delegate?.requestable(self, didReceiveResponse: response) observer.onError(result) } else { observer.onError(AROError.requestFailed(response: response)) } return } delegate?.requestable(self, didReceiveResponse: response) observer.onNext(response) observer.onCompleted() } private func parseSuccessResponseTask<ResponseParser: ResponseParserProtocol>(responseParser: ResponseParser, response: DataResponse<String>) -> Observable<ResponseParser.SuccessResponse> { return Observable.create { observer in DispatchQueue.global(qos: .userInteractive).async { guard let result = responseParser.parseSuccessResponse(response: response) else { observer.onError(AROError.parseSuccessResponseFailed(response: response)) return } observer.onNext(result) observer.onCompleted() } return Disposables.create() } } } public extension ApiRequestable where Self: RequestStatusObservable { func updateRequestStatus(_ requestState: RequestState) { requestStatus.onNext(requestState) } } <file_sep># Launch Debug Server ``` cd Server bundle exec ruby server.rb ``` <file_sep>Pod::Spec.new do |s| s.name = "ARORequest" s.version = "0.4.0" s.summary = "Alamofire + RxSwift + ObjectMapper" s.homepage = "https://github.com/taka0125/ARORequest" s.license = "MIT" s.author = { "<NAME>" => "<EMAIL>" } s.source = { :git => "https://github.com/taka0125/ARORequest.git", :tag => s.version.to_s } s.ios.deployment_target = "8.0" s.pod_target_xcconfig = { 'SWIFT_VERSION' => '4.2' } s.source_files = "Sources/**/*.swift" s.dependency 'Alamofire', '~> 4.8.1' s.dependency 'RxSwift', '~> 4.4.2' s.dependency 'ObjectMapper', '~> 3.4.2' end <file_sep># frozen_string_literal: true source "https://rubygems.org" gem 'json', github: 'flori/json', branch: 'v1.8' gem "cocoapods" gem "sinatra" <file_sep>// // ApiRequestable.swift // // Created by <NAME> // Copyright (c) 2016 <NAME>. All rights reserved. // Released under the MIT license. // import Alamofire import ObjectMapper public protocol ResponseParserProtocol { associatedtype SuccessResponse: Mappable associatedtype ErrorResponse: Mappable, Error func parseSuccessResponse(response: DataResponse<String>) -> SuccessResponse? func parseErrorResponse(response: DataResponse<String>) -> ErrorResponse? } public extension ResponseParserProtocol { public func parseSuccessResponse(response: DataResponse<String>) -> SuccessResponse? { guard let value = response.result.value else { return nil } guard let result = Mapper<SuccessResponse>().map(JSONString: value) else { return nil } return result } public func parseErrorResponse(response: DataResponse<String>) -> ErrorResponse? { guard let data = response.data else { return nil } guard let JSONString = String(data: data, encoding: .utf8) else { return nil } guard let result = Mapper<ErrorResponse>().map(JSONString: JSONString) else { return nil } return result } } public struct NullResponse: Mappable { public init?(map: Map) { } public mutating func mapping(map: Map) { } } public struct NullErrorResponse: Mappable, Error { public init?(map: Map) { } public mutating func mapping(map: Map) { } } public struct NullSuccessResponseParser<E: Mappable & Error>: ResponseParserProtocol { public typealias SuccessResponse = NullResponse public typealias ErrorResponse = E public init() { } } public struct NullErrorResponseParser<S: Mappable>: ResponseParserProtocol { public typealias SuccessResponse = S public typealias ErrorResponse = NullErrorResponse public init() { } } public struct NullResponseParser: ResponseParserProtocol { public typealias SuccessResponse = NullResponse public typealias ErrorResponse = NullErrorResponse public init() { } } public struct DefaultResponseParser<S: Mappable, E: Mappable & Error>: ResponseParserProtocol { public typealias SuccessResponse = S public typealias ErrorResponse = E public init() { } } <file_sep>require 'sinatra' require 'json' require 'securerandom' get '/success.json' do response = { id: 1, uuid: SecureRandom.uuid } response.to_json end get '/error.json' do response = { title: 'Error', message: 'An error has occurred' } status 400 body response.to_json end <file_sep>// // RequestState.swift // // Created by <NAME> // Copyright (c) 2016 <NAME>. All rights reserved. // Released under the MIT license. // import Foundation public enum RequestState { case none case requesting case success case error } <file_sep># ARORequest [![Version](https://img.shields.io/cocoapods/v/ARORequest.svg?style=flat)](http://cocoadocs.org/docsets/ARORequest) [![License](https://img.shields.io/cocoapods/l/ARORequest.svg?style=flat)](http://cocoadocs.org/docsets/ARORequest) [![Platform](https://img.shields.io/cocoapods/p/ARORequest.svg?style=flat)](http://cocoadocs.org/docsets/ARORequest) ## Installation ```ruby source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! pod 'ARORequest' ``` Then, run the following command: ```console $ pod install ``` ## Author <NAME>, <EMAIL> ## License ARORequest is available under the MIT license. See the LICENSE file for more info. <file_sep>platform :ios, '8.0' target 'ARORequestSample' do use_frameworks! pod 'ARORequest', path: '../' end <file_sep>// // ViewController.swift // ARORequestSample // // Created by <NAME> on 2016/11/19. // Copyright © 2016年 <NAME>. All rights reserved. // import UIKit import ARORequest import Alamofire import RxSwift import ObjectMapper struct SuccessResponse: Mappable { var id: Int = 0 var uuid: String = "" init?(map: Map) { } mutating func mapping(map: Map) { id <- map["id"] uuid <- map["uuid"] } } struct ErrorResponse: Mappable, Error { var title: String = "" var message: String = "" init?(map: Map) { } mutating func mapping(map: Map) { title <- map["title"] message <- map["message"] } } protocol MyApiRequestable: ApiRequestable { func headers() -> HTTPHeaders func parameterEncoding() -> ParameterEncoding } extension MyApiRequestable { func request<S: Mappable>( url: URLConvertible, method: HTTPMethod, parameters: Parameters? = nil, delegate: RequestableDelegate? = nil) -> Observable<S> { let sessionManager = SessionManager.default let parser = DefaultResponseParser<S, ErrorResponse>() return request( sessionManager: sessionManager, url: url, method: method, parameters: parameters, parameterEncoding: parameterEncoding(), headers: headers(), responseParser: parser, delegate: delegate ) } func request( url: URLConvertible, method: HTTPMethod, parameters: Parameters? = nil) -> Observable<NullResponse> { let sessionManager = SessionManager.default let parser = NullSuccessResponseParser<ErrorResponse>() return request( sessionManager: sessionManager, url: url, method: method, parameters: parameters, parameterEncoding: parameterEncoding(), headers: headers(), responseParser: parser ) } } class ViewController: UITableViewController { enum Row: Int { case successExample case errorExample case nullResponseExample case myApiRequestableSuccessExample case myApiRequestableErrorExample case myApiRequestableDelegateExample case myApiRequestableDelegateErrorExample var text: String { switch self { case .successExample: return "Success Example" case .errorExample: return "Error Example" case .nullResponseExample: return "Null Response Example" case .myApiRequestableSuccessExample: return "My ApiRequestable Success Example" case .myApiRequestableErrorExample: return "My ApiRequestable Error Example" case .myApiRequestableDelegateExample: return "My ApiRequestable Delegate Example" case .myApiRequestableDelegateErrorExample: return "My ApiRequestable Delegate Error Example" } } static var count: Int { return myApiRequestableDelegateErrorExample.rawValue + 1 } } let disposeBag = DisposeBag() override func viewDidLoad() { tableView.rowHeight = 44.0 tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return Row.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let row = Row(rawValue: indexPath.row) else { return UITableViewCell() } let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = row.text return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { defer { tableView.deselectRow(at: indexPath, animated: true) } guard let row = Row(rawValue: indexPath.row) else { return } switch row { case .successExample: doSuccessExample() case .errorExample: doErrorExample() case .nullResponseExample: doNullResponseExample() case .myApiRequestableSuccessExample: doMyApiRequestableSuccessExample() case .myApiRequestableErrorExample: doMyApiRequestableErrorExample() case .myApiRequestableDelegateExample: doMyApiRequestableDelegateExample() case .myApiRequestableDelegateErrorExample: doMyApiRequestableDelegateErrorExample() } } } extension ViewController: ApiRequestable { fileprivate func doSuccessExample() { let sessionManager = SessionManager.default let url = "http://localhost:4567/success.json" let responseParser = DefaultResponseParser<SuccessResponse, ErrorResponse>() request( sessionManager: sessionManager, url: url, method: .get, parameters: nil, parameterEncoding: URLEncoding.default, headers: nil, responseParser: responseParser ).subscribe { (event) in print(event) }.addDisposableTo(disposeBag) } fileprivate func doErrorExample() { let sessionManager = SessionManager.default let url = "http://localhost:4567/error.json" let responseParser = DefaultResponseParser<SuccessResponse, ErrorResponse>() request( sessionManager: sessionManager, url: url, method: .get, parameters: nil, parameterEncoding: URLEncoding.default, headers: nil, responseParser: responseParser ).subscribe { (event) in print(event) }.addDisposableTo(disposeBag) } fileprivate func doNullResponseExample() { let sessionManager = SessionManager.default let url = "http://localhost:4567/error.json" let responseParser = NullResponseParser() request( sessionManager: sessionManager, url: url, method: .get, parameters: nil, parameterEncoding: URLEncoding.default, headers: nil, responseParser: responseParser ).subscribe { (event) in print(event) }.addDisposableTo(disposeBag) } } extension ViewController: MyApiRequestable { internal func headers() -> HTTPHeaders { return ["X-MyApp-Name": "sample"] } internal func parameterEncoding() -> ParameterEncoding { return URLEncoding.default } fileprivate func doMyApiRequestableSuccessExample() { let url = "http://localhost:4567/success.json" request(url: url, method: .get, parameters: nil).subscribe { (event: Event<SuccessResponse>) in print(event) }.addDisposableTo(disposeBag) } fileprivate func doMyApiRequestableErrorExample() { let url = "http://localhost:4567/error.json" request(url: url, method: .get, parameters: nil).subscribe { (event) in print(event) }.addDisposableTo(disposeBag) } fileprivate func doMyApiRequestableDelegateExample() { let url = "http://localhost:4567/success.json" request(url: url, method: .get, parameters: nil, delegate: self).subscribe { (event: Event<SuccessResponse>) in print(event) }.addDisposableTo(disposeBag) } fileprivate func doMyApiRequestableDelegateErrorExample() { let url = "http://localhost:4567/error.json" request(url: url, method: .get, parameters: nil, delegate: self).subscribe { (event: Event<SuccessResponse>) in print(event) }.addDisposableTo(disposeBag) } } extension ViewController: RequestableDelegate { func requestable(_ requestable: ApiRequestable, didUploadRequest request: UploadRequest) { print("called didUploadRequest") } func requestable(_ requestable: ApiRequestable, didSendRequest request: DataRequest) { print("called didSendRequest") print(request.request!) } func requestable(_ requestable: ApiRequestable, didReceiveResponse response: DataResponse<String>) { print("called didReceiveResponse") print(response.response!) } }
0e936e79d18221490dbfe3c9971ea23be359643b
[ "Swift", "Ruby", "Markdown" ]
11
Swift
taka0125/ARORequest
52b9885064b41922c2e978c3246a0baef430a18c
90bc921ffb7f91c092936e974663a753f5575a38
refs/heads/master
<file_sep>function zoom() { thumb.setAttribute("class","thumb grande"); celu.setAttribute("class","visible "); celu.setAttribute("height","150"); } function otro() { thumb.setAttribute("class","thumb "); celu.setAttribute("class","invisible"); celu.setAttribute("height","120"); } function zoom2() { thumb2.setAttribute("class","thumb grande"); celu2.setAttribute("class","visible "); } function otro2() { thumb2.setAttribute("class","thumb "); celu2.setAttribute("class","invisible"); } function zoom3() { thumb3.setAttribute("class","thumb grande"); celu3.setAttribute("class","visible "); } function otro3() { thumb3.setAttribute("class","thumb "); celu3.setAttribute("class","invisible"); } function zoom4() { thumb4.setAttribute("class","thumb grande"); celu4.setAttribute("class","visible "); } function otro4() { thumb4.setAttribute("class","thumb "); celu4.setAttribute("class","invisible"); } function zoom5() { thumb5.setAttribute("class","thumb grande"); celu5.setAttribute("class","visible "); } function otro5() { thumb5.setAttribute("class","thumb "); celu5.setAttribute("class","invisible"); } function zoom6() { thumb6.setAttribute("class","thumb grande"); celu6.setAttribute("class","visible "); } function otro6() { thumb6.setAttribute("class","thumb "); celu6.setAttribute("class","invisible"); } var thumb=document.getElementById("thumb"); var celu=document.getElementById("celu"); var thumb2=document.getElementById("thumb2"); var celu2=document.getElementById("celu2"); var thumb3=document.getElementById("thumb3"); var celu3=document.getElementById("celu3"); var thumb4=document.getElementById("thumb4"); var celu4=document.getElementById("celu4"); var thumb5=document.getElementById("thumb5"); var celu5=document.getElementById("celu5"); var thumb6=document.getElementById("thumb6"); var celu6=document.getElementById("celu6"); thumb.addEventListener("mouseover",zoom); thumb.addEventListener("mouseout",otro); thumb2.addEventListener("mouseover",zoom2); thumb2.addEventListener("mouseout",otro2); thumb3.addEventListener("mouseover",zoom3); thumb3.addEventListener("mouseout",otro3); thumb4.addEventListener("mouseover",zoom4); thumb4.addEventListener("mouseout",otro4); thumb5.addEventListener("mouseover",zoom5); thumb5.addEventListener("mouseout",otro5); thumb6.addEventListener("mouseover",zoom6); thumb6.addEventListener("mouseout",otro6);
8ef3130af3a920d4da7fbcaedb3ccd723a1fc09e
[ "JavaScript" ]
1
JavaScript
TeamOpenSource1/Trika
c8145b7deee3e1609e7f2fccd6c8af96502a34fd
6615d47d479601f6c927b801ba6d9c5b72fa6aa1
refs/heads/master
<file_sep>#define _USE_MATH_DEFINES #include "warpfunctions.h" #include <math.h> Point3f WarpFunctions::squareToDiskUniform(const Point2f &sample) { //TODO float radius = sqrt(sample.x); float phi = 2*M_PI * sample.y; return glm::vec3(radius * cos(phi), radius * sin(phi), 0.0f); } Point3f WarpFunctions::squareToDiskConcentric(const Point2f &sample) { //TODO float phi, radius; float a = 2*sample.x-1; // (a,b) is now on [-1,1]ˆ2 float b = 2*sample.y-1; if (a > -b) // region 1 or 2 { if (a > b) // region 1, also |a| > |b| { radius = a; phi = (M_PI/4 ) * (b/a); } else // region 2, also |b| > |a| { radius = b; phi = (M_PI/4) * (2 - (a/b)); } } else // region 3 or 4 { if (a < b) // region 3, also |a| >= |b|, a != 0 { radius = -a; phi = (M_PI/4) * (4 + (b/a)); } else // region 4, |b| >= |a|, but a==0 and b==0 could occur. { radius = -b; if (b != 0) phi = (M_PI/4) * (6 - (a/b)); else phi = 0; } } return glm::vec3(radius * cos(phi), radius * sin(phi), 0.0f); } float WarpFunctions::squareToDiskPDF(const Point3f &sample) { //TODO return InvPi; } Point3f WarpFunctions::squareToSphereUniform(const Point2f &sample) { //TODO float z = 1 - 2*sample.x; return glm::vec3(sqrt(1 - z*z) *cos(2*M_PI * sample.y), sqrt(1 - z*z)*sin(2*M_PI * sample.y), z); } float WarpFunctions::squareToSphereUniformPDF(const Point3f &sample) { //TODO return Inv4Pi; } Point3f WarpFunctions::squareToSphereCapUniform(const Point2f &sample, float thetaMin) { //TODO thetaMin = glm::radians(180.f - thetaMin); float z = 1.f - (1.f - std::cos(thetaMin)) * sample.x; return glm::vec3(sqrt(1 - z*z) *cos(2*M_PI * sample.y), sqrt(1 - z*z)*sin(2*M_PI * sample.y), z); } float WarpFunctions::squareToSphereCapUniformPDF(const Point3f &sample, float thetaMin) { //TODO return Inv2Pi * (1.0f / (1.0f - cos(glm::radians(180 - thetaMin)))); } Point3f WarpFunctions::squareToHemisphereUniform(const Point2f &sample) { //TODO float z = sample.x; return glm::vec3(sqrt(1 - z*z) *cos(2*M_PI * sample.y), sqrt(1 - z*z)*sin(2*M_PI * sample.y), z); } float WarpFunctions::squareToHemisphereUniformPDF(const Point3f &sample) { //TODO return Inv2Pi; } Point3f WarpFunctions::squareToHemisphereCosine(const Point2f &sample) { //TODO glm::vec3 disk = squareToDiskConcentric(sample); float x = disk.x; float y = disk.y; float z = sqrt(1 - x*x - y*y); return glm::vec3(x, y, z); } float WarpFunctions::squareToHemisphereCosinePDF(const Point3f &sample) { //TODO float cosTheta = glm::dot(sample, glm::vec3(0,0,1)); return InvPi * cosTheta; } <file_sep>#include "diffusearealight.h" Color3f DiffuseAreaLight::L(const Intersection &isect, const Vector3f &w) const { //TODO if (this->twoSided || SameHemisphere(w,isect.normalGeometric)) { return emittedLight; } else { return Color3f(0.f); } } // Given a point of intersection on some surface in the scene and a pair // of uniform random variables, generate a sample point on the surface // of our shape and evaluate the light emitted along the ray from // our Shape's surface to the reference point. Color3f DiffuseAreaLight::Sample_Li(const Intersection &ref, const Point2f &xi, Vector3f *wi, Float *pdf) const { Intersection lightsample = this->shape->Sample(ref,xi,pdf); if( (*pdf) == 0.f || (ref.point == lightsample.point)) { *pdf == 0.f; return Color3f(0.f); } *wi = glm::normalize(lightsample.point - ref.point); if(*pdf > 0) { return emittedLight; } else { return Color3f(0.f); } } float DiffuseAreaLight::Pdf_Li(const Intersection &ref, const Vector3f &wi) const { //TODO float pdfli = 0.f; Intersection closest = Intersection(); Ray wiWray = ref.SpawnRay(wi); if(!this->shape->Intersect(wiWray,&closest)) { return 0.f; } if(closest.objectHit == nullptr || closest.objectHit->GetAreaLight() != this) { //BxDF sample didn't hit the light. pdfli still 0 } else { //else return the pdf due to our intersection with the light float coslight = glm::abs( glm::dot(closest.normalGeometric, -wi)); float denominator = coslight * this->shape->Area(); if(denominator != 0.f) { pdfli = glm::distance2(ref.point, closest.point) / denominator; } } return pdfli; } <file_sep>#include "lambertbtdf.h" #include <warpfunctions.h> Color3f LambertBTDF::f(const Vector3f &wo, const Vector3f &wi) const { //TODO return InvPi * (R*opacity + Color3f(1.0f ,1.0f ,1.0f) * (1.0f - opacity)); } Color3f LambertBTDF::Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &u, Float *pdf, BxDFType *sampledType) const { //TODO *wi = glm::normalize( WarpFunctions::squareToHemisphereCosine(u)); *pdf = Pdf(wo, *wi); //Out->in handling if(CosTheta(wo) > 0.0f) *wi = -*wi; return f(wo, *wi); } float LambertBTDF::Pdf(const Vector3f &wo, const Vector3f &wi) const { //TODO return WarpFunctions::squareToHemisphereCosinePDF(wi); } <file_sep>#include "shape.h" #include <QDateTime> pcg32 Shape::colorRNG = pcg32(QDateTime::currentMSecsSinceEpoch()); void Shape::InitializeIntersection(Intersection *isect, float t, Point3f pLocal) const { isect->point = Point3f(transform.T() * glm::vec4(pLocal, 1)); ComputeTBN(pLocal, &(isect->normalGeometric), &(isect->tangent), &(isect->bitangent)); isect->uv = GetUVCoordinates(pLocal); isect->t = t; } Intersection Shape::Sample(const Intersection &ref, const Point2f &xi, float *pdf) const { //TODO Intersection inters = Sample(xi, pdf); //Converet light sample weight to solid angle measure Vector3f LightVec = glm::normalize(inters.point - ref.point); float InvArea = *pdf; float NoL = glm::abs(glm::dot(inters.normalGeometric, -LightVec)); //Exception Handling if(NoL != 0.0f) *pdf = glm::distance2(ref.point, inters.point) * InvArea / NoL; return inters; } <file_sep>#include "squareplane.h" float SquarePlane::Area() const { //TODO return transform.getScale().x * transform.getScale().y; } bool SquarePlane::Intersect(const Ray &ray, Intersection *isect) const { //Transform the ray Ray r_loc = ray.GetTransformedCopy(transform.invT()); //Ray-plane intersection float t = glm::dot(glm::vec3(0,0,1), (glm::vec3(0.5f, 0.5f, 0) - r_loc.origin)) / glm::dot(glm::vec3(0,0,1), r_loc.direction); Point3f P = Point3f(t * r_loc.direction + r_loc.origin); //Check that P is within the bounds of the square if(t > 0 && P.x >= -0.5f && P.x <= 0.5f && P.y >= -0.5f && P.y <= 0.5f) { InitializeIntersection(isect, t, P); return true; } return false; } void SquarePlane::ComputeTBN(const Point3f &P, Normal3f *nor, Vector3f *tan, Vector3f *bit) const { *nor = glm::normalize(transform.invTransT() * Normal3f(0,0,1)); //TODO: Compute tangent and bitangent glm::vec4 ta = transform.T() * glm::vec4(1,0,0,0); *tan = glm::normalize(Vector3f(ta.x, ta.y, ta.z)); glm::vec4 bi = transform.T() * glm::vec4(0,1,0,0); *bit = glm::normalize(Vector3f(bi.x, bi.y, bi.z)); //*bit = glm::normalize(glm::cross(*nor ,*tan)); } Point2f SquarePlane::GetUVCoordinates(const Point3f &point) const { return Point2f(point.x + 0.5f, point.y + 0.5f); } Intersection SquarePlane::Sample(const Point2f &xi, Float *pdf) const { Intersection inter; //A SquarePlane is assumed to have a radius of 1 and a center of <0,0,0>. Point2f pt = Point2f(xi.x -0.5f, xi.y -0.5f); glm::vec4 WSP = transform.T() * glm::vec4(pt.x, pt.y, 0.0f,1.0f); Point3f WorldSpacePoint = Point3f(WSP.x, WSP.y, WSP.z); inter.point = WorldSpacePoint; inter.normalGeometric = glm::normalize(transform.invTransT() * Normal3f(0,0,1)); *pdf = 1.0f / Area(); return inter; } <file_sep>#include "cube.h" #include <iostream> float Cube::Area() const { //TODO return (transform.getScale().x * transform.getScale().y + transform.getScale().y * transform.getScale().z + transform.getScale().x * transform.getScale().z) * 2.0f; } // Returns +/- [0, 2] int GetFaceIndex(const Point3f& P) { int idx = 0; float val = -1; for(int i = 0; i < 3; i++){ if(glm::abs(P[i]) > val){ idx = i * glm::sign(P[i]); val = glm::abs(P[i]); } } return idx; } Normal3f GetCubeNormal(const Point3f& P) { int idx = glm::abs(GetFaceIndex(Point3f(P))); Normal3f N(0,0,0); N[idx] = glm::sign(P[idx]); return N; } bool Cube::Intersect(const Ray& r, Intersection* isect) const { //Transform the ray Ray r_loc = r.GetTransformedCopy(transform.invT()); float t_n = -1000000; float t_f = 1000000; for(int i = 0; i < 3; i++){ //Ray parallel to slab check if(r_loc.direction[i] == 0){ if(r_loc.origin[i] < -0.5f || r_loc.origin[i] > 0.5f){ return false; } } //If not parallel, do slab intersect check float t0 = (-0.5f - r_loc.origin[i])/r_loc.direction[i]; float t1 = (0.5f - r_loc.origin[i])/r_loc.direction[i]; if(t0 > t1){ float temp = t1; t1 = t0; t0 = temp; } if(t0 > t_n){ t_n = t0; } if(t1 < t_f){ t_f = t1; } } if(t_n < t_f) { float t = t_n > 0 ? t_n : t_f; if(t < 0) return false; //Lastly, transform the point found in object space by T glm::vec4 P = glm::vec4(r_loc.origin + t*r_loc.direction, 1); InitializeIntersection(isect, t, Point3f(P)); return true; } else{//If t_near was greater than t_far, we did not hit the cube return false; } } void Cube::ComputeTBN(const Point3f& P, Normal3f* nor, Vector3f* tan, Vector3f* bit) const { Normal3f localNormal = GetCubeNormal(P); *nor = glm::normalize(transform.invTransT() * GetCubeNormal(P)); //TODO: Compute tangent and bitangent // +x if(localNormal.x == 1.0f) { *tan = Vector3f(0, 0, -1); *bit = Vector3f(0, 1, 0); } // +z else if(localNormal.z == 1) { *tan = Vector3f(1, 0, 0); *bit = Vector3f(0, 1, 0); } else if(localNormal.x == -1) { *tan = Vector3f(0, 0, 1); *bit = Vector3f(0, 1, 0); } else if(localNormal.z == -1) { *tan = Vector3f(-1, 0, 0); *bit = Vector3f(0, 1, 0); } else if(localNormal.y == 1) { *tan = Vector3f(1, 0, 0); *bit = Vector3f(0, 0, -1); } else if(localNormal.y == -1) { *tan = Vector3f(1, 0, 0); *bit = Vector3f(0, 0, 1); } glm::vec4 ta = transform.T() * glm::vec4((*tan).r,(*tan).b,(*tan).g,0); *tan = glm::normalize(Vector3f(ta.x, ta.y, ta.z)); //*tan = transform.invTransT() * (*tan); *bit = glm::normalize(glm::cross(*nor ,*tan)); } glm::vec2 Cube::GetUVCoordinates(const glm::vec3 &point) const { glm::vec3 abs = glm::min(glm::abs(point), 0.5f); glm::vec2 UV;//Always offset lower-left corner if(abs.x > abs.y && abs.x > abs.z) { UV = glm::vec2(point.z + 0.5f, point.y + 0.5f)/3.0f; //Left face if(point.x < 0) { UV += glm::vec2(0, 0.333f); } else { UV += glm::vec2(0, 0.667f); } } else if(abs.y > abs.x && abs.y > abs.z) { UV = glm::vec2(point.x + 0.5f, point.z + 0.5f)/3.0f; //Left face if(point.y < 0) { UV += glm::vec2(0.333f, 0.333f); } else { UV += glm::vec2(0.333f, 0.667f); } } else { UV = glm::vec2(point.x + 0.5f, point.y + 0.5f)/3.0f; //Left face if(point.z < 0) { UV += glm::vec2(0.667f, 0.333f); } else { UV += glm::vec2(0.667f, 0.667f); } } return UV; } Intersection Cube::Sample(const Intersection &ref, const Point2f &xi, float *pdf) const { Intersection inter; //remapped Point2f pt = Point2f(glm::fract(xi.x*3.2345f* xi.y) -0.5f, xi.y -0.5f); std::vector<std::pair<int, float>> faces; // std::vector<int> _faces; float maxDot = 0.0f; //Z+ glm::vec4 ppt = transform.T() * glm::vec4( pt.x, pt.y, 0.5f, 1.0f); if( glm::dot( glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,0,1))) < 0.0f ) { maxDot = -glm::dot( glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,0,1))); faces.push_back(std::pair<int, float>(0,maxDot)); } //Z- ppt = transform.T() * glm::vec4(pt.x, pt.y, -0.5f, 1.0f); if( glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,0,-1))) < 0.0f ) { maxDot = -glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,0,-1))); faces.push_back(std::pair<int, float>(1,maxDot)); } //Y+ ppt = transform.T() * glm::vec4(pt.x, 0.5f, pt.y, 1.0f); if( glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,1,0))) < 0.0f ) { maxDot = -glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,1,0))); faces.push_back(std::pair<int, float>(2,maxDot)); } //Y- ppt = transform.T() * glm::vec4( pt.x, -0.5f, pt.y, 1.0f); if( glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,-1,0))) < 0.0f ) { maxDot = -glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(0,-1,0))); faces.push_back(std::pair<int, float>(3,maxDot)); } //X+ ppt = transform.T() * glm::vec4( 0.5f, pt.x, pt.y, 1.0f); if( glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(1,0,0))) < 0.0f ) { maxDot = -glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(1,0,0))); faces.push_back(std::pair<int, float>(4,maxDot)); } //X- ppt = transform.T() * glm::vec4( -0.5f, pt.x, pt.y, 1.0f); if( glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(-1,0,0))) < 0.0f ) { maxDot = -glm::dot(glm::normalize(Point3f(ppt.x, ppt.y, ppt.z) - ref.point), glm::normalize(transform.invTransT() * Normal3f(-1,0,0))); faces.push_back(std::pair<int, float>(5,maxDot)); } //Random Select one face float totalDot = 0.0f; float currentDot = 0.0f; for(int i=0; i<faces.size(); i++) { std::pair<int, float> fuc2k = faces.at(i); totalDot += fuc2k.second; } int chosenFace = -1; for(int i=0; i<faces.size(); i++) { std::pair<int, float> fuc2k = faces.at(i); currentDot += fuc2k.second/totalDot; if(xi.x <= currentDot) { chosenFace = i; break; } } if(chosenFace < 0) { *pdf = 0; return inter; } glm::vec4 WSP; Point3f WorldSpacePoint; std::pair<int, float> tempPair = faces.at(chosenFace); //Z+ if(tempPair.first == 0) { WSP = transform.T() * glm::vec4(pt.x, pt.y, 0.5f,1.0f); WorldSpacePoint = Point3f(WSP.x, WSP.y, WSP.z); inter.normalGeometric = glm::normalize(transform.invTransT() * Normal3f(0,0,1)); } //Z- else if(tempPair.first == 1) { WSP = transform.T() * glm::vec4(pt.x, pt.y, -0.5f,1.0f); WorldSpacePoint = Point3f(WSP.x, WSP.y, WSP.z); inter.normalGeometric = glm::normalize(transform.invTransT() * Normal3f(0,0,-1)); } //Y+ else if(tempPair.first == 2) { WSP = transform.T() * glm::vec4(pt.x, 0.5f, pt.y, 1.0f); WorldSpacePoint = Point3f(WSP.x, WSP.y, WSP.z); inter.normalGeometric = glm::normalize(transform.invTransT() * Normal3f(0,1,0)); } //Y- else if(tempPair.first == 3) { WSP = transform.T() * glm::vec4(pt.x, -0.5f, pt.y,1.0f); WorldSpacePoint = Point3f(WSP.x, WSP.y, WSP.z); inter.normalGeometric = glm::normalize(transform.invTransT() * Normal3f(0,-1,0)); } //X+ else if(tempPair.first == 4) { WSP = transform.T() * glm::vec4(0.5f, pt.x, pt.y, 1.0f); WorldSpacePoint = Point3f(WSP.x, WSP.y, WSP.z); inter.normalGeometric = glm::normalize(transform.invTransT() * Normal3f(1,0,0)); } //X- else if(tempPair.first == 5) { WSP = transform.T() * glm::vec4(-0.5f, pt.x, pt.y, 1.0f); WorldSpacePoint = Point3f(WSP.x, WSP.y, WSP.z); inter.normalGeometric = glm::normalize(transform.invTransT() * Normal3f(-1,0,0)); } inter.point = WorldSpacePoint; *pdf = Area() * 1.5f * totalDot; return inter; } Intersection Cube::Sample(const Point2f &xi, Float *pdf) const { return Intersection(); } <file_sep>#include "lambertbrdf.h" #include <warpfunctions.h> Color3f LambertBRDF::f(const Vector3f &wo, const Vector3f &wi) const { //TODO return R * InvPi; } Color3f LambertBRDF::Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &u, Float *pdf, BxDFType *sampledType) const { //TODO *wi = WarpFunctions::squareToHemisphereCosine(u); *pdf = LambertBRDF::Pdf(wo,*wi); return LambertBRDF::f(wo,*wi); } float LambertBRDF::Pdf(const Vector3f &wo, const Vector3f &wi) const { //TODO return WarpFunctions::squareToHemisphereCosinePDF(wi); } ////Oren-Nayar diffuse reflection //Color3f OrenNayarBRDF::f(const Vector3f &wo, const Vector3f &wi) const //{ // //TODO // float sinThetaI = BSDF::SinTheta(wi); // float sinThetaO = BSDF::SinTheta(wo); // // //cos term of Oren-Nayar model // float maxCos = 0.f; // if(sinThetaI > 0.0001f && sinThetaO > 0.0001f) { // float sinPhiI = BSDF::SinPhi(wi), cosPhiI = BSDF::CosPhi(wi); // float sinPhiO = BSDF::SinPhi(wo), cosPhiO = BSDF::CosPhi(wo); // // float dCos = cosPhiI * cosPhiO + sinPhiI * sinPhiO; // maxCos = std::max(0.f, dCos); // } // // //sin and tan terms of Oren-Nayar model // float sinAlpha, tanBeta; // if(AbsCosTheta(wi) > AbsCosTheta(wo)) { // sinAlpha = sinThetaO; // tanBeta = sinThetaI / AbsCosTheta(wi); // } else { // sinAlpha = sinThetaI; // tanBeta = sinThetaO / AbsCosTheta(wo); // } // // return R * InvPi * (A + B * maxCos * sinAlpha * tanBeta); //} // //Color3f OrenNayarBRDF::Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &u, // Float *pdf, BxDFType *sampledType) const //{ // //TODO // *wi = WarpFunctions::squareToHemisphereCosine(u); // *pdf = OrenNayarBRDF::Pdf(wo,*wi); // return OrenNayarBRDF::f(wo,*wi); //} // //float OrenNayarBRDF::Pdf(const Vector3f &wo, const Vector3f &wi) const //{ // //TODO // return WarpFunctions::squareToHemisphereCosinePDF(wi); //} Color3f LambertBTDF::f(const Vector3f &wo, const Vector3f &wi) const { //TODO return R * InvPi; } Color3f LambertBTDF::Sample_f(const Vector3f &wo, Vector3f *wi, const Point2f &u, Float *pdf, BxDFType *sampledType) const { //TODO *wi = WarpFunctions::squareToHemisphereCosine(u); *pdf = LambertBTDF::Pdf(wo,*wi); *wi = -1.f * (*wi); return LambertBTDF::f(wo,*wi); } float LambertBTDF::Pdf(const Vector3f &wo, const Vector3f &wi) const { //TODO return WarpFunctions::squareToHemisphereCosinePDF(wi); }
9209abdd9c67f96dbc6c92fa4e1df4407aea8c5c
[ "C++" ]
7
C++
loshjawrence/number4
34f6a571f97fc7207067ffb1c17a4a12eea9232c
0f3f029225946a2cbd127e704b0c5326c41b9406
refs/heads/master
<repo_name>shivakumar361/Simple-Puzzle<file_sep>/Number_game.c File name : Number_game.c #include<stdio.h> #include<stdlib.h> #include<dos.h> enum arrow_keys { exit_case=0, up_key=8, down_key=2, left_key=4, right_key=6 }; enum arrow_keys arrow_key; void display(int *puzzle); void shift_up(int(*q)[4]); void shift_down(int (*q)[4]); void shift_left(int (*q)[4]); void shift_right(int (*q)[4]); enum arrow_keys getkey(void); unsigned int puzzle_check(int *); int main() { int puzzle[4][4]={1,4,15,7,8,10,0,2,11,14,3,6,13,12,9,5}; int flag=0; printf("\nThis is the puzzle\n"); display(*puzzle); printf("\nRearrange the sequence in ascending order row wise using arrow keys\n"); while(1) { printf("\nEnter the arrow key to rearrange or 0 to exit\n"); arrow_key=getkey(); switch(arrow_key) { case exit_case:printf("You are exiting the game\n"); system("pause"); exit(0); break; case up_key:shift_up(puzzle); break; case down_key:shift_down(puzzle); break; case left_key:shift_left(puzzle); break; case right_key:shift_right(puzzle); break; default: printf("\nInvalid Key press\n"); } display(*puzzle); flag=puzzle_check(*puzzle); if(flag==1) { printf("\npuzzle is complete\n"); display(*puzzle); break; } } system("pause"); return 0; } enum arrow_keys getkey() { unsigned int key; scanf("%u",&key); return key; } void display(int *puzzle) { int i,j; for(i=0;i<4;i++) { for(j=0;j<4;j++) { printf("%d\t",*(puzzle+j)); } printf("\n"); puzzle=puzzle+4; } } void shift_up(int (*q)[4]) { int *ptr; int i,j,temp; for(i=0;i<3;i++) { ptr=(int *)(q+i); for(j=0;j<4;j++) { if(*(ptr+j)==0) { temp=*(ptr+j); *(ptr+j)=*(ptr+j+4); *(ptr+j+4)=temp; return; } } } } void shift_down(int (*q)[4]) { int *ptr; int i,j,temp; for(i=1;i<4;i++) { ptr=(int *)(q+i); for(j=0;j<4;j++) { if(*(ptr+j)==0) { temp=*(ptr+j); *(ptr+j)=*(ptr+j-4); *(ptr+j-4)=temp; return; } } } } void shift_left(int (*q)[4]) { int *ptr; int i,j,temp; for(i=0;i<4;i++) { ptr=(int*)(q+i); for(j=0;j<3;j++) { if(*(ptr+j)==0) { temp=*(ptr+j); *(ptr+j)=*(ptr+j+1); *(ptr+j+1)=temp; return; } } } } void shift_right(int (*q)[4]) { int *ptr; int i,j,temp; for(i=0;i<4;i++) { ptr=(int*)(q+i); for(j=1;j<4;j++) { if(*(ptr+j)==0) { temp=*(ptr+j); *(ptr+j)=*(ptr+j-1); *(ptr+j-1)=temp; return; } } } } unsigned int puzzle_check(int *puzzle) { int i,j,flag=0; int *ptr; ptr=puzzle; for(i=0;i<15;i++) { if(*(ptr+i+1)-*(ptr+i)==1) { flag=1; } else { flag=0; break; } } return flag; } <file_sep>/README.md Simple-Puzzle ============= Arrange the numbers in square matrix in ascending order.. This is my first project on GitHub. A 3*3 matrix has numbers from 1 to 15 dispersed in any order. You are required to arrange the numbers in ascending order using arrow keys as described below: Key Direction 2 Down 4 left 6 right 8 up This game is in the beginning stage. To make it compatible across all machines, arrow keys need to be used for choosing the direction. This game is developed in C programming language using DevC++ editor. Please feel free to provide your feedback. Thanks. <file_sep>/Number_game.h #ifndef NUMBER_GAME_H #def NUMBER_GAME_H #include<stdio.h> #include<stdlib.h> #include<dos.h> #endif
a85f493211f136cc13da3da94a2de0c85db4fa4a
[ "Markdown", "C" ]
3
C
shivakumar361/Simple-Puzzle
af1eed05e341ba9569cba9049a62d6869b6a5e14
4df47d9edcc1115c845f5b4c62fe990dc9d3491d
refs/heads/master
<file_sep>import java.awt.GridLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; public class TicTacToeGui extends JFrame implements ActionListener { // adds images ImageIcon player1X = new ImageIcon( "/Users/jakeburns/Documents/Java Coding/Weber Tic Tac Toe/src/x.png"); ImageIcon player1O = new ImageIcon( "/Users/jakeburns/Documents/Java Coding/Weber Tic Tac Toe/src/circle4.png"); private JPanel panel; public JButton[] button; int width = 153; int height = 153; int runOrNot = 0; int amountXWins, amountOWins, numberTies, numberUntilWinINT = 0; String numberUntilWin; public TicTacToeGui() { setTitle("Tic Tac Toe"); setSize(463, 475); setResizable(false); setDefaultCloseOperation(EXIT_ON_CLOSE); setLocationRelativeTo(null); buildPanel(); add(panel); panel.setLayout(new GridLayout(3, 3)); setVisible(true); for (int j = 0; j <= 8; j++) { // adds action listener for all buttons button[j].addActionListener(this); } } private void buildPanel() { button = new JButton[9]; panel = new JPanel(); for (int i = 0; i <= 8; i++) { // Initiates all buttons button[i] = new JButton(); panel.add(button[i]); } // setting single or multiplayer // button[0].setText("Click for player one"); // button[1].setText("Click for player two."); int askNumberUntilWin = JOptionPane.showConfirmDialog(null, "Set number of wins needed to win?"); if (askNumberUntilWin == JOptionPane.CANCEL_OPTION) { return; } if (askNumberUntilWin == JOptionPane.NO_OPTION) { } if (askNumberUntilWin == JOptionPane.YES_OPTION) { numberUntilWin = JOptionPane .showInputDialog("Enter number of max wins."); numberUntilWinINT = Integer.parseInt(numberUntilWin); System.out.println(numberUntilWin); } String XAndOColor = JOptionPane .showInputDialog("Enter 1 - Blue, 2 - red, 3 - green, 4 - yellow, 5 - pink, or press ok for default (black)."); if (XAndOColor.equalsIgnoreCase("1")) { player1X = new ImageIcon( "/Users/jakeburns/Documents/Java Coding/Weber Tic Tac Toe/src/blueX2.jpeg"); } if (XAndOColor.equalsIgnoreCase("2")) { player1X = new ImageIcon( "/Users/jakeburns/Documents/Java Coding/Weber Tic Tac Toe/src/redX.png"); } if (XAndOColor.equalsIgnoreCase("3")) { player1X = new ImageIcon( "/Users/jakeburns/Documents/Java Coding/Weber Tic Tac Toe/src/greenX.png"); } if (XAndOColor.equalsIgnoreCase("4")) { player1X = new ImageIcon( "/Users/jakeburns/Documents/Java Coding/Weber Tic Tac Toe/src/yellowX.png"); } if (XAndOColor.equalsIgnoreCase("5")) { player1X = new ImageIcon( "/Users/jakeburns/Documents/Java Coding/Weber Tic Tac Toe/src/pinkX.png"); } } void checkForWinnerO() { if (button[0].getIcon() != null && button[1].getIcon() != null && button[2].getIcon() != null) { if (button[0].getIcon().equals(player1O) && button[1].getIcon().equals(player1O) && button[2].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } if (button[3].getIcon() != null && button[0].getIcon() != null && button[6].getIcon() != null) { if (button[3].getIcon().equals(player1O) && button[0].getIcon().equals(player1O) && button[6].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!.."); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } if (button[4].getIcon() != null && button[0].getIcon() != null && button[8].getIcon() != null) { if (button[0].getIcon().equals(player1O) && button[4].getIcon().equals(player1O) && button[8].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!."); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } if (button[1].getIcon() != null && button[4].getIcon() != null && button[7].getIcon() != null) { if (button[1].getIcon().equals(player1O) && button[4].getIcon().equals(player1O) && button[7].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } if (button[2].getIcon() != null && button[5].getIcon() != null && button[8].getIcon() != null) { if (button[2].getIcon().equals(player1O) && button[5].getIcon().equals(player1O) && button[8].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } if (button[2].getIcon() != null && button[4].getIcon() != null && button[6].getIcon() != null) { if (button[2].getIcon().equals(player1O) && button[4].getIcon().equals(player1O) && button[6].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } if (button[3].getIcon() != null && button[4].getIcon() != null && button[5].getIcon() != null) { if (button[3].getIcon().equals(player1O) && button[4].getIcon().equals(player1O) && button[5].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } if (button[6].getIcon() != null && button[7].getIcon() != null && button[8].getIcon() != null) { if (button[6].getIcon().equals(player1O) && button[7].getIcon().equals(player1O) && button[8].getIcon().equals(player1O)) { JOptionPane.showMessageDialog(null, "O wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountOWins++; askToRestart(); } } } void checkForWinnerX() { if (button[1].getIcon() != null && button[0].getIcon() != null && button[2].getIcon() != null) { if (button[1].getIcon().equals(player1X) && button[0].getIcon().equals(player1X) && button[2].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } if (button[3].getIcon() != null && button[0].getIcon() != null && button[6].getIcon() != null) { if (button[3].getIcon().equals(player1X) && button[0].getIcon().equals(player1X) && button[6].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } if (button[4].getIcon() != null && button[0].getIcon() != null && button[8].getIcon() != null) { if (button[0].getIcon().equals(player1X) && button[4].getIcon().equals(player1X) && button[8].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } if (button[1].getIcon() != null && button[4].getIcon() != null && button[7].getIcon() != null) { if (button[1].getIcon().equals(player1X) && button[4].getIcon().equals(player1X) && button[7].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } if (button[2].getIcon() != null && button[5].getIcon() != null && button[8].getIcon() != null) { if (button[2].getIcon().equals(player1X) && button[5].getIcon().equals(player1X) && button[8].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } if (button[2].getIcon() != null && button[4].getIcon() != null && button[6].getIcon() != null) { if (button[2].getIcon().equals(player1X) && button[4].getIcon().equals(player1X) && button[6].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } if (button[3].getIcon() != null && button[4].getIcon() != null && button[5].getIcon() != null) { if (button[3].getIcon().equals(player1X) && button[4].getIcon().equals(player1X) && button[5].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } if (button[6].getIcon() != null && button[7].getIcon() != null && button[8].getIcon() != null) { if (button[6].getIcon().equals(player1X) && button[7].getIcon().equals(player1X) && button[8].getIcon().equals(player1X)) { JOptionPane.showMessageDialog(null, "X wins!"); runOrNot++; for (int j = 0; j <= 8; j++) { button[j].setEnabled(false); } amountXWins++; askToRestart(); } } } void RestartGame() { // reset all icons pictures and make them clickable for (int j = 0; j <= 8; j++) { button[j].setIcon(null); button[j].setEnabled(true); } playerTurn = 0; } void askToRestart() { if ((amountXWins | amountOWins) != 0) { displayWins(); } int restart = JOptionPane.showConfirmDialog(null, "Restart?"); if (restart == JOptionPane.OK_OPTION) { RestartGame(); } if (restart == JOptionPane.NO_OPTION) { JOptionPane.showMessageDialog(null, "Program terminated."); System.exit(0); return; } } void displayWins() { if (numberUntilWinINT != 0) { if ((amountXWins | amountOWins) == numberUntilWinINT) { if (amountXWins == numberUntilWinINT) { JOptionPane.showMessageDialog(null, "X wins match with " + amountXWins + " wins! O only had " + amountOWins + " wins!"); System.exit(0); } else if (amountOWins == numberUntilWinINT) { JOptionPane.showMessageDialog(null, "O wins match with " + amountOWins + " wins! X only had " + amountXWins + " wins!"); System.exit(0); } } } JOptionPane.showMessageDialog(null, "X has " + amountXWins + " wins. O has " + amountOWins + " wins. There are " + numberTies + " ties."); } int playerTurn = 0; int ran = 0; int runThis = 0; int clicked = 0; public void actionPerformed(ActionEvent e) { for (int clicked = 0; clicked <= 8; clicked++) { if (button[clicked] == e.getSource()) { // check which button was // if (playerTurn % 2 == 0) { // when it is x's turn button[clicked].setIcon(player1X); button[clicked].setEnabled(false); button[clicked].setDisabledIcon(player1X); playerTurn++; System.out.println(playerTurn); checkForWinnerO(); checkForWinnerX(); if (playerTurn > 8) { // checking for tie numberTies++; JOptionPane.showMessageDialog(null, "Tie!"); displayWins(); int restart = JOptionPane.showConfirmDialog(null, "Restart?"); if (restart == JOptionPane.OK_OPTION) { RestartGame(); } if (restart == JOptionPane.NO_OPTION) { JOptionPane.showMessageDialog(null, "Program terminated."); System.exit(0); return; } } } else { button[clicked].setIcon(player1O); button[clicked].setEnabled(false); button[clicked].setDisabledIcon(player1O); playerTurn++; System.out.println(playerTurn); checkForWinnerO(); checkForWinnerX(); } } } } public static void main(String[] args) { new TicTacToeGui(); } } <file_sep># TicTacToe tic tac toe java gui
8ec81cee12446d44d4b73e626f35677c42123dc3
[ "Markdown", "Java" ]
2
Java
jakeburns/TicTacToe
e12a398258cd5f8dd7a4240b750dcdc21deef29a
8caf188e4225e5d20a40fc64c9c55ca679d0eec1
refs/heads/main
<repo_name>reii-code/PBO_4418<file_sep>/Pertemuan 3/gameEnemy.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author user */ public class GameEnemy { double width; double height; int positionX; int positionY; GameEnemy(){ } public GameEnemy(double width,double height,int positionX,int positionY) { } public void setDimension(double width,double height) { the.width = width; the.height = height; } public void setPosition(int positionX,int positionY) { the.positionX = positionX; the.positionY = positionY; } public double getWidth() { return the.width; } public double getHeight() { return the.height; } public int getX() { return the.positionX; } public int getY() { return the.positionY; } public void Run() { System.out.println("Enemy is running"); } }<file_sep>/Pertemuan2/Mobil.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package mobil; public class Mobil { public static void main(String[] args) { MobilL myCar = new MobilL(); myCar.hidupkanMobil(); myCar.ubahGigi(1); System.out.println("Mobil sudah menyala : " + myCar.active + " Masukan gigi mobil " + myCar.gigi); } } class Mobill { boolean active = false; int gigi; Mobill() { } public void hidupkanMobil() { active = true; } public void matikanMobil() { active = false; } public void ubahGigi(int gigiBaru) { if (active) { gigi = gigiBaru; } } }<file_sep>/Pertemuan2/matematika.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author asus */ package matematika; public class Matematika { public static void main(String[] args) { matematika hitung = new matematika(); hitung.pertambahan(10, 30); hitung.pengurangan(50, 25); hitung.perkalian(25, 5); hitung.pembagian(35, 5); } } class matematika { matematika() { } public void pertambahan(int num1, int num2) { int hasil = num1 + num2; System.out.println("Pertambahan: " + num1 + " + " + num2 + " = " + hasil); } public void pengurangan(int num1, int num2) { int hasil = num1 - num2; System.out.println("Pengurangan: " + num1 + " - " + num2 + " = " + hasil); } public void perkalian(int num1, int num2) { int hasil = num1 * num2; System.out.println("Perkalian: " + num1 + " x " + num2 + " = " + hasil); } public void pembagian(int num1, int num2) { int hasil = num1 / num2; System.out.println("Pembagian: " + num1 + " / " + num2 + " = " + hasil); } } <file_sep>/pertemuan 4/gamePlayer.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author user */ public class GamePlayer { double width; double height; int positionX; int positionY; GamePlayer(){ } public GamePlayer (double width,double height,int positionX,int positionY) { } public void setDimension (double width,double height) { the.width = width; the.height = height; } public void setPosition (int positionX,int positionY) { the.positionX = positionX; the.positionY = positionY; } public double getWidth() { return th.width; } public double getHeight() { return the.height; } public int getX(){ return the.positionX; } public int getY(){ return the.positionY; } public void Run() { System.out.println("Player is running"); } public void Run(int incrementX){ incrementX = positionX + incrementX; System.out.println("Player still running...current X position="+ incrementX); } }<file_sep>/Pertemuan 6/TransportasiDemo.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import Transportasi.Bicycle; import Transportasi.Mobil; public class TransportasiDemo { public static void main(String[] args){ Bicyle sepeda = new Bicycle(); sepeda.ringBell(Kring..kring...); sepeda.changeGear(4); sepeda.speedUp(15); Mobil mobil = new Mobil("Black", Nissan); mobil.getwarna(); mobil.getmerk(); System.out.println("warna Mobil : "+mobil.getwarna()); System.out.println("merk Mobil : "+mobil.getmerk()); } }
f151ab90fe70642d510e31138c8c5cb6fdf8f967
[ "Java" ]
5
Java
reii-code/PBO_4418
eb5c3239873d0f25cbd9c9f0a86a476d923e9618
c29799652dcb55ab28161710fe3cd8709e31b09d
refs/heads/master
<repo_name>cleliacort/CIRIquant<file_sep>/requirements.txt numexpr==2.6.9 numpy==1.16.4 pysam==0.15.2 PyYAML==5.4 scikit-learn==0.20.3 scipy==1.2.2 argparse>=1.2.1 <file_sep>/CIRIquant/prep_CIRIquant.py #! /usr/bin/env python # -*- encoding:utf-8 -*= import os import sys import argparse import logging from collections import namedtuple from version import __version__ LOGGER = logging.getLogger('prep_CIRIquant') CIRC = namedtuple('CIRC', 'bsj fsj ratio rnaser_bsj rnaser_fsj') INFO = namedtuple('INFO', 'strand circ_type gene_id gene_name gene_type') def load_gtf(in_file): from circ import GTFParser LOGGER.info('Loading CIRIquant result: {}'.format(in_file)) circ_data = {} circ_info = {} with open(in_file, 'r') as f: header = {} for line in f: if line.startswith('##'): key, value = line.rstrip().strip('#').split(':') header.update({key.strip(): value.strip()}) continue content = line.rstrip().split('\t') tmp_parser = GTFParser(content) circ_data[tmp_parser.attr['circ_id']] = CIRC( float(tmp_parser.attr['bsj']), float(tmp_parser.attr['fsj']), float(tmp_parser.attr['junc_ratio']), float(tmp_parser.attr['rnaser_bsj']) if 'rnaser_bsj' in tmp_parser.attr else None, float(tmp_parser.attr['rnaser_fsj']) if 'rnaser_fsj' in tmp_parser.attr else None, ) circ_info[tmp_parser.attr['circ_id']] = INFO( tmp_parser.strand, tmp_parser.attr['circ_type'], tmp_parser.attr['gene_id'] if 'gene_id' in tmp_parser.attr else 'NA', tmp_parser.attr['gene_name'] if 'gene_name' in tmp_parser.attr else 'NA', tmp_parser.attr['gene_type'] if 'gene_type' in tmp_parser.attr else 'NA', ) return header, circ_data, circ_info def main(): global LOGGER from logger import get_logger from utils import check_file # Init argparser parser = argparse.ArgumentParser(prog="prep_CIRIquant") parser.add_argument('-i', dest='input', metavar='FILE', required=True, help='input sample list', ) parser.add_argument('--lib', dest='lib', metavar='FILE', required=True, help='output file of library information') parser.add_argument('--circ', dest='circ', metavar='FILE', required=True, help='output file of circRNA annotation information') parser.add_argument('--bsj', dest='bsj', metavar='FILE', required=True, help='output file of circRNA bsj reads number', ) parser.add_argument('--ratio', dest='ratio', metavar='FILE', required=True, help='output file of circRNA junction ratio matrix', ) # Optional parameters args = parser.parse_args() LOGGER = get_logger('prep_CIRIquant', None, False) # Load GTF sample_lst = check_file(args.input) lib_file, info_file = os.path.abspath(args.lib), os.path.abspath(args.circ) bsj_file, ratio_file = os.path.abspath(args.bsj), os.path.abspath(args.ratio) LOGGER.info('Input file name: {}'.format(os.path.basename(sample_lst))) LOGGER.info('Output library information: {}'.format(lib_file)) LOGGER.info('Output circRNA annotation: {}'.format(info_file)) LOGGER.info('Output BSJ matrix: {}'.format(bsj_file)) LOGGER.info('Output Ratio matrix: {}'.format(ratio_file)) all_circ = {} all_sample = {} all_data = {} is_paired = 0 with open(sample_lst, 'r') as f: for line in f: content = line.rstrip().split() if len(content) == 0: continue sample, sample_file, group = content[0], content[1], content[2] sample_header, sample_data, sample_info = load_gtf(sample_file) all_sample[sample] = sample_header all_sample[sample]['Group'] = group if len(content) > 3: all_sample[sample]['Subject'] = content[3] is_paired = 1 all_circ.update(sample_info) all_data[sample] = sample_data sample_names = sorted(all_sample.keys()) circ_ids = sorted(all_circ.keys()) # library information and circRNA annotation with open(lib_file, 'w') as lib_out, open(info_file, 'w') as info_out: info_out.write('circ_id,strand,circ_type,gene_id,gene_name,gene_type\n') for circ_id in circ_ids: tmp_circ = all_circ[circ_id] tmp_line = [circ_id, tmp_circ.strand,tmp_circ.circ_type, tmp_circ.gene_id, tmp_circ.gene_name, tmp_circ.gene_type] info_out.write(','.join(['"{}"'.format(x) for x in tmp_line]) + '\n') if is_paired == 0: lib_out.write('Sample,Total,Mapped,Circular,Group\n') else: lib_out.write('Sample,Total,Mapped,Circular,Group,Subject\n') for sample in sample_names: tmp_sample = all_sample[sample] tmp_line = [sample, tmp_sample['Total_Reads'], tmp_sample['Mapped_Reads'], tmp_sample['Circular_Reads'], tmp_sample['Group'], ] if is_paired != 0: if 'Subject' in tmp_sample: tmp_line.append(tmp_sample['Subject']) else: LOGGER.error('No subject ID found for {}, please check your input'.format(sample)) sys.exit() lib_out.write(','.join(tmp_line) + '\n') # BSJ and junction ratio with open(bsj_file, 'w') as bsj_out, open(ratio_file, 'w') as ratio_out: tmp_header = ["circ_id", ] + sample_names bsj_out.write(','.join(tmp_header) + '\n') ratio_out.write(','.join(tmp_header) + '\n') for circ_id in circ_ids: tmp_bsj, tmp_ratio = [circ_id, ], [circ_id, ] for sample in sample_names: if circ_id in all_data[sample]: tmp_bsj.append(all_data[sample][circ_id].bsj) tmp_ratio.append(all_data[sample][circ_id].ratio) else: tmp_bsj.append(0) tmp_ratio.append(0) bsj_out.write(','.join([str(x) for x in tmp_bsj]) + '\n') ratio_out.write(','.join([str(x) for x in tmp_ratio]) + '\n') LOGGER.info('Finished!') if __name__ == '__main__': main() <file_sep>/CIRIquant/pipeline.py #! /usr/bin/env python # -*- encoding:utf-8 -*= import os import sys import logging import subprocess import utils LOGGER = logging.getLogger('CIRIquant') def align_genome(log_file, thread, reads, outdir, prefix): # mapping to reference genome align_dir = outdir + '/align' utils.check_dir(align_dir) hisat_bam = '{}/{}.bam'.format(align_dir, prefix) hisat_cmd = '{} -p {} --dta -q -x {} -1 {} -2 {} -t | {} view -bS > {}'.format( utils.HISAT2, thread, utils.HISAT_INDEX, reads[0], reads[1], utils.SAMTOOLS, hisat_bam ) # sort hisat2 bam sorted_bam = '{}/{}.sorted.bam'.format(align_dir, prefix) sort_cmd = '{} sort --threads {} -o {} {}'.format( utils.SAMTOOLS, thread, sorted_bam, hisat_bam, ) index_cmd = '{} index -@ {} {}'.format( utils.SAMTOOLS, thread, sorted_bam, ) with open(log_file, 'a') as log: LOGGER.debug(hisat_cmd) subprocess.call(hisat_cmd, shell=True, stderr=log) LOGGER.debug(sort_cmd) subprocess.call(sort_cmd, shell=True, stderr=log) LOGGER.debug(index_cmd) subprocess.call(index_cmd, shell=True, stderr=log) if os.path.getsize(sorted_bam + '.bai') <= 16: raise utils.PipelineError('Empty hisat2 bam generated, please re-run CIRIquant with -v and check the fastq and hisat2-index.') return sorted_bam def gene_abundance(log_file, thread, outdir, prefix, hisat_bam): align_dir = outdir + '/align' utils.check_dir(align_dir) # estimate gene expression LOGGER.info('Estimate gene abundance ..') gene_dir = '{}/gene'.format(outdir) utils.check_dir(gene_dir) stringtie_cmd = '{0} {1} -e -G {2} -C {3}/{4}_cov.gtf -p {5} -o {3}/{4}_out.gtf -A {3}/{4}_genes.list'.format( utils.STRINGTIE, hisat_bam, utils.GTF, gene_dir, prefix, thread, ) with open(log_file, 'a') as log: LOGGER.debug(stringtie_cmd) subprocess.call(stringtie_cmd, shell=True, stderr=log) LOGGER.debug('Gene expression profile: {}/{}_genes.list'.format(gene_dir, prefix)) return 1 def run_bwa(log_file, thread, cand_reads, outdir, prefix): LOGGER.info('Running BWA-mem mapping candidate reads ..') utils.check_dir('{}/circ'.format(outdir)) bwa_sam = '{}/circ/{}_unmapped.sam'.format(outdir, prefix) bwa_cmd = '{} mem -t {} -T 19 {} {} > {}'.format( utils.BWA, thread, utils.BWA_INDEX, ' '.join(cand_reads), bwa_sam, ) with open(log_file, 'a') as log: LOGGER.debug(bwa_cmd) subprocess.call(bwa_cmd, shell=True, stderr=log, stdout=log) LOGGER.debug('BWA-mem sam: ' + bwa_sam) return bwa_sam def run_ciri(log_file, thread, bwa_sam, outdir, prefix): LOGGER.info('Running CIRI2 for circRNA detection ..') ciri_file = '{}/circ/{}.ciri'.format(outdir, prefix) ciri_cmd = 'CIRI2.pl -I {} -O {} -F {} -A {} -0 -T {} -G {}'.format( bwa_sam, ciri_file, utils.FASTA, utils.GTF, thread, log_file, ) with open(log_file, 'a') as log: LOGGER.debug(ciri_cmd) subprocess.call(ciri_cmd, shell=True, stderr=log, stdout=log) return ciri_file def convert_bed(ciri_file): out_file = ciri_file + '.bed' with open(ciri_file, 'r') as f, open(out_file, 'w') as out: f.readline() for line in f: content = line.rstrip().split('\t') chrom, start, end = content[1:4] strand = content[10] out.write('\t'.join([chrom, start, end, '{}:{}|{}'.format(chrom, start, end), '.', strand]) + '\n') return out_file def clean_tmp(outdir, prefix): tmp_files = [ '{}/circ/{}_unmapped.sam'.format(outdir, prefix), '{}/circ/{}_denovo.bam'.format(outdir, prefix), '{}/align/{}.bam'.format(outdir, prefix), ] for f in tmp_files: if os.path.exists(f) and os.path.isfile(f): os.remove(f) return 0 <file_sep>/setup.py #! /usr/bin/env python # -*- encoding:utf-8 -*- import os import codecs from setuptools import setup, find_packages from CIRIquant.version import __version__ def read(infile): return codecs.open(os.path.join(os.path.dirname(__file__), infile)).read() setup( name='CIRIquant', version=__version__, author='<NAME>', author_email='<EMAIL>', maintainer='<NAME>', maintainer_email='<EMAIL>', url='https://github.com/bioinfo-biols/CIRIquant', description='circular RNA quantification pipeline', long_description=read('README.md'), long_description_content_type='text/markdown', classifiers=[ 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', ], license='MIT', packages=find_packages(), entry_points={ 'console_scripts': [ 'CIRIquant=CIRIquant.main:main', 'CIRI_DE=CIRIquant.de:main', 'CIRI_DE_replicate=CIRIquant.replicate:main', 'prep_CIRIquant=CIRIquant.prep_CIRIquant:main' ] }, keywords='circRNA', include_package_data=True, zip_safe=False, install_requires=[ 'argparse>=1.2.1', 'PyYAML==5.4', 'pysam==0.15.2', 'numpy==1.16.4', 'scipy==1.2.2', 'scikit-learn==0.20.3', 'numexpr==2.6.9', ], ) <file_sep>/CIRIquant/de.py #! /usr/bin/env python # -*- encoding:utf-8 -*= import os import sys import argparse import logging from multiprocessing import Pool from collections import namedtuple import numpy as np np.random.seed(5) import numexpr as ne ne.set_num_threads(4) from version import __version__ LOGGER = logging.getLogger('CIRI_DE') CIRC = namedtuple('CIRC', 'bsj fsj ratio rnaser_bsj rnaser_fsj') def main(): global LOGGER from circ import grouper from logger import get_logger from utils import check_file, get_thread_num # Init argparser parser = argparse.ArgumentParser(prog="CIRIquant") parser.add_argument('-n', dest='control', metavar='CONTROL', default=None, help='control gtf file', ) parser.add_argument('-c', dest='case', metavar='CASE', default=None, help='case gtf file', ) parser.add_argument('-o', dest='out', metavar='FILE', default='CIRI_DE.csv', help='output file name', ) parser.add_argument('-p', dest='pval', metavar='FLOAT', default=0.05, help='P value threshold for DE and DS score calculation', ) parser.add_argument('-t', '--threads', dest='cpu_threads', default=4, metavar='INT', help='Number of CPU threads, default: 4', ) # Optional parameters args = parser.parse_args() thread = get_thread_num(int(args.cpu_threads)) LOGGER = get_logger('CIRI_DE', None, False) size = 100000 pval = float(args.pval) assert 0 < pval < 0.5 # Load GTF case_gtf, ctrl_gtf = check_file(args.case), check_file(args.control) out_csv = os.path.abspath(args.out) LOGGER.info('Experiment: {}'.format(os.path.basename(case_gtf))) LOGGER.info('Control: {}'.format(os.path.basename(ctrl_gtf))) LOGGER.info('Threads: {}'.format(thread)) LOGGER.info('Threshold: {}'.format(args.pval)) case_header, case_data = load_gtf(case_gtf) ctrl_header, ctrl_data = load_gtf(ctrl_gtf) factor = float(case_header['Mapped_Reads']) / float(ctrl_header['Mapped_Reads']) # Multiprocessing all_circ = set(case_data.keys() + ctrl_data.keys()) jobs = [] chunk_size = max(1000, len(all_circ) / thread + 1) if 'N' in case_header and 'N' in ctrl_header: pool = Pool(thread, correction_initializer, (case_data, case_header, ctrl_data, ctrl_header, size, pval)) for circ_chunk in grouper(all_circ, chunk_size): jobs.append(pool.apply_async(correction_worker, (circ_chunk, factor, ))) else: pool = Pool(thread, score_initializer, (case_data, ctrl_data, size, pval)) for circ_chunk in grouper(all_circ, chunk_size): jobs.append(pool.apply_async(score_worker, (circ_chunk, factor, ))) pool.close() pool.join() circ_scores = dict() for job in jobs: tmp_score = job.get() circ_scores.update(tmp_score) LOGGER.info('Output csv: {}'.format(out_csv)) with open(out_csv, 'w') as out: out.write('circRNA_ID\tCase_BSJ\tCase_FSJ\tCase_Ratio\tCtrl_BSJ\tCtrl_FSJ\tCtrl_Ratio\tDE_score\tDS_score\n') for circ_id in all_circ: case_bsj = int(case_data[circ_id].bsj) if circ_id in case_data else 0 case_fsj = int(case_data[circ_id].fsj) if circ_id in case_data else 0 case_ratio = float(case_data[circ_id].ratio) if circ_id in case_data else 0 ctrl_bsj = int(ctrl_data[circ_id].bsj) if circ_id in ctrl_data else 0 ctrl_fsj = int(ctrl_data[circ_id].fsj) if circ_id in ctrl_data else 0 ctrl_ratio = float(ctrl_data[circ_id].ratio) if circ_id in ctrl_data else 0 tmp_de, tmp_ds = circ_scores[circ_id] tmp_line = [circ_id, case_bsj, case_fsj, case_ratio, ctrl_bsj, ctrl_fsj, ctrl_ratio, tmp_de, tmp_ds] out.write('\t'.join([str(x) for x in tmp_line]) + '\n') LOGGER.info('Finished!') CASE = None CTRL = None CASE_PRIOR = [] CTRL_PRIOR = [] SIZE = 100000 PVAL = 0.05 def score_initializer(case_data, ctrl_data, size, pval): global CASE, CTRL global SIZE, PVAL CASE, CTRL = case_data, ctrl_data SIZE = size PVAL = pval def correction_initializer(case_data, case_header, ctrl_data, ctrl_header, size, pval): global CASE, CTRL, CASE_PRIOR, CTRL_PRIOR global SIZE, PVAL CASE, CTRL = case_data, ctrl_data CASE_PRIOR = gmm_sampling(case_header) CTRL_PRIOR = gmm_sampling(ctrl_header) SIZE = size PVAL = pval def score_worker(circ_ids, factor): score_data = {} for circ_id in circ_ids: case_bsj = int(CASE[circ_id].bsj) if circ_id in CASE else 0 ctrl_bsj = int(CTRL[circ_id].bsj) if circ_id in CTRL else 0 tmp_de = de_score(max(case_bsj, 1), max(ctrl_bsj, 1), 1.0 / factor, size=SIZE, pval=PVAL) case_fsj = int(CASE[circ_id].fsj) if circ_id in CASE else 0 ctrl_fsj = int(CTRL[circ_id].fsj) if circ_id in CTRL else 0 tmp_ds = ds_score(max(case_bsj, 1), max(case_fsj, 1), max(ctrl_bsj, 1), max(ctrl_fsj, 1), size=SIZE, pval=PVAL) score_data[circ_id] = (tmp_de, tmp_ds) return score_data def correction_worker(circ_ids, factor): score_data = {} for circ_id in circ_ids: if circ_id in CASE: if CASE[circ_id].rnaser_fsj and CASE[circ_id].fsj != 0: case_exp = prior_exp_sampling(CASE_PRIOR, CASE[circ_id].rnaser_bsj, CASE[circ_id].rnaser_fsj, CASE[circ_id].fsj) else: case_exp = np.random.gamma(shape=int(CASE[circ_id].bsj) + 1 + 1, size=SIZE) else: case_exp = np.random.gamma(shape=1, size=SIZE) if circ_id in CTRL: if CTRL[circ_id].rnaser_fsj and CTRL[circ_id].fsj != 0: ctrl_exp = prior_exp_sampling(CTRL_PRIOR, CTRL[circ_id].rnaser_bsj, CTRL[circ_id].rnaser_fsj, CTRL[circ_id].fsj) else: ctrl_exp = np.random.gamma(shape=int(CTRL[circ_id].bsj) + 1 + 1, size=SIZE) else: ctrl_exp = np.random.gamma(shape=1, size=SIZE) tmp_de = corrected_score(case_exp, ctrl_exp, 1.0 / factor, size=SIZE, pvalue=PVAL) score_data[circ_id] = (tmp_de, None) return score_data def load_gtf(in_file): from circ import GTFParser LOGGER.info('Loading CIRIquant result: {}'.format(in_file)) circ_data = {} with open(in_file, 'r') as f: header = {} for line in f: if line.startswith('##'): key, value = line.rstrip().strip('#').split(':') header.update({key.strip(): value.strip()}) continue content = line.rstrip().split('\t') tmp_parser = GTFParser(content) circ_data[tmp_parser.attr['circ_id']] = CIRC( float(tmp_parser.attr['bsj']), float(tmp_parser.attr['fsj']), float(tmp_parser.attr['junc_ratio']), float(tmp_parser.attr['rnaser_bsj']) if 'rnaser_bsj' in tmp_parser.attr else None, float(tmp_parser.attr['rnaser_fsj']) if 'rnaser_fsj' in tmp_parser.attr else None, ) return header, circ_data def de_score(a, b, factor=1, size=SIZE, pval=0.05): x1 = np.random.gamma(shape=a + 1, size=size) x2 = np.random.gamma(shape=b + 1, size=size) z = ne.evaluate("x1 / x2") z.sort() if np.mean(z) * factor >= 1: score = max(np.log2(z[int(round(size * pval))] * factor), 0) else: score = min(np.log2(z[int(round(size * (1 - pval)))] * factor), 0) return score def corrected_score(dis_a, dis_b, factor=1, size=SIZE, pvalue=0.05): from itertools import izip # fc = ne.evaluate("dis_a / dis_b") fc = sorted([np.log(j / i) for i, j in izip(dis_a, dis_b)]) miu = np.mean(fc) + factor assert len(dis_a) > 0 and len(dis_b) > 0 if miu >= 0: score = max((fc[int(size * pvalue)] + fc[int(size * pvalue) + 1]) / 2 + factor, 0) else: score = min((fc[-int(size * pvalue)] + fc[-int(size * pvalue) + 1]) / 2 + factor, 0) return score def ds_score(a1, b1, a2, b2, size=SIZE, pval=0.05): x1 = np.random.beta(a1, b1, size=size) x2 = np.random.beta(a2, b2, size=size) z = ne.evaluate("x1 / x2") z.sort() if np.mean(z) >= 1: score = max(np.log2(z[int(round(size * pval))]), 0) else: score = min(np.log2(z[int(round(size * (1 - pval)))]), 0) return score def gmm_sampling(header, size=SIZE): n = int(header['N']) w = header['W'].split(',') m = header['M'].split(',') sd = header['SD'].split(',') sample = np.array([]) for i in range(n): sample = np.append(sample, np.random.normal(float(m[i]), float(sd[i]), int(size * float(w[i])))) return sample def prior_exp_sampling(sample, bsj, fsj, total_fsj): factor = depth_factor(bsj / (bsj + 0.5 * fsj)) corrected_read = ne.evaluate("sample * 0.5 * factor * total_fsj") return [np.random.gamma(shape=x + 1) for x in corrected_read if x > 0] def depth_factor(r): return r / (1.0 - r) # def with_replicate(sample_lst, read_len): # from math import ceil # # lib_path = os.path.dirname(os.path.split(os.path.realpath(__file__))[0]) + '/libs' # # os.environ['PATH'] = lib_path + ':' + os.environ['PATH'] # # os.chmod(lib_path + '/CIRI_DE.Rscript', 0o755) # samples = [] # with open(sample_lst, 'r') as f: # for line in f: # samples.append(tuple(line.rstrip().split())) # # # ID,Type,Mapped_reads # design_matrix = [] # # g_matrix = defaultdict(dict) # t_matrix = defaultdict(dict) # gene_IDs = {} # # c_matrix = [] # j_matrix = [] # for sample, sample_type, prefix in samples: # gene_f = '{}/gene/{}_out.gtf'.format(prefix, sample) # circ_f = '{}/{}.gtf'.format(prefix, sample) # # with open(gene_f, 'r') as f: # t_len = 0 # for line in f: # if line.starswith('#'): # continue # content = line.rstrip().split('\t') # if content[2] == 'transcript': # if t_len > 0: # t_matrix[t_id].setdefault(sample, int(ceil(cov * t_len / read_len))) # t_id = RE_TRANSCRIPT_ID.search(content[-1]).group(1) # g_id = get_gene_ID(content[-1], chrom, t_id) # gene_IDs[t_id] = g_id # cov = get_cov(content[-1]) # t_len = 0 # if content[2] == 'exon': # t_len += int(content[4]) - int(content[3]) + 1 # t_matrix[t_id].setdefault(sample, int(ceil(cov * t_len / read_len))) # # with open(circ_f, 'r') as f: # header = {} # for line in f: # if line.startswith('##'): # key, value = line.strip('#').split(':') # header.update({key: value}) # continue # content = line.rstrip().split('\t') # if content[2] == 'circRNA': # continue # # # for t_id, t_exp in t_matrix.iteritems(): # for sample in t_exp: # g_matrix[gene_IDs[t_id]][sample] = g_matrix[gene_IDs[t_id]].setdefault(sample, 0) + t_exp[sample] # # # RE_GENE_ID=re.compile('gene_id "([^"]+)"') # RE_GENE_NAME=re.compile('gene_name "([^"]+)"') # RE_TRANSCRIPT_ID=re.compile('transcript_id "([^"]+)"') # RE_COVERAGE=re.compile('cov "([\-\+\d\.]+)"') # RE_STRING=re.compile(re.escape(opts.string)) # # t_id=RE_TRANSCRIPT_ID.search(v[len(v)-1]).group(1) # # def get_gene_ID(attr, chrom, t_id): # m = RE_GENE_ID.search(attr) # if m: # return m.group(1) # m = RE_GENE_NAME.search(attr) # if m: # return chrom + '|' + m.group(1) # return t_id # # # def get_cov(attr): # m = RE_COVERAGE.search(s) # cov = max(float(m.group(1)), 0.0) if m else 0.0 # return cov if __name__ == '__main__': main() <file_sep>/CIRIquant/main.py #! /usr/bin/env python # -*- encoding:utf-8 -*= import os import sys import re import argparse def main(): from version import __version__ import circ import pipeline from logger import get_logger from utils import check_file, check_dir, check_config, get_thread_num from utils import CIRCparser, TOOLS # Init argparser parser = argparse.ArgumentParser(prog='CIRIquant') # required arguments parser.add_argument('--config', dest='config_file', metavar='FILE', help='Config file in YAML format', ) parser.add_argument('-1', '--read1', dest='mate1', metavar='MATE1', help='Input mate1 reads (for paired-end data)', ) parser.add_argument('-2', '--read2', dest='mate2', metavar='MATE2', help='Input mate2 reads (for paired-end data)', ) # optional arguments parser.add_argument('-o', '--out', dest='output', metavar='DIR', default=None, help='Output directory, default: ./', ) parser.add_argument('-p', '--prefix', dest='prefix', metavar='PREFIX', default=None, help='Output sample prefix, default: input sample name', ) parser.add_argument('-t', '--threads', dest='cpu_threads', default=4, metavar='INT', help='Number of CPU threads, default: 4', ) parser.add_argument('-a', '--anchor', dest='anchor', default=5, metavar='INT', help='Minimum anchor length for junction alignment, default: 5', ) parser.add_argument('-l', '--library-type', dest='library_type', metavar='INT', default=0, help='Library type, 0: unstranded, 1: read1 match the sense strand,' '2: read1 match the antisense strand, default: 0', ) parser.add_argument('-v', '--verbose', dest='verbosity', default=False, action='store_true', help='Run in debugging mode', ) parser.add_argument('--version', action='version', version='%(prog)s {version}'.format(version=__version__)) parser.add_argument('-e', '--log', dest='log_file', default=None, metavar='LOG', help='Log file, default: out_dir/prefix.log', ) # provide pre-defined list of circRNAs parser.add_argument('--bed', dest='bed', metavar='FILE', default=None, help='bed file for putative circRNAs (optional)', ) parser.add_argument('--circ', dest='circ', metavar='FILE', default=None, help='circRNA prediction results from other softwares', ) parser.add_argument('--tool', dest='tool', metavar='TOOL', default=None, help='circRNA prediction tool, required if --circ is provided', ) # when provide RNase R result, do RNase R correction parser.add_argument('--RNaseR', dest='rnaser', metavar='FILE', default=None, help='CIRIquant result of RNase R sample', ) # skip hisat2 alignment for RNA-seq data parser.add_argument('--bam', dest='bam', metavar='BAM', default=None, help='hisat2 alignment to reference genome', ) # skip stringtie prediction parser.add_argument('--no-gene', dest='gene_exp', default=False, action='store_true', help='Skip stringtie estimation for gene abundance', ) args = parser.parse_args() """Check required parameters""" # check input reads if args.mate1 and args.mate2: reads = [check_file(args.mate1), check_file(args.mate2)] else: sys.exit('No input files specified, please see manual for detailed information') try: lib_type = int(args.library_type) except ValueError: sys.exit('Wrong library type, please check your command.\nSupported types:\n0 - unstranded;\n' '1 - read1 match the sense strand;\n2 - read1 match the antisense strand;') if lib_type not in [0, 1, 2]: sys.exit('Wrong library type, please check your command.\nSupported types:\n0 - unstranded;\n' '1 - read1 match the sense strand;\n2 - read1 match the antisense strand;') # check configuration if args.config_file: config = check_config(check_file(args.config_file)) else: sys.exit('A config file is needed, please see manual for detailed information.') """Check optional parameters""" # use circRNA bed file if provided bed_file = check_file(args.bed) if args.bed else None circ_file = check_file(args.circ) if args.circ else None circ_tool = args.tool # user provided RNase R CIRIquant results rnaser_file = check_file(args.rnaser) if args.rnaser else None # pre aligned hisat2 bam hisat_bam = check_file(args.bam) if args.bam else None # Output prefix if args.prefix is None: try: prefix = re.search(r'(\S+)[_/-][12]', os.path.basename(reads[0])).group(1) except AttributeError: sys.exit('Ambiguous sample name, please manually select output prefix') else: prefix = args.prefix # check output dir outdir = './' + prefix if args.output is None else args.output outdir = check_dir(outdir) # Parse arguments log_file = os.path.abspath(args.log_file) if args.log_file else '{}/{}.log'.format(outdir, prefix) verbosity = args.verbosity logger = get_logger('CIRIquant', log_file, verbosity) # Add lib to PATH lib_path = os.path.dirname(os.path.split(os.path.realpath(__file__))[0]) + '/libs' os.environ['PATH'] = lib_path + ':' + os.environ['PATH'] os.chmod(lib_path + '/CIRI2.pl', 0o755) """Start Running""" os.chdir(outdir) logger.info('Input reads: ' + ','.join([os.path.basename(args.mate1), os.path.basename(args.mate2)])) if lib_type == 0: lib_name = 'unstranded' elif lib_type == 1: lib_name = 'ScriptSeq' elif lib_type == 2: lib_name = 'TAKARA SMARTer' else: sys.exit('Unsupported library type, please check the manual for instructions.') logger.info('Library type: {}'.format(lib_name)) logger.info('Output directory: {}, Output prefix: {}'.format(outdir, prefix)) logger.info('Config: {} Loaded'.format(config)) thread = get_thread_num(int(args.cpu_threads)) anchor = int(args.anchor) # Step1: Data Preparation # Step1.1: HISAT2 mapping if hisat_bam is None: logger.info('Align RNA-seq reads to reference genome ..') hisat_bam = pipeline.align_genome(log_file, thread, reads, outdir, prefix) else: logger.info('HISAT2 alignment bam provided, skipping alignment step ..') logger.debug('HISAT2 bam: {}'.format(os.path.basename(hisat_bam))) # Step1.2: Estimate Gene Abundance if args.gene_exp: logger.info('Skipping gene abundance estimation') else: pipeline.gene_abundance(log_file, thread, outdir, prefix, hisat_bam) # Step3: run CIRI2 if bed_file: logger.info('Using user-provided circRNA bed file: {}'.format(bed_file)) else: if circ_file or circ_tool: if circ_file and circ_tool: logger.info('Using predicted circRNA results from {}: {}'.format(circ_tool, circ_file)) circ_parser = CIRCparser(circ_file, circ_tool) else: sys.exit('--circ and --tool must be provided in the same time!') else: logger.info('No circRNA information provided, run CIRI2 for junction site prediction ..') bwa_sam = pipeline.run_bwa(log_file, thread, reads, outdir, prefix) ciri_file = pipeline.run_ciri(log_file, thread, bwa_sam, outdir, prefix) circ_parser = CIRCparser(ciri_file, 'CIRI2') bed_file = '{}/{}.bed'.format(outdir, prefix) circ_parser.convert(bed_file) # Step4: estimate circRNA expression level out_file = circ.proc(log_file, thread, bed_file, hisat_bam, rnaser_file, reads, outdir, prefix, anchor, lib_type) # Remove temporary files pipeline.clean_tmp(outdir, prefix) logger.info('circRNA Expression profile: {}'.format(os.path.basename(out_file))) logger.info('Finished!') if __name__ == '__main__': main() <file_sep>/CIRIquant/utils.py #! /usr/bin/env python # -*- encoding:utf-8 -*= import os import sys import logging LOGGER = logging.getLogger('CIRIquant') BWA = None HISAT2 = None STRINGTIE = None SAMTOOLS = None FASTA = None GTF = None BWA_INDEX = None HISAT_INDEX = None class ConfigError(Exception): pass class PipelineError(Exception): pass def subprocess_setup(): """ Python installs a SIGPIPE handler by default. This is usually not what non-Python subprocesses expect """ import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) def get_thread_num(thread): from multiprocessing import cpu_count cores = cpu_count() workers = min(cores, int(thread)) LOGGER.info('{} CPU cores availble, using {}'.format(cores, workers)) return workers def check_file(file_name, is_required=True): if os.path.exists(file_name) and os.path.isfile(file_name): return os.path.abspath(file_name) else: if is_required: raise ConfigError('File: {}, not found'.format(file_name)) else: return None def check_dir(dir_name): if os.path.exists(dir_name): if os.path.isdir(dir_name): pass # Output directory already exists else: raise ConfigError('Directory: {}, clashed with existed files'.format(dir_name)) else: os.mkdir(dir_name) return os.path.abspath(dir_name) def check_config(config_file): import yaml global BWA, HISAT2, STRINGTIE, SAMTOOLS global FASTA, GTF, BWA_INDEX, HISAT_INDEX # check config reliability LOGGER.info('Loading config file: {}'.format(os.path.basename(config_file))) with open(config_file, 'r') as infile: config = yaml.load(infile, Loader=yaml.BaseLoader) # check all tools if 'tools' not in config: raise ConfigError('Path of required software must be provided!') for i in 'bwa', 'hisat2', 'stringtie', 'samtools': if i not in config['tools']: raise ConfigError('Tool: {} need to be specificed'.format(i)) globals()[i.upper()] = check_file(config['tools'][i]) # check required software version check_samtools_version(config['tools']['samtools']) # check reference and index for i in 'fasta', 'gtf': if i not in config['reference']: raise ConfigError('Reference {} need to be specified'.format(i)) globals()[i.upper()] = check_file(config['reference'][i]) if 'bwa_index' not in config['reference']: raise ConfigError('BWA index not found') BWA_INDEX = os.path.splitext(check_file(config['reference']['bwa_index'] + '.bwt'))[0] if 'hisat_index' not in config['reference']: raise ConfigError('HISAT2 index not found') short_index = check_file(config['reference']['hisat_index'] + '.1.ht2', is_required=False) long_index = check_file(config['reference']['hisat_index'] + '.1.ht2l', is_required=False) if short_index: HISAT_INDEX = os.path.splitext(os.path.splitext(short_index)[0])[0] elif long_index: HISAT_INDEX = os.path.splitext(os.path.splitext(long_index)[0])[0] else: raise ConfigError('Could not find hisat2 index with suffix: *.[1-8].ht2 or *.[1-8].ht2l, please check your configuration') return config['name'] def check_samtools_version(samtools): from commands import getoutput from distutils.version import LooseVersion version = getoutput('{} --version'.format(samtools).split('\n')[0].split(' ')[1]) if version and cmp(LooseVersion(version), LooseVersion('1.9')) < 0: raise ConfigError('samtools version too low, 1.9 required') return 1 def convert_bed(ciri_file): out_file = ciri_file + '.bed' with open(ciri_file, 'r') as f, open(out_file, 'w') as out: f.readline() for line in f: content = line.rstrip().split('\t') chrom, start, end = content[1:4] strand = content[10] out.write('\t'.join([chrom, start, end, '{}:{}|{}'.format(chrom, start, end), '.', strand]) + '\n') return out_file TOOLS = ['CIRI2', 'CIRCexplorer2', 'DCC', 'KNIFE', 'MapSplice', 'UROBORUS', 'circRNA_finder', 'find_circ'] class CIRCparser(object): """convert circRNA prediction results to bed file""" def __init__(self, circ, tool): self.circ = circ if tool not in TOOLS: sys.exit('Tool: {} not in supported list, please manually convert the circRNA coordinates to bed file.') self.tool = tool def _ciri2(self): circ_data = [] with open(self.circ, 'r') as f: f.readline() for line in f: content = line.rstrip().split('\t') chrom, start, end, strand = content[1], int(content[2]), int(content[3]), content[10] circ_data.append([chrom, start, end, strand]) return circ_data def _circexplorer2(self): circ_data = [] with open(self.circ, 'r') as f: for line in f: content = line.rstrip().split('\t') chrom, start, end, strand = content[0], int(content[1]) + 1, int(content[2]), content[5] circ_data.append([chrom, start, end, strand]) return circ_data def _dcc(self): circ_data = [] with open(self.circ, 'r') as f: for line in f: content = line.rstrip().split('\t') circ_data.append([content[0], int(content[1]), int(content[2]), content[3]]) return circ_data def _knife(self): circ_data = [] with open(self.circ, 'r') as f: for line in f: content = line.rstrip().split('\t') contig, start, end, junction_type, strand = content[0].split('|') if junction_type == 'reg': continue if float(content[2]) < 0.9 and float(content[4]) < 0.9: continue st = int(end.split(':')[1]) if strand == '+' else int(start.split(':')[1]) en = int(start.split(':')[1]) if strand == '+' else int(end.split(':')[1]) circ_data.append([contig, st, en, strand]) return circ_data def _mapsplice(self): circ_data = [] with open(self.circ, 'r') as f: for line in f: content = line.rstrip().split('\t') contig1, contig2 = content[0].split('~') strand1, strand2 = content[5] if contig1 != contig2 or strand1 != strand2: continue if strand1 == '-': circ_data.append([contig1, int(content[1]), int(content[2]), strand1]) else: circ_data.append([contig1, int(content[2]), int(content[1]), strand1]) return circ_data def _uroborus(self): circ_data = [] with open(self.circ, 'r') as f: for line in f: content = line.rstrip().split('\t') chrom, start, end, strand = content[0], int(content[1]) + 1, int(content[2]), content[3] circ_data.append([chrom, start, end, strand]) return circ_data def _circRNA_finder(self): circ_data = [] with open(self.circ, 'r') as f: for line in f: content = line.rstrip().split('\t') chrom, start, end, strand = content[0], int(content[1]) + 1, int(content[2]), content[5] circ_data.append([chrom, start, end, strand]) return circ_data def _find_circ(self): circ_data = [] with open(self.circ, 'r') as f: for line in f: content = line.rstrip().split('\t') chrom, start, end, strand = content[0], int(content[1]) + 1, int(content[2]), content[5] circ_data.append([chrom, start, end, strand]) return circ_data # def _segemehl(self): # circ_data = [] # with open(self.circ, 'r') as f: # for line in f: # content = line.rstrip().split('\t') # chrom, start, end = content[0], int(content[1]) + 1, int(content[2]) # circ_data.append([chrom, start, end, '+']) # return circ_data def convert(self, out_file): circ_data = getattr(self, '_' + self.tool.lower())() with open(out_file, 'w') as out: for chrom, start, end, strand in circ_data: tmp_line = [chrom, start, end, '{}:{}|{}'.format(chrom, start, end), '.', strand] out.write('\t'.join([str(x) for x in tmp_line]) + '\n') return out_file <file_sep>/CIRIquant/replicate.py #! /usr/bin/env python # -*- encoding:utf-8 -*= import os import sys import argparse import logging import subprocess from version import __version__ LOGGER = logging.getLogger('CIRI_DE') def main(): global LOGGER from logger import get_logger from utils import check_file # Init argparser parser = argparse.ArgumentParser(prog="prep_CIRIquant") parser.add_argument('--lib', dest='lib', metavar='FILE', required=True, help='library information') parser.add_argument('--bsj', dest='bsj', metavar='FILE', required=True, help='circRNA expression matrix', ) parser.add_argument('--gene', dest='gene', metavar='FILE', required=True, help='gene expression matrix', ) parser.add_argument('--out', dest='out', metavar='FILE', required=True, help='output result of differential expression analysis', ) # Optional parameters args = parser.parse_args() LOGGER = get_logger('CIRI_DE', None, False) lib_path = os.path.dirname(os.path.split(os.path.realpath(__file__))[0]) + '/libs' os.environ['PATH'] = lib_path + ':' + os.environ['PATH'] os.chmod(lib_path + '/CIRI_DE.R', 0o755) # Load GTF lib_file = check_file(args.lib) bsj_file = check_file(args.bsj) gene_file = check_file(args.gene) out_file = os.path.abspath(args.out) LOGGER.info('Library information: {}'.format(lib_file)) LOGGER.info('circRNA expression matrix: {}'.format(bsj_file)) LOGGER.info('gene expression matrix: {}'.format(gene_file)) LOGGER.info('Output DE results: {}'.format(out_file)) de_cmd = 'CIRI_DE.R --lib={} --bsj={} --gene={} --out={}'.format(lib_file, bsj_file, gene_file, out_file) subprocess.call(de_cmd, shell=True) LOGGER.info('Finished!') if __name__ == '__main__': main() <file_sep>/CIRIquant/circ.py #! /usr/bin/env python # -*- encoding:utf-8 -*- import os import sys import re import logging import pysam import time import subprocess from multiprocessing import Pool from collections import defaultdict from itertools import izip_longest import utils LOGGER = logging.getLogger('CIRIquant') PREFIX = re.compile(r'(.+)[/_-][12]') class BedParser(object): """ Class for parsing circRNA information in bed file """ def __init__(self, content): self.chrom = content[0] self.start = int(content[1]) self.end = int(content[2]) self.circ_id = content[3] self.strand = content[5] self.length = self.end - self.start + 1 def load_bed(fname): """ Load Back-Spliced Junction Sites in bed file Parameters ----- fname : str input file name Returns ----- dict divide all circRNAs into different chromsomes """ circ_info = defaultdict(dict) with open(fname, 'r') as f: for line in f: content = line.rstrip().split('\t') parser = BedParser(content) circ_info[parser.chrom][parser.circ_id] = parser return circ_info def update_info(circ_info, rnaser_file): """ Add information of RNase R circRNAs """ circ_exp = {} LOGGER.info('RNase R file: {}'.format(rnaser_file)) with open(rnaser_file, 'r') as f: header = {} for line in f: if line.startswith('##'): key, value = line.rstrip().strip('#').split(':') header.update({key: value}) continue content = line.rstrip().split('\t') tmp_parser = GTFParser(content) circ_exp[tmp_parser.attr['circ_id']] = { 'bsj': float(tmp_parser.attr['bsj']), 'fsj': float(tmp_parser.attr['fsj']), 'ratio': 2 * float(tmp_parser.attr['bsj']) / (2 * float(tmp_parser.attr['bsj']) + float(tmp_parser.attr['fsj'])) } parser = BedParser([ tmp_parser.chrom, tmp_parser.start, tmp_parser.end, tmp_parser.attr['circ_id'], '.', tmp_parser.strand, ]) if parser.chrom in circ_info and parser.circ_id in circ_info[parser.chrom]: continue circ_info[parser.chrom].update({parser.circ_id: parser}) return circ_exp, (int(header['Total_Reads']), int(header['Mapped_Reads']), int(header['Circular_Reads'])) def load_fai(fname): """ Load fai index of fasta created by samtools Parameters ----- fname : str input fai file name Returns ----- dict chromsome and start / end position in file """ faidx = {} with open(fname, 'r') as f: for line in f: content = line.rstrip().split('\t') chrom, length, start, eff_length, line_length = content shift_length = int(length) * int(line_length) / int(eff_length) faidx[chrom] = [int(start), shift_length] return faidx def extract_seq(fasta, start, length): """ Extract sequence from fasta according to given position Parameters ----- fasta : str file name of fasta start : int offset of chrosome length : int length of chromsome sequence Returns ----- str sequence from start to start + length """ with open(fasta, 'r') as f: f.seek(start, 0) seq = f.read(length) seq = re.sub('\n', '', seq) return seq def generate_index(log_file, circ_info, circ_fasta): """ Generate pseudo circular index Parameters ----- log_file : str file name of log file, used for subprocess.PIPE circ_info : dict back-spliced junction sites circ_fasta : output fasta file name Returns ----- dict chromosomes used in BSJ sites """ from logger import ProgressBar fai = utils.FASTA + '.fai' if not os.path.exists(fai): LOGGER.debug('Indexing FASTA') index_cmd = '{} faidx {}'.format(utils.SAMTOOLS, utils.FASTA) with open(log_file, 'a') as log: LOGGER.debug(index_cmd) subprocess.call(index_cmd, shell=True, stderr=log, stdout=log) fasta_index = load_fai(fai) LOGGER.info('Extract circular sequence') prog = ProgressBar() prog.update(0) cnt = 0 with open(circ_fasta, 'w') as out: for chrom in sorted(circ_info.keys()): prog.update(100 * cnt / len(circ_info)) cnt += 1 if chrom not in fasta_index: sys.exit('Unconsistent chromosome id: {}'.format(chrom)) chrom_start, chrom_length = fasta_index[chrom] chrom_seq = extract_seq(utils.FASTA, chrom_start, chrom_length) chrom_circ = circ_info[chrom] for circ_id in chrom_circ: parser = chrom_circ[circ_id] circ_seq = chrom_seq[parser.start - 1:parser.end] * 2 if circ_seq.count('N') > len(circ_seq) * 0.5 or len(circ_seq) == 0: continue out.write('>{}'.format(parser.circ_id) + '\n') out.write(circ_seq + '\n') prog.update(100) return fasta_index def build_index(log_file, thread, pseudo_fasta, outdir, prefix): """ Build hisat2 index for pseudo circular index Returns ----- str index file name used in denovo mapping """ LOGGER.info('Building circular index ..') denovo_index = '{}/circ/{}_index'.format(outdir, prefix) build_cmd = '{}-build -p {} -f {} {}'.format( utils.HISAT2, thread, pseudo_fasta, denovo_index ) with open(log_file, 'a') as log: LOGGER.debug(build_cmd) subprocess.call(build_cmd, shell=True, stderr=log, stdout=log) return denovo_index def denovo_alignment(log_file, thread, reads, outdir, prefix): """ Call hisat2 to read re-alignment Returns ----- str Output bam file """ LOGGER.info('De novo alignment for circular RNAs ..') denovo_bam = '{}/circ/{}_denovo.bam'.format(outdir, prefix) sorted_bam = '{}/circ/{}_denovo.sorted.bam'.format(outdir, prefix) align_cmd = '{} -p {} --dta -q -x {}/circ/{}_index -1 {} -2 {} | {} view -bS > {}'.format( utils.HISAT2, thread, outdir, prefix, reads[0], reads[1], utils.SAMTOOLS, denovo_bam, ) sort_cmd = '{} sort --threads {} -o {} {}'.format( utils.SAMTOOLS, thread, sorted_bam, denovo_bam, ) index_cmd = '{} index -@ {} {}'.format( utils.SAMTOOLS, thread, sorted_bam, ) with open(log_file, 'a') as log: LOGGER.debug(align_cmd) subprocess.call(align_cmd, shell=True, stderr=log, stdout=log) LOGGER.debug(sort_cmd) subprocess.call(sort_cmd, shell=True, stderr=log, stdout=log) LOGGER.debug(index_cmd) subprocess.call(index_cmd, shell=True, stderr=log, stdout=log) # wait for samtools index to correct time stamp time.sleep(5) return sorted_bam def grouper(iterable, n, fillvalue=None): """ Collect data info fixed-length chunks or blocks grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx """ args = [iter(iterable)] * n return izip_longest(*args, fillvalue=None) def proc_denovo_bam(bam_file, thread, circ_info, threshold, lib_type): """ Extract BSJ reads in denovo mapped bam file Returns ----- dict query_name -> mate_id -> pysam.AlignSegment """ LOGGER.info('Detecting reads containing Back-splicing signals') sam = pysam.AlignmentFile(bam_file, 'rb') header = sam.header['SQ'] sam.close() pool = Pool(thread, denovo_initializer, (bam_file, circ_info, threshold, )) jobs = [] chunk_size = max(500, len(header) / thread + 1) for circ_chunk in grouper(header, chunk_size): jobs.append(pool.apply_async(denovo_worker, (circ_chunk, lib_type, ))) pool.close() pool.join() cand_reads = defaultdict(dict) for job in jobs: tmp_cand = job.get() for read_id, mate_id, circ_id, blocks, cigartuples in tmp_cand: cand_reads[read_id][mate_id] = (circ_id, blocks, cigartuples) return cand_reads BAM = None THRESHOLD = None CIRC = None def denovo_initializer(infile, circ_info, threshold): """ Initializer for passing bam file name """ global BAM, CIRC, THRESHOLD BAM, CIRC, THRESHOLD = infile, circ_info, threshold def denovo_worker(circ_chunk, lib_type): """ Find candidate reads with junction signal Parameters ----- circ_chunk : list list of Pysam header to process Returns ----- list pysam.AlignedSegment, candidate reads with junction signal """ #TODO: add support for stranded specific RNA_seq libraries sam = pysam.AlignmentFile(BAM, 'rb') cand_reads = [] for d in circ_chunk: if d is None: continue circ_id, junc_site = d['SN'], int(d['LN']) / 2 contig = circ_id.split(':')[0] parser = CIRC[contig][circ_id] tmp_cand = [] circ_reads = defaultdict(dict) for read in sam.fetch(circ_id, multiple_iterators=True): if read.is_unmapped or read.is_secondary or read.is_supplementary: continue read_strand = '-' if read.is_reverse else '+' if lib_type == 0: pass elif lib_type == 1: if read.is_read1 - read.is_read2 > 0: if read_strand != parser.strand: continue else: if read_strand == parser.strand: continue elif lib_type == 2: if read.is_read1 - read.is_read2 > 0: if read_strand == parser.strand: continue else: if read_strand != parser.strand: continue circ_reads[query_prefix(read.query_name)][read.is_read1 - read.is_read2] = 1 if read.mapping_quality <= 10: continue if read.get_overlap(junc_site - THRESHOLD, junc_site + THRESHOLD) >= THRESHOLD * 2: tmp_cand.append((read.query_name, read.is_read1 - read.is_read2, circ_id, read.get_blocks(), read.cigartuples)) for qname, mate_id, circ_id, blocks, cigartuples in tmp_cand: if -1 * mate_id in circ_reads[query_prefix(qname)]: cand_reads.append((qname, mate_id, circ_id, blocks, cigartuples)) sam.close() return cand_reads def proc_genome_bam(bam_file, thread, circ_info, cand_reads, threshold, tmp_dir): """ Extract FSJ reads and check BSJ reads alignment information Returns ----- dict bsj reads of circRNAs, pair_id -> mate_id -> circ_id dict fsj reads of circRNAs, pair_id -> mate_id -> circ_id """ import cPickle LOGGER.info('Detecting FSJ reads from genome alignment file') sam = pysam.AlignmentFile(bam_file, 'rb') header = sam.header['SQ'] sam.close() pool = Pool(thread, genome_initializer, (bam_file, circ_info, cand_reads, threshold)) jobs = [] for chrom_info in header: jobs.append(pool.apply_async(genome_worker, (chrom_info['SN'], tmp_dir, ))) pool.close() pool.join() fp_bsj = defaultdict(dict) fsj_reads = defaultdict(dict) cand_to_genome = [] for job in jobs: tmp = job.get() if tmp is None: continue res = tmp if isinstance(tmp, dict) else cPickle.load(open(tmp, 'rb')) chrom_fp_bsj, chrom_fsj, chrom_cand = res['fp_bsj'], res['fsj_reads'], res['cand_to_genome'] for pair_id, mate_id in chrom_fp_bsj: fp_bsj[pair_id][mate_id] = 1 for pair_id, mate_id, circ_id in chrom_fsj: fsj_reads[pair_id][mate_id] = circ_id cand_to_genome += chrom_cand circ_bsj = defaultdict(dict) circ_fsj = defaultdict(dict) for pair_id in cand_reads: for mate_id, (circ_id, blocks, cigartuples) in cand_reads[pair_id].iteritems(): if pair_id in fp_bsj and mate_id in fp_bsj[pair_id]: continue circ_bsj[circ_id].update({query_prefix(pair_id): 1}) for pair_id in fsj_reads: for mate_id, circ_id in fsj_reads[pair_id].iteritems(): if pair_id in cand_reads and mate_id in cand_reads[pair_id] and not (pair_id in fp_bsj and mate_id in fp_bsj[pair_id]): continue circ_fsj[circ_id].update({query_prefix(pair_id): 1}) # sam = pysam.AlignmentFile(bam_file, 'rb') # cand_sam = pysam.AlignmentFile(bam_file + '.fsj', 'w', template=sam) # cand_sam.close() # sam.close() # # with open(bam_file + '.fsj', 'w') as out: # for read in cand_to_genome: # out.write(read + '\n') return circ_bsj, circ_fsj BSJ = None def genome_initializer(bam_file, circ_info, cand_bsj, threshold): """ Initializer for passing bam file name and circRNA_info """ global BAM, CIRC, THRESHOLD, BSJ BAM, CIRC, BSJ, THRESHOLD = bam_file, circ_info, cand_bsj, threshold def genome_worker(chrom, tmp_dir): """ Find FSJ reads and re-check BSJ reads Parameters ----- chrom : str chromosme or scaffold name for process Returns ----- list false positive reads information, (query_name, mate_id) list fsj_reads of circRNAs, (query_name, mate_id, circ_id) """ import cPickle if chrom not in CIRC: return None sam = pysam.AlignmentFile(BAM, 'rb') cand_to_genome = [] fp_bsj = [] for read in sam.fetch(chrom, multiple_iterators=True): # If Reads is bsj candidate if read.is_unmapped: continue if read.query_name not in BSJ or read.is_read1 - read.is_read2 not in BSJ[read.query_name]: continue circ_id, blocks, cigartuples = BSJ[read.query_name][read.is_read1 - read.is_read2] cand_to_genome.append(read.to_string()) # check alignment against reference genome qual_filter = 1 if mapping_quality(blocks) <= mapping_quality(read.get_blocks()) + 5 else 0 linear_filter = 1 if is_linear(read.cigartuples[0]) and is_linear(read.cigartuples[-1]) else 0 align_filter = 1 if read.mapping_quality <= 10 or read.is_secondary or read.is_supplementary else 0 if qual_filter or linear_filter or align_filter: fp_bsj.append((read.query_name, read.is_read1 - read.is_read2)) fsj_reads = [] for circ_id, parser in CIRC[chrom].iteritems(): # FSJ across start site for read in sam.fetch(region='{0}:{1}-{1}'.format(chrom, parser.start)): if read.is_unmapped or read.is_supplementary: continue if read.mapping_quality <= 10: continue if not read.get_overlap(parser.start - 1, parser.start + THRESHOLD - 1) >= THRESHOLD: continue if is_mapped(read.cigartuples[0]) and is_mapped(read.cigartuples[-1]): fsj_reads.append((read.query_name, read.is_read1 - read.is_read2, circ_id)) for read in sam.fetch(region='{0}:{1}-{1}'.format(chrom, parser.end)): if read.is_unmapped or read.is_supplementary: continue if read.mapping_quality <= 10: continue if not read.get_overlap(parser.end - THRESHOLD, parser.end) >= THRESHOLD: continue if is_mapped(read.cigartuples[0]) and is_mapped(read.cigartuples[-1]): fsj_reads.append((read.query_name, read.is_read1 - read.is_read2, circ_id)) sam.close() res = {'fp_bsj': fp_bsj, 'fsj_reads': fsj_reads, 'cand_to_genome': cand_to_genome} res_to_string = cPickle.dumps(res, 0) if sys.getsizeof(res_to_string) > 1024 * 1024 * 1024: pkl_file = "{}/{}.pkl".format(tmp_dir, chrom) cPickle.dump(res, open(pkl_file, "wb"), -1) return pkl_file return res def mapping_quality(blocks): return sum([j - i for i, j in blocks]) def is_mapped(cigar_tuple): """ Whether end of alignment segment is a mapped end Parameters ----- cigar_tuple : tuple of cigar Returns ----- int 1 for linear end, 0 for ambiguous end """ if cigar_tuple[0] == 0 or cigar_tuple[1] <= 10: return 1 else: return 0 def is_linear(cigar_tuple): """ Whether end of alignment segment is a linear end Parameters ----- cigar_tuple : tuple of cigar Returns ----- int 1 for linear end, 0 for ambiguous end """ if cigar_tuple[0] == 0 and cigar_tuple[1] >= 5: return 1 else: return 0 def query_prefix(query_name): """ Get pair id without mate id marker Paramters ----- read : pysam.AlignedSegment Returns ----- str mate id of segment """ prefix_m = PREFIX.search(query_name) prefix = prefix_m.group(1) if prefix_m else query_name return prefix def proc(log_file, thread, circ_file, hisat_bam, rnaser_file, reads, outdir, prefix, anchor, lib_type): """ Build pseudo circular reference index and perform reads re-alignment Extract BSJ and FSJ reads from alignment results Returns ----- str output file name """ from utils import check_dir circ_dir = '{}/circ'.format(outdir) check_dir(circ_dir) circ_fasta = '{}/circ/{}_index.fa'.format(outdir, prefix) circ_info = load_bed(circ_file) if rnaser_file: LOGGER.info('Loading RNase R results') rnaser_exp, rnaser_stat = update_info(circ_info, rnaser_file) # extract fasta file for reads alignment generate_index(log_file, circ_info, circ_fasta) # hisat2-build index denovo_index = build_index(log_file, thread, circ_fasta, outdir, prefix) LOGGER.debug('De-novo index: {}'.format(denovo_index)) # hisat2 de novo alignment for candidate reads denovo_bam = denovo_alignment(log_file, thread, reads, outdir, prefix) LOGGER.debug('De-novo bam: {}'.format(denovo_bam)) # Find BSJ and FSJ informations cand_bsj = proc_denovo_bam(denovo_bam, thread, circ_info, anchor, lib_type) bsj_reads, fsj_reads = proc_genome_bam(hisat_bam, thread, circ_info, cand_bsj, anchor, circ_dir) total_reads, mapped_reads = bam_stat(hisat_bam) circ_reads = sum([len(bsj_reads[i]) for i in bsj_reads]) * 2 sample_stat = (total_reads, mapped_reads, circ_reads) sample_exp = expression_level(circ_info, bsj_reads, fsj_reads) # circRNA annotation header = [ 'Sample: {}'.format(prefix), 'Total_Reads: {}'.format(total_reads), 'Mapped_Reads: {}'.format(mapped_reads), 'Circular_Reads: {}'.format(circ_reads), ] out_file = '{}/{}.gtf'.format(outdir, prefix) if rnaser_file: import coeff tmp_header, circ_exp = coeff.correction(sample_exp, sample_stat, rnaser_exp, rnaser_stat) header += tmp_header else: circ_exp = sample_exp from version import __version__ header += ['version: {}'.format(__version__), ] gtf_info = index_annotation(utils.GTF) format_output(circ_info, circ_exp, sample_stat, header, gtf_info, out_file) return out_file def expression_level(circ_info, bsj_reads, fsj_reads): LOGGER.info('Merge bsj and fsj results') circ_exp = defaultdict(dict) bsj_ids = {} for chrom in circ_info: for circ_id in circ_info[chrom]: bsj = len(bsj_reads[circ_id]) if circ_id in bsj_reads else 0 fsj = len(fsj_reads[circ_id]) if circ_id in fsj_reads else 0 if bsj == 0 and fsj == 0: continue bsj_ids[circ_id] = bsj_reads[circ_id].keys() junc = 2.0 * bsj / (2.0 * bsj + fsj) circ_exp[circ_id] = {'bsj': bsj, 'fsj': fsj, 'ratio': junc} return circ_exp def bam_stat(bam_file): """ Stat of bam file Returns ----- int number of total reads int number of mapped reads """ sam = pysam.AlignmentFile(bam_file, 'rb') total = sam.count(read_callback=total_callback, until_eof=True) sam.close() sam = pysam.AlignmentFile(bam_file, 'rb') unmapped = sam.count(read_callback=unmapped_callback, until_eof=True) sam.close() return total, total - unmapped def unmapped_callback(read): """ callback for counting unmapped reads """ return read.is_unmapped or read.mate_is_unmapped and not read.is_supplementary and not read.is_secondary def total_callback(read): """ callback for counting total reads """ return not read.is_supplementary and not read.is_secondary def format_output(circ_info, circ_exp, sample_stat, header, gtf_index, outfile): """ Output bsj information of circRNA expression levels """ LOGGER.info('Output circRNA expression values') with open(outfile, 'w') as out: for h in header: out.write('##' + h + '\n') for chrom in sorted(circ_info.keys(), key=by_chrom): for circ_id in sorted(circ_info[chrom].keys(), cmp=by_circ, key=lambda x:circ_info[chrom][x]): if circ_id not in circ_exp or circ_exp[circ_id]['bsj'] == 0: continue parser = circ_info[chrom][circ_id] strand = parser.strand tmp_line = [ chrom, 'CIRIquant', 'circRNA', parser.start, parser.end, '{:.4f}'.format(2 * 1000.0 * 1000.0 * circ_exp[circ_id]['bsj'] / sample_stat[1]), strand, '.', ] field = circRNA_attr(gtf_index, parser) tmp_attr = 'circ_id "{}"; circ_type "{}"; bsj {:.3f}; fsj {:.3f}; junc_ratio {:.3f};'.format( circ_id, field['circ_type'] if field else "Unknown", circ_exp[circ_id]['bsj'], circ_exp[circ_id]['fsj'], circ_exp[circ_id]['ratio'], ) for key in 'rnaser_bsj', 'rnaser_fsj': if key in circ_exp[circ_id]: tmp_attr += ' {} {:.3f};'.format(key, circ_exp[circ_id][key]) for key in 'gene_id', 'gene_name', 'gene_type': if key in field: tmp_attr += ' {} "{}";'.format(key, field[key]) tmp_line.append(tmp_attr) out.write('\t'.join([str(x) for x in tmp_line]) + '\n') return 1 def by_chrom(x): """ Sort by chromosomes """ chrom = x if x.startswith('chr'): chrom = chrom.strip('chr') try: chrom = int(chrom) except ValueError as e: pass return chrom def by_circ(x, y): """ Sort circRNAs by the start and end position """ return x.end - y.end if x.start == y.start else x.start - y.start class GTFParser(object): """ Class for parsing annotation gtf """ def __init__(self, content): self.chrom = content[0] self.source = content[1] self.type = content[2] self.start, self.end = int(content[3]), int(content[4]) self.strand = content[6] self.attr_string = content[8] @property def attr(self): """ Parsing attribute column in gtf file """ field = {} for attr_values in [re.split(r'[\s=]+', i.strip()) for i in self.attr_string.split(';')[:-1]]: key, value = attr_values[0], attr_values[1:] field[key] = ' '.join(value).strip('"') return field def index_annotation(gtf): """ Generate binned index for element in gtf """ LOGGER.info('Loading annotation gtf ..') gtf_index = defaultdict(dict) with open(gtf, 'r') as f: for line in f: if line.startswith('#'): continue content = line.rstrip().split('\t') # only include gene and exon feature for now if content[2] not in ['gene', 'exon']: continue parser = GTFParser(content) # if 'gene_biotype' in parser.attr and parser.attr['gene_biotype'] in ['lincRNA', 'pseudogene']: # continue # if 'gene_type' in parser.attr and parser.attr['gene_type'] in ['lincRNA', 'pseudogene']: # continue start_div, end_div = parser.start / 500, parser.end / 500 for i in xrange(start_div, end_div + 1): gtf_index[parser.chrom].setdefault(i, []).append(parser) return gtf_index def circRNA_attr(gtf_index, circ): """ annotate circRNA information """ if circ.chrom not in gtf_index: LOGGER.warn('chrom of contig "{}" not in annotation gtf, please check'.format(circ.chrom)) return {} start_div, end_div = circ.start / 500, circ.end / 500 host_gene = {} start_element = defaultdict(list) end_element = defaultdict(list) for x in xrange(start_div, end_div + 1): if x not in gtf_index[circ.chrom]: continue for element in gtf_index[circ.chrom][x]: # start site if element.start <= circ.start <= element.end and element.strand == circ.strand: start_element[element.type].append(element) # end site if element.start <= circ.end <= element.end and element.strand == circ.strand: end_element[element.type].append(element) # if element.type != 'gene': # continue if element.end < circ.start or circ.end < element.start: continue if element.attr['gene_id'] not in host_gene: host_gene[element.attr['gene_id']] = element circ_type = {} forward_host_gene = [] antisense_host_gene = [] if len(host_gene) > 0: for gene_id in host_gene: if host_gene[gene_id].strand == circ.strand: forward_host_gene.append(host_gene[gene_id]) if 'exon' in start_element and 'exon' in end_element: circ_type['exon'] = 1 else: circ_type['intron'] = 1 else: antisense_host_gene.append(host_gene[gene_id]) circ_type['antisense'] = 1 else: circ_type['intergenic'] = 1 if len(forward_host_gene) > 1: circ_type['gene_intergenic'] = 1 field = {} if 'exon' in circ_type: field['circ_type'] = 'exon' elif 'intron' in circ_type: field['circ_type'] = 'intron' # elif 'gene_intergenic' in circ_type: # field['circ_type'] = 'gene_intergenic' elif 'antisense' in circ_type: field['circ_type'] = 'antisense' else: field['circ_type'] = 'intergenic' if len(forward_host_gene) == 1: if 'gene_id' in forward_host_gene[0].attr: field['gene_id'] = forward_host_gene[0].attr['gene_id'] if 'gene_name' in forward_host_gene[0].attr: field['gene_name'] = forward_host_gene[0].attr['gene_name'] if 'gene_type' in forward_host_gene[0].attr: field['gene_type'] = forward_host_gene[0].attr['gene_type'] elif 'gene_biotype' in forward_host_gene[0].attr: field['gene_type'] = forward_host_gene[0].attr['gene_biotype'] else: pass elif len(forward_host_gene) > 1: tmp_gene_id = [] tmp_gene_name = [] tmp_gene_type = [] for x in forward_host_gene: if 'gene_id' in x.attr: tmp_gene_id.append(x.attr['gene_id']) if 'gene_name' in x.attr: tmp_gene_name.append(x.attr['gene_name']) if 'gene_type' in x.attr: tmp_gene_type.append(x.attr['gene_type']) elif 'gene_biotype' in x.attr: tmp_gene_type.append(x.attr['gene_biotype']) else: pass if len(tmp_gene_id) > 0: field['gene_id'] = ','.join(tmp_gene_id) if len(tmp_gene_name) > 0: field['gene_name'] = ','.join(tmp_gene_name) if len(tmp_gene_type) > 0: field['gene_type'] = ','.join(tmp_gene_type) elif field['circ_type'] == 'antisense' and len(antisense_host_gene) > 0: tmp_gene_id = [] tmp_gene_name = [] tmp_gene_type = [] for x in antisense_host_gene: if 'gene_id' in x.attr: tmp_gene_id.append(x.attr['gene_id']) if 'gene_name' in x.attr: tmp_gene_name.append(x.attr['gene_name']) if 'gene_type' in x.attr: tmp_gene_type.append(x.attr['gene_type']) elif 'gene_biotype' in x.attr: tmp_gene_type.append(x.attr['gene_biotype']) else: pass if len(tmp_gene_id) > 0: field['gene_id'] = ','.join(tmp_gene_id) if len(tmp_gene_name) > 0: field['gene_name'] = ','.join(tmp_gene_name) if len(tmp_gene_type) > 0: field['gene_type'] = ','.join(tmp_gene_type) else: pass return field <file_sep>/CIRIquant/coeff.py #! /usr/bin/env python # -*- encoding:utf-8 -*- import logging import numpy as np LOGGER = logging.getLogger('CIRIquant') def correction(sample_exp, sample_stat, rnaser_exp, rnaser_stat): """ RNase R correction """ LOGGER.info('RNase R treatment coefficient correction') header = [] circ_exp = {} train_index = [] overlap_index = [] for i in sample_exp: if sample_exp[i]['bsj'] <= 1: continue if i not in rnaser_exp or rnaser_exp[i]['bsj'] <= 5: continue if float(sample_exp[i]['bsj']) / sample_stat[1] >= float(rnaser_exp[i]['bsj']) / rnaser_stat[1]: continue overlap_index.append(i) if sample_exp[i]['ratio'] == 1 or rnaser_exp[i]['ratio'] == 1: continue if sample_exp[i]['ratio'] >= rnaser_exp[i]['ratio']: continue train_index.append(i) if len(overlap_index) == 0 or len(train_index) == 0: LOGGER.warn('No enough overlap circRNAs for correction, skipping this step') return [], sample_exp # Overlap expression constant for BSJ total_median = np.median([sample_exp[i]['bsj'] for i in overlap_index]) rnaser_median = np.median([rnaser_exp[i]['bsj'] for i in overlap_index]) exp_constant = total_median / rnaser_median y_factor = [factor(sample_exp[i]) for i in train_index] y, y_mean = np.transpose(np.matrix(y_factor)), np.median(y_factor) x_factor = [factor(rnaser_exp[i]) for i in train_index] x, x_mean = np.transpose(np.matrix(x_factor)), np.median(x_factor) coef_mean = y_mean / x_mean LOGGER.info('Fitting Model') coef, intercept = fit_model(x, y) LOGGER.info('Generate prior distribution ..') gmm = prior_distribution(x, y) header += [ 'RNaseR_Reads: {}'.format(rnaser_stat[1]), 'Amplification: {}'.format(exp_constant), 'Coef: {}'.format(coef), 'Intercept: {}'.format(intercept), 'N: {}'.format(gmm.n_components), 'W: {}'.format(','.join([str(i) for i in np.round(gmm.weights_, 4)])), 'M: {}'.format(','.join([str(i[0]) for i in np.round(gmm.means_, 4)])), 'SD: {}'.format(','.join([str(i[0][0]) for i in np.round(gmm.covariances_, 4)])), ] for i in rnaser_exp: if i in sample_exp and sample_exp[i]['bsj'] == 0 and rnaser_exp[i]['fsj'] != 0: corrected_bsj = coef_mean * sample_exp[i]['fsj'] * rnaser_exp[i]['bsj'] / rnaser_exp[i]['fsj'] corrected_ratio = junc_ratio(corrected_bsj, sample_exp[i]['fsj']) circ_exp[i] = { 'bsj': corrected_bsj, 'fsj': sample_exp[i]['fsj'], 'ratio': corrected_ratio, 'rnaser_bsj': rnaser_exp[i]['bsj'], 'rnaser_fsj': rnaser_exp[i]['fsj'] } elif i in sample_exp and sample_exp[i]['bsj'] != 0: circ_exp[i] = sample_exp[i] # corrected_bsj = coef_mean * sample_exp[i]['fsj'] * rnaser_exp[i]['bsj'] / rnaser_exp[i]['fsj'] # corrected_ratio = junc_ratio(corrected_bsj, sample_exp[i]['fsj']) # circ_exp[i] = { # 'bsj': corrected_bsj, 'fsj': sample_exp[i]['fsj'], 'ratio': corrected_ratio, # 'rnaser_bsj': rnaser_exp[i]['bsj'], 'rnaser_fsj': rnaser_exp[i]['fsj'] # } else: corrected_bsj = rnaser_exp[i]['bsj'] * exp_constant corrected_fsj = corrected_bsj / (rnaser_exp[i]['bsj'] / rnaser_exp[i]['fsj']) / coef_mean if rnaser_exp[i]['fsj'] != 0 else 0 corrected_ratio = junc_ratio(corrected_bsj, corrected_fsj) circ_exp[i] = { 'bsj': corrected_bsj, 'fsj': corrected_fsj, 'ratio': corrected_ratio, 'rnaser_bsj': rnaser_exp[i]['bsj'], 'rnaser_fsj': rnaser_exp[i]['fsj'], } for i in sample_exp: if i in circ_exp: continue circ_exp[i] = sample_exp[i] return header, circ_exp def junc_ratio(bsj, fsj): return 2.0 * bsj / (2.0 * bsj + fsj) def factor(d): """ Factor """ return d['ratio'] / (1.0 - d['ratio']) def fit_model(x, y): from sklearn import linear_model, model_selection import warnings with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=DeprecationWarning) x_train, x_test, y_train, y_test = model_selection.train_test_split(x, y, test_size=0.4, random_state=0) clf = linear_model.LinearRegression(fit_intercept=True) clf.fit(x_train, y_train) coef = clf.coef_[0][0] try: intercept = clf.intercept_[0] except Exception: intercept = 0 LOGGER.debug('Coefficient: {}'.format(coef)) LOGGER.debug('Intercept: {}'.format(intercept)) LOGGER.debug('R-square: {}'.format(clf.score(x_train, y_train))) LOGGER.debug('Var: {}'.format((np.array(y_test - clf.predict(x_test)) ** 2).sum())) return coef, intercept def prior_distribution(x, y): from sklearn.mixture import GaussianMixture import warnings coeff = y / x with warnings.catch_warnings(): warnings.filterwarnings('ignore', category=DeprecationWarning) models = [GaussianMixture(i).fit(coeff) for i in np.arange(1, 4)] AIC = [m.aic(coeff) for m in models] # BIC = [m.bic(coeff) for m in models] gmm = models[np.argmin(AIC)] return gmm <file_sep>/libs/CIRI_DE.R #!/usr/bin/env Rscript rm(list=ls()) suppressPackageStartupMessages(library(edgeR)) suppressPackageStartupMessages(library(optparse)) # Parse parameters parser <- OptionParser() parser <- add_option(parser, c("--lib"), action="store", default=NA, type='character', help="library csv matrix") parser <- add_option(parser, c("--bsj"), action="store", default=NA, type='character', help="bsj csv matrix") # parser <- add_option(parser, c("--circ"), action="store", default=NA, type='character', # help="circ info matrix") parser <- add_option(parser, c("--gene"), action="store", default=NA, type='character', help="gene count matrix") parser <- add_option(parser, c("--out"), action="store", default=NA, type='character', help="output file") # opt <- parse_args(parser, args = c("--lib=AD_lib.csv", # "--bsj=AD_bsj.csv", # "--gene=AD_gene_count_matrix.csv", # "--out=AD_de.csv")) opt <- parse_args(parser) # main point of program is here, do this whether or not "verbose" is set if (is.na(opt$lib) || is.na(opt$bsj) || is.na(opt$gene) || is.na(opt$out)) { cat("Please specify --lib/--bsj/--gene/--out, refer to the manual for detailed instruction!\n", file=stderr()) quit() } # Load data lib_mtx <- read.csv(opt$lib, row.names = 1) gene_mtx <- read.csv(opt$gene, row.names = 1, check.names=FALSE) gene_mtx <- gene_mtx[,rownames(lib_mtx)] bsj_mtx <- read.csv(opt$bsj, row.names = 1, check.names=FALSE) gene_DGE <- DGEList(counts = gene_mtx, group = lib_mtx$Group) gene_idx <- filterByExpr(gene_DGE) gene_DGE <- gene_DGE[gene_idx, keep.lib.sizes=FALSE] gene_DGE <- calcNormFactors(gene_DGE) if ("Subject" %in% colnames(lib_mtx)) { subject <- factor(lib_mtx$Subject) treat <- factor(lib_mtx$Group, levels=c("C", "T")) design <- model.matrix(~subject + treat) } else { treat <- factor(lib_mtx$Group, levels=c("C", "T")) design <- model.matrix(~treat) } # design <- model.matrix(~factor(lib_mtx$Group)) # gene_DGE <- estimateDisp(gene_DGE, design, robust = TRUE) # gene_fit <- glmFit(gene_DGE, design) # gene_lrt <- glmLRT(gene_fit) # # gene_df <- gene_lrt$table # gene_order <- order(gene_lrt$table$PValue) # gene_df$DE <- decideTestsDGE(gene_lrt) # gene_df <- gene_df[gene_order, ] # gene_df$FDR <- p.adjust(gene_df$PValue, method="fdr") circ_DGE <- DGEList(counts = bsj_mtx, group = lib_mtx$Group, lib.size = gene_DGE$samples[, "lib.size"], norm.factors = gene_DGE$samples[, "norm.factors"]) # circ_idx <- filterByExpr(circ_DGE, min.count=) # circ_DGE <- circ_DGE[circ_idx, , keep.lib.sizes=TRUE] # head(circ_df[rowSums(bsj_mtx >= 2) >= nrow(lib_mtx) / 2,]) circ_DGE <- estimateDisp(circ_DGE, design, robust = TRUE) circ_fit <- glmFit(circ_DGE, design) circ_lrt <- glmLRT(circ_fit) circ_df <- circ_lrt$table circ_order <- order(circ_lrt$table$PValue) circ_df$DE <- as.vector(decideTestsDGE(circ_lrt)) circ_df <- circ_df[circ_order, ] circ_df$FDR <- p.adjust(circ_df$PValue, method="fdr") write.csv(circ_df, file=opt$out, quote = FALSE) <file_sep>/README.md ## CIRIquant [![Build Status](https://travis-ci.com/bioinfo-biols/CIRIquant.svg?branch=master)](https://travis-ci.com/bioinfo-biols/CIRIquant) ![GitHub release (latest by date)](https://img.shields.io/github/v/release/bioinfo-biols/CIRIquant) [![The MIT License](https://img.shields.io/badge/license-MIT-orange.svg)](https://github.com/bioinfo-biols/CIRIquant/blob/master/LICENSE) ![GitHub All Releases](https://img.shields.io/github/downloads/bioinfo-biols/CIRIquant/total) ![SourceForge](https://img.shields.io/sourceforge/dm/ciri/CIRIquant) [![Documentation Status](https://readthedocs.org/projects/ciri-cookbook/badge/?version=latest)](https://ciri-cookbook.readthedocs.io/en/latest/?badge=latest) CIRIquant is a comprehensive analysis pipeline for circRNA detection and quantification in RNA-Seq data ### Documentation Documentation is available online at [https://ciri-cookbook.readthedocs.io/en/latest/](https://ciri-cookbook.readthedocs.io/en/latest/CIRIquant_0_home.html#) ### Author Authors: <NAME>(<EMAIL>), <NAME>(<EMAIL>) Maintainer: <NAME> ### Release Notes - Version 1.1: Added support for stranded library and GFF3 format input. - Version 1.0: The first released version of CIRIquant. ### License The code is released under the MIT License. See the `LICENSE` file for more detail. ### Citing CIRIquant - <NAME>., <NAME>., <NAME>. et al. Accurate quantification of circular RNAs identifies extensive circular isoform switching events. Nat Commun 11, 90 (2020) [doi:10.1038/s41467-019-13840-9](https://doi.org/10.1038/s41467-019-13840-9)
2fdc8ffc291c0e5ea487b73ff6f11247a0237d3e
[ "Markdown", "Python", "Text", "R" ]
12
Text
cleliacort/CIRIquant
a742793386967014cc78078c485ea2cfabce381c
2857b8f20b40f1664ffa10f19f9c20f3cf94eb21
refs/heads/master
<repo_name>browserstack/Galen-BrowserStack<file_sep>/Galen_JavaScript_Tests/BrowserStack.parameterized.js // A Galen-JavaScript test to execute a spec against multiple configurations // Configurations for running the tests this.devices = { // For mobile devices mobile: { tag: "mobile", deviceName: "iPhone 5S", browserName: "iPhone", platform: "MAC", device: "iPhone 5S", browser: "", browser_version: "", os: "", os_version: "", emulator: "true" }, // For desktop browsers desktop: { tag: "desktop", deviceName: "Win-Chrome 43", browserName: "", platform: "", device: "", browser: "Chrome", browser_version: "43", os: "Windows", os_version: "8.1", emulator: "" } }; forAll(devices, function (option) { test("Homepage Test on ${deviceName}", function() { var driver = createGridDriver("http://" + System.getProperty("browserstack.username") + ":" + System.getProperty("browserstack.key") + "@hub.browserstack.com/wd/hub", { desiredCapabilities: { browser: option.browser, browser_version: option.browser_version, os: option.os, os_version: option.os_version, browserName: option.browserName, platform: option.platform, device: option.device, emulator: option.emulator, "browserstack.debug": "true" } }); // Open the test URL driver.get("http://www.google.com/ncr"); // Select the Spec checkLayout(driver, "homepage.gspec", [option.tag]); // Destroy the session driver.quit(); }); });<file_sep>/README.md # Galen-BrowserStack Perform Automated Layout Testing using Galen Framework on BrowserStack. ## BrowserStack BrowserStack is a cross-browser testing tool, to test public websites and protected servers, on a cloud infrastructure of desktop and mobile browsers. For more information visit https://www.browserstack.com. ## Galen Framework Galen is an open-source tool for testing layout and responsive design of web applications. It is also a powerfull functional testing framework. For more information visit http://galenframework.com. ## How to Install Galen * For installing Galen on OSX and Linux visit http://galenframework.com/docs/getting-started-install-galen * For configuring Galen on Windows visit http://mindengine.net/post/2014-01-08-configuring-galen-framework-for-windows ## Run Galen Tests on BrowserStack Just a few things you should ensure before running Galen tests on BrowserStack: * First you need to have an account at BrowserStack ([Sign-up](https://www.browserstack.com/users/sign_in)). The free trial gets you access to 100 minutes of BrowserStack Automate with 5 parallel runs which should be enough for you to try out your Galen tests. * Get your Automate `Username` and `Access Key` from [here](https://www.browserstack.com/accounts/automate), after you login to your account. * Add these credentials to the test files, to point your tests to BrowserStack's Selenium Hub. Here are the two kinds of galen tests which you can run on BrowserStack: #### Galen Specs Using Galen Specs Language you are able to describe any complex layout including different screen sizes or browsers. It's not only easy to write, it is also easy to read if you are unfamiliar with the language. A list of all capabilities for running tests on various BrowserStack platforms can be found [here](https://www.browserstack.com/automate/capabilities). Command to execute the Galen Spec test: ``` galen test BrowserStackTest.test --parallel-suites 2 -Dbrowserstack.username=<USERNANME> -Dbrowserstack.key=<KEY> ``` #### Galen JavaScript Tests With JavaScript tests you are free to invent your own test framework and perform a lot of complex stuff. You can execute tests against a Galen Spec on a single congiguration or parameterize your test to run it against multiple configurations. You also have the flexibility to write functional tests using which you can interact with the browser elements. Command to execute the Galen JavaScript test: ``` galen test BrowserStack.test.js --parallel-suites 2 -Dbrowserstack.username=<USERNANME> -Dbrowserstack.key=<KEY> ``` #### Command line arguments (More information [here](http://galenframework.com/docs/reference-working-in-command-line/#Runningtestsuites)): * _htmlreport_ - path to folder in which Galen should generate html reports * _testngreport_ - path to xml file in which Galen should write testng report * _parallel-suites_ - amount of threads for running tests in parallel * _recursive_ - flag which is used in case you want to search for all .test files recursively in folder * _filter_ - a filter for a test name ## Additional Links * Selenium Testing on BrowserStack - https://www.browserstack.com/automate * Galen Specs Language Guide - http://galenframework.com/docs/reference-galen-spec-language-guide * Galen JavaScript Test Guide - http://galenframework.com/docs/reference-javascript-tests-guide
9743e2a76d139ad848e034eaa2a5671c9daf4048
[ "JavaScript", "Markdown" ]
2
JavaScript
browserstack/Galen-BrowserStack
f3731abfd26d3efed6af77fb016646f71d763f45
ba260dc221801ee83660d1e5f6d8c02d9124b6a0
refs/heads/main
<repo_name>arthurs14/Login-Full-Stack<file_sep>/client/src/components/Home/Home.js import { Container, Typography, Button, Paper } from '@material-ui/core'; import { useUser } from '../../context/UserContext'; import { useHistory } from 'react-router-dom'; import makeStyles from './styles'; const Home = () => { const { logout } = useUser(); const history = useHistory(); const classes = makeStyles(); const handleLogout = () => { console.log('logging out'); logout(history); }; return ( <Container maxWidth="md"> <Paper className={classes.paper} elevation={3}> <Typography className={classes.home} variant="h6">Homepage</Typography> <Button className={classes.logout} variant="outlined" color="secondary" onClick={handleLogout}>Logout</Button> </Paper> </Container> ); }; export default Home;
170ec083535bce77f4b0965edac793499f1b1000
[ "JavaScript" ]
1
JavaScript
arthurs14/Login-Full-Stack
e07646a69c9e24ee8efc0076fead80fac37ef660
b7d696d0fb8a954373ea35b789a9bc2723d03628
refs/heads/main
<file_sep># -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'mainwindow.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(382, 332) MainWindow.setMinimumSize(QtCore.QSize(382, 332)) MainWindow.setMaximumSize(QtCore.QSize(382, 16777215)) MainWindow.setStyleSheet("background-color: rgb(38, 32, 38);") self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.pushButton = QtWidgets.QPushButton(self.centralwidget) self.pushButton.setGeometry(QtCore.QRect(10, 120, 171, 91)) self.pushButton.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton.setStyleSheet("#pushButton {\n" " background-color: rgb(209, 0, 174);\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}\n" "\n" "#pushButton:hover {\n" " background-color: #a61c98;\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}") self.pushButton.setObjectName("pushButton") self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_2.setGeometry(QtCore.QRect(200, 120, 171, 91)) self.pushButton_2.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_2.setStyleSheet("#pushButton_2 {\n" " background-color: rgb(209, 0, 174);\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}\n" "\n" "#pushButton_2:hover {\n" " background-color: #a61c98;\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}") self.pushButton_2.setObjectName("pushButton_2") self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_3.setGeometry(QtCore.QRect(10, 10, 361, 91)) self.pushButton_3.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_3.setStyleSheet("#pushButton_3 {\n" " background-color: rgb(209, 0, 174);\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}\n" "\n" "#pushButton_3:hover {\n" " background-color: #a61c98;\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}") self.pushButton_3.setObjectName("pushButton_3") self.pushButton_4 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_4.setGeometry(QtCore.QRect(10, 230, 171, 91)) self.pushButton_4.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_4.setStyleSheet("#pushButton_4 {\n" " background-color: rgb(209, 0, 174);\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}\n" "\n" "#pushButton_4:hover {\n" " background-color: #a61c98;\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}") self.pushButton_4.setObjectName("pushButton_4") self.pushButton_5 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_5.setGeometry(QtCore.QRect(200, 230, 171, 91)) self.pushButton_5.setCursor(QtGui.QCursor(QtCore.Qt.PointingHandCursor)) self.pushButton_5.setStyleSheet("#pushButton_5 {\n" " background-color: rgb(209, 0, 174);\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}\n" "\n" "#pushButton_5:hover {\n" " background-color: #a61c98;\n" " color: rgb(255, 255, 255);\n" " font: 44pt \"Bebas Neue Cyrillic\";\n" "}") self.pushButton_5.setObjectName("pushButton_5") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 382, 21)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "PhotoConventor")) self.pushButton.setText(_translate("MainWindow", "To PNG")) self.pushButton_2.setText(_translate("MainWindow", "To JPG")) self.pushButton_3.setText(_translate("MainWindow", "SELECT FILE")) self.pushButton_4.setText(_translate("MainWindow", "To bmp")) self.pushButton_5.setText(_translate("MainWindow", "To tiff")) <file_sep>from PIL import Image import easygui from PyQt5 import QtCore, QtGui, QtWidgets from mainwindow import Ui_MainWindow import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() global file_name file_name = None def open_file(): global file_name file_name = easygui.fileopenbox(msg = 'Select image file') ui.pushButton_3.clicked.connect(open_file) def to_png(): global file_name if file_name: save_name = easygui.filesavebox(msg='Save png image') img = Image.open(file_name) img = img.convert('RGBA') img.save(save_name+".png", "png") ui.pushButton.clicked.connect(to_png) def to_jpg(): global file_name if file_name: save_name = easygui.filesavebox(msg='Save jpg image') img = Image.open(file_name) img = img.convert('RGB') img.save(save_name+".jpg", "jpeg") ui.pushButton_2.clicked.connect(to_jpg) def to_bmp(): global file_name if file_name: save_name = easygui.filesavebox(msg='Save bmp image') img = Image.open(file_name) img.save(save_name+".bmp", "bmp") ui.pushButton_4.clicked.connect(to_bmp) def to_tiff(): global file_name if file_name: save_name = easygui.filesavebox(msg='Save tiff image') img = Image.open(file_name) img.save(save_name+".tiff", "tiff") ui.pushButton_5.clicked.connect(to_tiff) sys.exit(app.exec_())<file_sep># PhotoConventor ## Необходимые модули: - easygui - PyQt5 - pillow
6560c71bcb3c7e0fc517a60466035be523561e71
[ "Markdown", "Python" ]
3
Python
onleew/PhotoConventor
0ee0d16744737bef9aa4fc55f9e3d3760388e5f4
a740dc1ceea6a8b3ef1ed19592f72f5f7c698e14
refs/heads/master
<repo_name>stenechkin/skillbox<file_sep>/app/client.py """ Клиентское приложение с интерфейсом """
c803ef4ffb3aad844d1bf63dd08cbc2495101d74
[ "Python" ]
1
Python
stenechkin/skillbox
4a62e7751a20eb9ba735f8d94ec597290529ecf1
8bd1415244ea27b9366dd25dc52926b14d4a935f
refs/heads/master
<repo_name>ellamaryp16/CSA-project-the-first<file_sep>/medialab/Movie.java /** * Write a description of class Movie here. * * @author (your name) * @version (a version number or a date) */ public class Movie extends Media { private int rating; private String title; private double price; private boolean favorite; private int duration = 100; private int time; public Movie() { rating = 10; title = "Ponyo"; price = 11.9; } //duration 1.1.3 pt 4 public int getDuration () { return duration; } public void setDuration (int d) { duration = d; } public String displayDuration () { int hr = duration/60; int min = duration % 60; String d = hr + " Hours & " + min + " Minutes"; return d; } } <file_sep>/fkja/xclkg.java /** * Write a description of class xclkgj here. * * @author (your name) * @version (a version number or a date) */ public class xclkg { int fall = 6; int run = }<file_sep>/medialab/LoopingMediaLab.java /** * Write a description of class LoopingMediaLab here. * * @author (your name) * @version (a version number or a date) */ public class LoopingMediaLab { public static void main () { String songInfo = MediaFile.readString(); /*for (int i = 0; i< medialab.numSongs; i++) { System.out.println(MediaFile.readString());}*/ while (songInfo != null){ System.out.println(songInfo); songInfo = MediaFile.readString(); } MediaFile.saveAndClose(); System.out.println(); } } <file_sep>/medialab/medialab.java /** * Write a description of class medialab here. * * @author (your name) * @version (a version number or a date) */ class medialab { public static double avgRating = (10 + 9 + 9)/3; public static int numSongs = 1 + 1 + 1; public static double totalCost = 1.0 + 2.33 + 1.0; public static void main () { System.out.println("Welcome to your media library!"); //Song Song Song1 = new Song("House of the Rising Sun",1.0,10); Song Song2 = new Song("Dance. Dance.", 2.33, 9); Song Song3 = new Song("bulletproof heart", 1.0, 9); Song1.setTitle("House of the Rising Sun"); System.out.println(Song1.getTitle()); System.out.println(Song2.getTitle()); Song1.setPrice(1.0); System.out.println(Song1.getRating()); System.out.println(Song1.getPrice()); System.out.println("The average rating is " + avgRating); System.out.println("The number of songs is " + numSongs); System.out.println(totalCost); System.out.println(Song2.getTitle()); //Movie Movie Movie1 = new Movie(); System.out.println(Movie1); Movie1.setTitle("Ponyo"); System.out.println(Movie1.getTitle()); Movie1.setPrice(11.9); System.out.println(Movie1.getPrice()); System.out.println(Movie1.displayDuration()); //Book Book Book1 = new Book(); System.out.println(Book1); Book1.setTitle("Wee Free Men"); System.out.println(Book1.getTitle()); Book1.setPrice(5.8); System.out.println(Song1.getPrice()); // 1.2.1 MediaFile.writeString(Song1.getTitle() + "|" + Song1.getRating()); MediaFile.writeString(Song2.getTitle() + "|" + Song2.getRating()); MediaFile.writeString(Song3.getTitle() + "|" + Song3.getRating()); MediaFile.saveAndClose(); } }
499e5634df0964b1ef838970764205fafdbff132
[ "Java" ]
4
Java
ellamaryp16/CSA-project-the-first
182cf1a85447de9a01d44f2888f4c92368a03595
e22ae5139188638ad8ed45c87c5a586797631b32
refs/heads/master
<repo_name>chandrakantsworld/price-calculator-kata<file_sep>/PriceCalculatorTests/ApplyExpenseOnProduct.cs using PriceCalculator; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace PriceCalculatorTests { public class ApplyExpenseOnProduct { public static readonly List<object[]> ProductTestData = new List<object[]> { new object[]{ new Product("The Little Prince", 12345, new Amount(20.25)), 21,15, new List<UpcDiscounts>() { new UpcDiscounts() { Upc = 12345, Discount = new Discount(7) } },"$4.25", "$4.46", "$22.44","$0.20","$2.20", new Expenses(new List<IExpense>(){(new Expense() { Name = "Packaging", ExpenseType = ExpenseType.Percentage, Value = 1 }), new Expense() { Name = "Transport", ExpenseType = ExpenseType.Monetary, Value = 2.2 } }) } }; [Theory] [MemberData("ProductTestData")] public void Apply_Expense_Discount_ExpectedResult(Product product, int tax, int discount, List<UpcDiscounts> upcDiscounts, string expectedTax, string expectedDiscount, string expectedPrice, string packaging,string shipping,Expenses expenses) { //Arrange Products products = new Products(new[] { product }); products.WithTax(new Tax(tax)) .WithDiscount(new Discount(discount), upcDiscounts) .WithExpense(expenses); //Act products.DisplayResult(); //Assert Assert.Equal(expectedTax, products.ContainedProducts.FirstOrDefault().TotalTax.ToString()); Assert.Equal(packaging, products.ContainedProducts.FirstOrDefault().Expenses.Expense.FirstOrDefault(s=>s.Name== "Packaging").Amount.ToString()); Assert.Equal(shipping, products.ContainedProducts.FirstOrDefault().Expenses.Expense.FirstOrDefault(s => s.Name == "Transport").Amount.ToString()); Assert.Equal(expectedDiscount, products.ContainedProducts.FirstOrDefault().TotalDiscount.ToString()); Assert.Equal(expectedPrice, products.ContainedProducts.FirstOrDefault().FinalPrice.ToString()); } } } <file_sep>/PriceCalculator/Expense.cs namespace PriceCalculator { public class Expense : IExpense { public string Name { get; set; } public ExpenseType ExpenseType { get; set; } public double Value { get; set; } public Amount Amount { get; set; } } } <file_sep>/PriceCalculator/IExpense.cs namespace PriceCalculator { public interface IExpense { string Name { get; set; } ExpenseType ExpenseType { get; set; } double Value { get; set; } Amount Amount { get; set; } } }<file_sep>/PriceCalculator/Currency.cs namespace PriceCalculator { public class Currency { public string CurrencySymbol { get; } public string CurrencyCode { get; } public Currency(string CurrencySymbol, string CurrencyCode) { this.CurrencyCode = CurrencyCode; this.CurrencySymbol = CurrencySymbol; } } } <file_sep>/PriceCalculator/Products.cs using System; using System.Collections.Generic; using System.Linq; namespace PriceCalculator { public class Products { public IEnumerable<IProduct> ContainedProducts { get; } public IEnumerable<UpcDiscounts> UpcDiscounts { get; set; } = Enumerable.Empty<UpcDiscounts>(); private ITaxCalculate taxCalculate; private ICalculateDiscount calculateDiscount; private ICalculateExpense calculateExpense; public Expenses Expenses { get; set; } private readonly IResult result; public Products(IEnumerable<IProduct> products) { ContainedProducts = products.ToList(); this.calculateDiscount = new DiscountCalculate(new Discount(0) , Enumerable.Empty<UpcDiscounts>()); result = new DisplayConsole(); calculateExpense = new ExpenseCalculator(new Expenses()); } public Products WithTax(Tax tax) { this.taxCalculate = new TaxCalculate(tax); return this; } public Products WithDiscount(Discount discount, IEnumerable<UpcDiscounts> upcDiscounts = null) { this.UpcDiscounts = upcDiscounts ?? Enumerable.Empty<UpcDiscounts>(); this.calculateDiscount = new DiscountCalculate(discount, this.UpcDiscounts); return this; } public Products WithExpense(Expenses expenses) { this.Expenses = expenses; this.calculateExpense = new ExpenseCalculator(this.Expenses); return this; } public void DisplayResult() { this.ContainedProducts.Each(s => { taxCalculate.CalculateTax(s, this.calculateDiscount.CalculateAddionalDiscount); this.calculateDiscount?.Calculate(s); s.FinalPrice = new Amount(s.Price.Value + s.TotalTax.Value - s.TotalDiscount.Value - s.AddionalDiscount.Value); s.TotalDiscount = new Amount(s.TotalDiscount.Value + s.AddionalDiscount.Value); this.calculateExpense.Calculate(s); result.Display(s); }); } } } <file_sep>/PriceCalculator/DiscountCalculate.cs using System; using System.Collections.Generic; using System.Linq; namespace PriceCalculator { class DiscountCalculate : ICalculateDiscount { private readonly Discount discount; private readonly IEnumerable<UpcDiscounts> upcDiscounts; public DiscountCalculate(Discount discount, IEnumerable<UpcDiscounts> upcDiscounts) { this.discount = discount; this.upcDiscounts = upcDiscounts; } public void Calculate(IProduct product) { CalculateAddDiscount(product); product.Discount = this.discount; product.TotalDiscount = new Amount(product.FinalPrice.Value * this.discount.DiscountRate); } private void CalculateAddDiscount(IProduct product) { product.AddionalDiscount = new Amount(product.Price.Value * FindAddionalDiscountProduct(product).Discount.DiscountRate); } private UpcDiscounts FindAddionalDiscountProduct(IProduct s) { return this.upcDiscounts.FirstOrDefault(product => product.Upc == s.Upc) ?? new UpcDiscounts(); } public override string ToString() => $"Discount {this.discount}"; public Amount CalculateAddionalDiscount(IProduct product) { var specialProduct = FindAddionalDiscountProduct(product); if (specialProduct.CanTaxCalculateAfterDiscount && specialProduct.Discount.DiscountRate > 0) return new Amount(product.Price.Value * specialProduct.Discount.DiscountRate); return new Amount(0); } } } <file_sep>/PriceCalculator/ITaxCalculate.cs using System; using System.Collections.Generic; namespace PriceCalculator { interface ITaxCalculate { void CalculateTax(IProduct product, Func<IProduct, Amount> additonaldiscount); } }<file_sep>/PriceCalculator/DisplayConsole.cs using System; namespace PriceCalculator { public class DisplayConsole : IResult { public void Display(IProduct product) { Console.WriteLine($"Product = {product.Name} UPC = {product.Upc}"); Console.WriteLine($"Cost = {product.Price} "); Console.WriteLine($"Tax = {product.TotalTax}"); if (product.TotalDiscount.Value>0) { Console.WriteLine($"Discounts = {product.TotalDiscount}"); } product.Expenses.DisplayResult(); Console.WriteLine($"Total = { product.FinalPrice}"); Console.WriteLine(); } } }<file_sep>/PriceCalculator/IResult.cs namespace PriceCalculator { interface IResult { void Display(IProduct product); } }<file_sep>/PriceCalculator/Tax.cs using System; namespace PriceCalculator { public class Tax { private readonly int Percent; public double TaxRate { get; } public Tax(int percent) { if (percent < 0 || percent > 100) throw new ArgumentOutOfRangeException( nameof(percent), $"{nameof(Tax)} percentage should be < 0 and > 100"); this.Percent = percent; TaxRate = (double)Percent / 100; } public override string ToString() => $"{Percent}%"; } } <file_sep>/PriceCalculator/UpcDiscounts.cs namespace PriceCalculator { public class UpcDiscounts { public bool CanTaxCalculateAfterDiscount { get; set; } = false; public int Upc { get; set; } public Discount Discount { get; set; } = new Discount(0); } } <file_sep>/PriceCalculator/EnumarableExtention.cs using System; using System.Collections.Generic; namespace PriceCalculator { public static class EnumarableExtention { public static void Each<T>( this IEnumerable<T> source, Action<T> action) { foreach (T element in source) action(element); } } } <file_sep>/PriceCalculator/Expenses.cs using System.Collections.Generic; namespace PriceCalculator { public class Expenses { public List<IExpense> Expense = new List<IExpense>(); public Expenses() { } public Expenses(List<IExpense> Expense) { this.Expense = Expense; } public void AddExpense(IExpense expense) { this.Expense.Add(expense); } public void AddRangeExpense(IExpense expense) { this.Expense.Add(expense); } public void DisplayResult() { Expense.ForEach(exp => { System.Console.WriteLine($"{exp.Name} = {exp.Amount}"); }); } } } <file_sep>/PriceCalculator/Discount.cs using System; namespace PriceCalculator { public class Discount { private readonly int Percent; public double DiscountRate { get; } public Discount(int percent) { if (percent < 0 || percent > 100) throw new ArgumentOutOfRangeException( nameof(percent), $"{nameof(Tax)} percentage should be in range [0..100]"); this.Percent = percent; this.DiscountRate = (double)Percent / 100; } public override string ToString() => $"{Percent}%"; } } <file_sep>/PriceCalculator/ExpenseCalculator.cs namespace PriceCalculator { public class ExpenseCalculator : ICalculateExpense { private readonly Expenses expenses; public ExpenseCalculator(Expenses expenses) { this.expenses = expenses; } public void Calculate(IProduct product) { this.expenses.Expense.ForEach(expense => { expense.Amount = expense.ExpenseType == ExpenseType.Percentage ? new Amount(expense.Value * product.Price.Value/100) : new Amount(expense.Value); product.Expenses.AddExpense(expense); product.FinalPrice = new Amount(product.FinalPrice.Value + expense.Amount.Value); }); } } } <file_sep>/PriceCalculator/ExpenseType.cs namespace PriceCalculator { public enum ExpenseType { Percentage, Monetary } } <file_sep>/PriceCalculator/TaxCalculate.cs using System; using System.Collections.Generic; using System.Linq; namespace PriceCalculator { class TaxCalculate : ITaxCalculate { public Tax tax { get; } public Amount Amount { get; set; } public TaxCalculate(Tax tax) { this.tax = tax ?? throw new System.ArgumentNullException(nameof(tax)); } public override string ToString() => $"Tax = {this.tax}"; public void CalculateTax(IProduct product,Func<IProduct,Amount> additonaldiscount) { var price = new Amount( product.Price.Value - additonaldiscount(product).Value); product.TotalTax = new Amount(price.Value * tax.TaxRate); product.Tax = this.tax; product.FinalPrice = price; } } } <file_sep>/PriceCalculator/Program.cs using System; using System.Collections.Generic; using System.Linq; namespace PriceCalculator { class Program { static void Main(string[] args) { List<UpcDiscounts> upcDiscounts = new List<UpcDiscounts>() { new UpcDiscounts() { Upc = 12345, Discount = new Discount(7) } }; Console.WriteLine("----------TAX--------"); //----------TAX-------- Products products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { } }); products.WithTax(new Tax(20)); products.DisplayResult(); Console.WriteLine("----------Discount--------"); //---------Discount----- products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { }, new Product("The Little Prince1", 123, new Amount(20.25)) { } }); products.WithTax(new Tax(20)) .WithDiscount(new Discount(15),Enumerable.Empty<UpcDiscounts>()); products.DisplayResult(); Console.WriteLine("----------Selective--------"); //---------Selective----- products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { }, new Product("The Little Prince1", 123, new Amount(20.25)) { } }); products.WithTax(new Tax(20)) .WithDiscount(new Discount(15), upcDiscounts); products.DisplayResult(); Console.WriteLine("----------Selective Case 2--------"); products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { }, new Product("The Little Prince1", 789, new Amount(20.25)) { } }); products.WithTax(new Tax(21)) .WithDiscount(new Discount(15), new List<UpcDiscounts>() { new UpcDiscounts() { Upc = 789, Discount = new Discount(7) } }); products.DisplayResult(); Console.WriteLine("----------Precedance--------"); products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { }, }); products.WithTax(new Tax(20)) .WithDiscount(new Discount(15), new List<UpcDiscounts>() { new UpcDiscounts() { Upc = 12345, Discount = new Discount(7), CanTaxCalculateAfterDiscount = true } }) ; products.DisplayResult(); Console.WriteLine("----------Expense--------"); products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { }, }); var expense = new Expenses(); expense.AddExpense( new Expense() { Name = "Packaging", ExpenseType = ExpenseType.Percentage, Value = 1 }); expense.AddExpense( new Expense() { Name = "Transport", ExpenseType = ExpenseType.Monetary, Value = 2.2 }); products.WithTax(new Tax(21)) .WithDiscount(new Discount(15), new List<UpcDiscounts>() { new UpcDiscounts() { Upc = 12345, Discount = new Discount(7), CanTaxCalculateAfterDiscount = false } }) .WithExpense(expense); products.DisplayResult(); Console.WriteLine("----------Expense 2--------"); products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { }, }); products.WithTax(new Tax(21)); products.DisplayResult(); // The code provided will print ‘Hello World’ to the console. // Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app. // Console.WriteLine("Hello World!"); Console.ReadKey(); // Go to http://aka.ms/dotnet-get-started-console to continue learning how to build a console app! } } } <file_sep>/PriceCalculator/Product.cs using System.Linq; namespace PriceCalculator { public class Product : IProduct { public string Name { get; } public int Upc { get; } public Amount Price { get; } public Amount TotalTax { get; set; } public Amount TotalDiscount { get; set; } public Amount AddionalDiscount { get; set; } = new Amount(0); public Amount FinalPrice { get; set; } = new Amount(0); public Tax Tax { get; set; } public Discount Discount { get; set; } public Expenses Expenses { get; set; } public Product(string name, int upc, Amount amount) { this.Name = name; this.Upc = upc; this.Price = amount; this.Expenses = new Expenses(); } public override string ToString() => $"Product Name {this.Name} UPC {this.Upc} Price {this.Price}"; } } <file_sep>/PriceCalculator/ICalculateExpense.cs namespace PriceCalculator { public interface ICalculateExpense { void Calculate(IProduct product); } } <file_sep>/PriceCalculator/Amount.cs using System; namespace PriceCalculator { public class Amount { public Currency Currency { get; set; } public double Value { get; } public Amount(double value) { if (value < 0) throw new ArgumentException("Amount can not be less than 0"); this.Value = Math.Round(value, 2, MidpointRounding.AwayFromZero); this.Currency = new Currency("$", "USD"); } public override string ToString() => $"{this.Currency.CurrencySymbol}{Value:#0.00}"; } } <file_sep>/PriceCalculatorTests/ApplyDiscount.cs using PriceCalculator; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace PriceCalculatorTests { public class ApplyDiscount { public static readonly List<object[]> ProductTestData = new List<object[]> { new object[]{ new Product("The Little Prince", 12345, new Amount(20.25)), 20,15, "$4.05", "$3.04", "$21.26"}, }; [Theory] [MemberData("ProductTestData")] public void Apply_Discount_ExpectedResult(Product product, int tax,int discount,string expectedTax, string expectedDiscount,string expectedPrice) { //Arrange Products products = new Products(new[] { product }); products.WithTax(new Tax(tax)); products.WithDiscount(new Discount(discount)); //Act products.DisplayResult(); //Assert Assert.Equal(expectedTax, products.ContainedProducts.FirstOrDefault().TotalTax.ToString()); Assert.Equal(expectedDiscount, products.ContainedProducts.FirstOrDefault().TotalDiscount.ToString()); Assert.Equal(expectedPrice, products.ContainedProducts.FirstOrDefault().FinalPrice.ToString()); } } } <file_sep>/PriceCalculatorTests/ApplyTax.cs using PriceCalculator; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace PriceCalculatorTests { public class ApplyTax { [Theory] [InlineData(20, "$24.30")] [InlineData(21, "$24.50")] public void Step1_Tax_ExpectedResult(int percent, string expectedResult) { //Arrange Products products = new Products(new[] { new Product("The Little Prince", 12345, new Amount(20.25)) { } }); products.WithTax(new Tax(percent)); //Act products.DisplayResult(); //Assert Assert.Equal(expectedResult, products.ContainedProducts.FirstOrDefault().FinalPrice.ToString()); } } } <file_sep>/PriceCalculatorTests/ApplyPrecedanceDiscountBeforTax.cs using PriceCalculator; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace PriceCalculatorTests { public class ApplyPrecedanceDiscountBeforTax { public static readonly List<object[]> ProductTestData = new List<object[]> { new object[]{ new Product("The Little Prince", 12345, new Amount(20.25)), 20,15, new List<UpcDiscounts>() { new UpcDiscounts() { Upc = 12345, Discount = new Discount(7),CanTaxCalculateAfterDiscount = true } },"$3.77", "$4.24", "$19.78","$1.42"}, new object[]{ new Product("The Little Prince", 789, new Amount(20.25)), 21,15, new List<UpcDiscounts>() { new UpcDiscounts() { Upc = 12345, Discount = new Discount(7) } },"$4.25", "$3.04", "$21.46","$0.00"}, }; [Theory] [MemberData("ProductTestData")] public void Apply_Precedance_Discount_ExpectedResult(Product product, int tax, int discount, List<UpcDiscounts> upcDiscounts, string expectedTax, string expectedDiscount, string expectedPrice, string expectedAddionalDiscount) { //Arrange Products products = new Products(new[] { product }); products.WithTax(new Tax(tax)) .WithDiscount(new Discount(discount), upcDiscounts); //Act products.DisplayResult(); //Assert Assert.Equal(expectedTax, products.ContainedProducts.FirstOrDefault().TotalTax.ToString()); Assert.Equal(expectedAddionalDiscount, products.ContainedProducts.FirstOrDefault().AddionalDiscount.ToString()); Assert.Equal(expectedDiscount, products.ContainedProducts.FirstOrDefault().TotalDiscount.ToString()); Assert.Equal(expectedPrice, products.ContainedProducts.FirstOrDefault().FinalPrice.ToString()); } } } <file_sep>/PriceCalculator/IDiscountCalculate.cs namespace PriceCalculator { interface ICalculateDiscount { void Calculate(IProduct product); Amount CalculateAddionalDiscount(IProduct product); } }<file_sep>/PriceCalculator/IProduct.cs namespace PriceCalculator { public interface IProduct { string Name { get; } int Upc { get; } Amount Price { get; } Amount TotalTax { get; set; } Amount FinalPrice { get; set; } Amount TotalDiscount { get; set; } Amount AddionalDiscount { get; set; } Tax Tax { get; set; } Discount Discount { get; set; } Expenses Expenses { get; set; } } }
a55ced7eccd089f0254fb2605ad4f5ac576fe1d7
[ "C#" ]
26
C#
chandrakantsworld/price-calculator-kata
6fd0a2868b94704c26610b054bcc9e5d6dc2909b
65df526b944427787967730a2e1b9858d2aa362d
refs/heads/master
<repo_name>Schnides123/mini-edgar<file_sep>/src/edgar_crawler/pipelines.py # -*- coding: utf-8 -*- import csv # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html class EdgarCrawlerPipeline(object): def process_item(self, item, spider): file_path = spider.path+"/"+spider.output_name+".tsv" print("saving "+spider.id+" to file "+file_path+"...") with open(file_path, "w+", newline='') as file: writer = csv.DictWriter(file, item['keys'], restval="n/a", delimiter='\t') writer.writeheader() for row in item["data"]: writer.writerow(row) file.close() print("file saved successfully.") return <file_sep>/Readme.txt Hi, thanks for taking the time to check out my edgar crawler! I threw it together using Scrapy and BeautifulSoup, so there shouldn't be too many dependencies with running everything. Additionally, I've got ahead and included my venv config. It might be convenient to use them for setup, but you mileage may vary. The installation instructions below will assume that you aren't using them. If there are any problems with installation or your computer catches on fire while running the program, feel free to reach out to me any time at <EMAIL>. ================= Steps to install: 1. Use pip to install the following dependencies: -Scrapy -BeautifulSoup 1.5. Make sure your paths are set up to be able to run scrapy from the command line. To check whether or not this is the case, just type "scrapy" into the command line and see if anything comes up. (I tried doing a test install on a friend's computer and this was a bit of a pain to deal with. That said, I'd imagine an office machine would be already configured so this will probably be a non-issue for you.) 2. Navigate to src/edgar-crawler 3. Use the following command to run the crawler: scrapy crawl crawler [-a cik_ticker=""] [-a output_path=""] [-a output_name=""] *using -a cik_ticker=#### isn't required, but it'll prompt you to enter one in later if you don't **By default, the output path is set to the data folder in src/edgar-crawler ***If you don't include a name for the output file, it'll be named after the CIK or Ticker For reference, here are the example values from the prompt: Gates Foundation | 0001166559 CALEDONIA FUND LTD. | 0001037766 Peak6 Investments LLC | 0001756111 Kemnay Advisory Services Inc. | 0001555283 HHR Asset Management, LLC | 0001397545 Benefit Street Partners LLC | 0001543160 Okumus Fund Management Ltd. | 0001496147 PROSHARE ADVISORS LLC | 0001357955 TOSCAFUND ASSET MANAGEMENT LLP | 0001439289 Black Rock | 0001086364<file_sep>/src/edgar_crawler/spiders/Crawler.py # -*- coding: utf-8 -*- import scrapy from ..items import EdgarData from bs4 import BeautifulSoup class Crawler(scrapy.Spider): name = 'crawler' allowed_domains = ['sec.gov'] start_urls = [] def __init__(self, cik_ticker=None, output_path="data", output_name=None): if not cik_ticker: cik_ticker = input("Enter a CIK number or ticker to search for.") self.id = cik_ticker.strip() self.path = output_path self.output_name = output_name if output_name else self.id self.start_urls = [ 'https://www.sec.gov/cgi-bin/browse-edgar?CIK={}&owner=exclude&action=getcompany&Find=Search'.format(self.id) ] def parse(self, response): soup = BeautifulSoup(response.body, "lxml") table = soup.find("table", {"class": "tableFile2"}) rows = table.findAll("tr") if table else [] link = None for row in rows: cell = row.find(text="13F-HR") if cell: # *Cries in HTML* link = row.find("a", {"id": "documentsbutton"}) break if link and len(link) > 0: link = "https://"+self.allowed_domains[0]+link["href"] return scrapy.Request(link, self.parse_docs_page) def parse_docs_page(self, response): soup = BeautifulSoup(response.body, "lxml") rows = soup.find("table", {"class": "tableFile"}).findAll("tr") file_url = None for row in rows: cell = row.find(text="INFORMATION TABLE") link = row.find("a", href=lambda ref: ref and ".xml" in ref, text=lambda text: text and ".xml" in text) if cell and link: file_url = "https://" + self.allowed_domains[0] + link["href"] break if file_url: return scrapy.Request(file_url, self.parse_data) def parse_data(self, response): soup = BeautifulSoup(response.body, "lxml-xml") rows = soup.find_all("infoTable") if rows: first = rows[0] keys = [] data = [] for row in rows: row_data = {} for tag in row.find_all(): #strip container tags to flatten out rows if len(tag.contents) <= 1: if tag.name not in keys: keys.append(tag.name) row_data[tag.name] = tag.text data.append(row_data) results = EdgarData() results["keys"] = keys results["data"] = data return results
409d789feddb209d0c90040df1a1867c26172b28
[ "Python", "Text" ]
3
Python
Schnides123/mini-edgar
f84b8f3a1bc8b085183ac232f1be1a55ac4ad099
5704af2a8c528bda12bc30728b5274e3f2bc29c1
refs/heads/master
<repo_name>mrmrtalbot/PassIParcel2.0<file_sep>/apiKey.properties apiKey.id = <KEY> apiKey.secret = <KEY> <file_sep>/routes/index.js var express = require('express'); var router = express.Router(); var stormpath = require('express-stormpath'); // Render the home page. router.get('/', function(req, res) { res.render('index', {title: 'Home', user: req.user}); }); router.get('/Home', function(req, res) { res.render('Home', {title: 'Home', user: req.user}); }); // Render the dashboard page. router.get('/dashboard', function (req, res) { if (!req.user || req.user.status !== 'ENABLED') { return res.redirect('/login'); } res.render('dashboard', {title: 'Dashboard', user: req.user}); }); // Render the create parcel page. router.get('/createparcel', function(req, res) { res.render('createparcel', {title: 'Create Parcel', user: req.user}); }); router.post('/created', function(req, res){ res.render('index', {title: 'Create Parcel', user: req.user}); console.log('how are you'); console.log(JSON.stringify(req.body)); res.end(); }); /* var result = utils.BuildParcelFromData(req); if(!result["errorCode"]) { var error = ""; result.parcel.save(function (err) { if (err) { error=err; } }); if(error.length === 0) { result.content.save(function(err){ if(err) { error=err; } }); } if(error.length === 0) { result.batch.save(function(err){ if(err) { error=err; } }); } if(error) { res.send(error); } } res.send(result); */ router.get('/login', function(req,res) { res.sendFile('login.html', {root: './views/partials/'}); }); router.get('/logout', function(req,res) { res.sendFile('logout.html', {root: './views/partials/'}); }); module.exports = router; <file_sep>/routes/api/utils.js var restful = require('node-restful'); var mongoose = restful.mongoose; var utils = require('./utils'); var Parcel = mongoose.model('Parcel', Parcel); var ParcelContent = mongoose.model('ParcelContent', ParcelContent); var Voucher = mongoose.model('ParcelVoucher', Voucher); var Batch = mongoose.model('ParcelBatch', Batch); var stormpath = require('express-stormpath'); var ErrorMessage = mongoose.model('Error', Error); //var InformationMessage = mongoose.model('Info', Info); module.exports.testFunctionality = function() { return"Yay"; }; module.exports.BlindBatchParcelConstructor = function (parcel, content, index, voucher) { var result = {}; if(typeof voucher === 'undefined' || typeof parcel === 'undefined' || voucher.length === 0 || index > voucher.length) { return result; } if(typeof Parcel !== 'undefined' && typeof content !== 'undefined') { result.parcel = parcel; result.content = content; result.parcel._id = new mongoose.Types.ObjectId();; result.content._id = new mongoose.Types.ObjectId();; result.parcel.contentId = result.content._id; result.content.voucher._id = new mongoose.Types.ObjectId();; result.content.voucher.code = voucher[index]; } return result; } module.exports.BuildParcelFromData = function (req){ var Result = {}; var p = new Parcel; var fields = new Array(); if(utils.isSet([req.body.expiryDate])) { p.expiryDate = req.body.expiryDate; } if(utils.isSet([req.body.name])) { p.name = req.body.name; } else { fields.push("name"); } if(utils.isSet([req.body.openMethods]) && req.body.openMethods.length > 0) { p.openMethods = []; for(var i =0; i < req.body.openMethods.length; i++) { if(req.body.openMethods[i].hasOwnProperty('name') && req.body.openMethods[i].hasOwnProperty('description')) { p.openMethods.push({name:req.body.openMethods[i].name, description:req.body.openMethods[i].description}); } else { fields.push ("malformed open method at index " + i); } } } else { fields.push("openMethods"); } //TODO: Get current user via stormpath if(utils.isSet(req.user.username)) { p.currentUser = req.user.username; } else { fields.push("UserName"); } //TODO: Get current user via stormpath if(utils.isSet(req.user.username)) { p.previousUsers.push(req.user.username); } else { fields.push("Username"); } if(utils.isSet([req.body.category])) { p.category = req.body.category; } else { fields.push("category"); } if(utils.isSet(([req.batchId]))) { p.batchId = req.body.batchId; } else { utils.GenerateBatch(req, p, fields, Result); if("batch" in Result) { p.batchId = Result.batch._id; } else { fields.push("Batch creation failure"); } } if(utils.isSet([req.body.content])) { var temp = utils.BuildParcelContentFromData(req, p, fields, Result); if(temp === Array) { fields.push.apply(fields, temp); } } else { fields.push("parcel.content"); } if(fields.length > 0) { var e = utils.GenerateError("100","The Message was missing parameters",fields.slice()); return e; } p.dateUpdated = Date.now(); if("content" in Result) { p.contentId = Result.content._id; } Result.parcel = p; return Result; }; //TODO: To test module.exports.PassParcel = function(parcel,requestor, newOwner) { var Result = {}; var fields = new Array(); if(typeof parcel === 'undefined') { fields.push("Parcel not found"); } if(typeof requestor === 'undefined' || requestor.length === 0) { fields.push("Anonymous sender, pass failed"); } if(typeof newOwner === 'undefined' || newOwner.length === 0) { fields.push("New parcel owner not specified"); } //TODO : check if new owner is a user on the system if(typeof requestor === 'String' && typeof newOwner === 'String' && parcel.ownerId === requestor) { if(parcel.previousUsers.indexOf(newOwner) > -1) { fields.push("The parcel cannot be handed to this person. They have already recieved this parcel."); } else { parcel.previousUsers.push(requestor); parcel.currentUser = newOwner; } } else { return utils.GenerateError("100","The Message was missing parameters"); } if(fields.length > 0) { Result.errorCode = fields; } else { parcel.dateUpdated = Date.now(); Result.parcel = parcel; } return Result; }; //TODO: To test module.exports.OpenParcel = function(parcel, requestor) { var Result = {}; var fields = new Array(); if(typeof parcel === 'undefined') { fields.push("Parcel not found"); } if(typeof requestor === 'undefined' || requestor.length === 0) { fields.push("Anonymous requester, open failed"); } if(typeof parcel.opened !== 'undefined' && parcel.opened === true) { fields.push("The parcel is already open"); } if(typeof request === 'string' && parcel.currentUser === requestor) { // Person is authorised to open it //TODO - What happens when you open a parcel parcel.opened = true; } else { fields.push("This is not your parcel to open"); } if(fields.length > 0) { Result.errorCode = fields; } else { parcel.dateUpdated = Date.now(); Result.parcel = parcel; } return Result; } module.exports.BuildParcelContentFromData = function (req, parcel, fields, Result) { var hasParcel = true; if (typeof parcel === 'undefined') { hasParcel = false; } if (typeof fields === 'undefined') { fields = new Array(); } var content = new ParcelContent; if(utils.isSet([req.body.content.name])) { content.name = req.body.content.name; } else { fields.push("content.name"); } if(utils.isSet([req.body.content.extensionData])) { content.extensionData = req.body.extensionData; } if(utils.isSet([req.body.content.vouchers])) { if(req.body.content.vouchers.length === 0) { fields.push("Content.vouchers contains a blank voucher"); } else { content.voucher = new Voucher(); content.voucher.code = req.body.content.vouchers[0]; } } else { fields.push("content.vouchers"); } if(fields.length > 0) { if(hasParcel) { return fields; } else { var e = utils.GenerateError("101","The Message was missing parameters",fields.slice()); return e; } } else { content.dateUpdated = Date.now(); Result.content = content; } }; module.exports.GenerateBatch = function (req, parcel, fields ,Result) { var b = new Batch(); if(typeof fields === 'undefined') { fields = new Array(); } if(typeof req === 'undefined') { fields.push("Batch"); } if(typeof parcel === 'undefined') { if(utils.isSet([req.body.name])) { b.name = req.body.name; } else { fields.push("Batch.name"); } } else { if(utils.isSet([parcel.name])) { b.name = parcel.name + " Batch"; } else { fields.push("Batch.name"); } } //TODO: Get Owner ID if(true) { b.ownerId = "TODO"; } if(fields.length > 0) { var e = utils.GenerateError("101","The Message was missing parameters",fields.slice()); return e; } else if(typeof Result === 'undefined') { return b; } else { Result.batch = b; } } module.exports.GenerateError = function(code,message,fields) { if (typeof code === 'undefined') { code = "10"; } if (typeof message === 'undefined') { message = "No message specified." } if (typeof fields === 'undefined') { fields = ["No fields specified"]; } var e = new ErrorMessage; e.errorCode = code; e.message = message; e.fields = fields; return e; }; module.exports.GenerateInformation = function(code, message) { if (typeof code === 'undefined') { code = "1"; } if (typeof message === 'undefined') { message = "No message specified." } var i = new InformationMessage; i.messageCode = code; i.message = message; }; module.exports.isSet = function(a){ for(var i = 0; i < a.length; i++){ if(typeof a[i] != 'undefined'){ continue; } return false; } return true; }; module.exports.strToJson= function(str) { eval("var x = " + str + ";"); return JSON.stringify(x); }; module.exports.guid = function () { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; module.exports.objClone = function (obj) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = obj[attr]; } } return copy; } <file_sep>/models/list.js var restful = require('node-restful'); var mongoose = restful.mongoose; var CategorySchema = new mongoose.Schema({ name: {type: String, required: true}, categoryType: {type:Boolean}, }); var ProviderSchema = new mongoose.Schema({ name: {type: String, required: true}, }); module.exports = restful.model('Category', CategorySchema); module.exports = restful.model('Provider', ProviderSchema); //Provider - Id, Name //Category - Id, Name<file_sep>/routes/api.js var express = require('express'); var router = express.Router(); //models var Adverts = require('../models/advert'); var Parcels = require('../models/parcel'); var Errors = require('../models/errorhandling'); var Information = require('../models/errorhandling'); /* GET api listing. */ Parcels.methods(['get', 'put', 'post', 'delete']); Parcels.register(router, '/api/parcel'); Adverts.methods(['get', 'put', 'post', 'delete']); Adverts.register(router, '/api/advert'); router.get('/', function(req, res, next) { res.send({'api version': '1.0', 'teamMembers':['<NAME>', '<NAME>'], 'message':'Please Refer to the API documentation http://www.Placeholder.com/documentation/ for more information'}); }); module.exports = router; <file_sep>/public/js/pip.js (function() { var app = angular.module("Pip", ['stormpath', 'stormpath.templates']); app.directive('bindDynamicHtml', ['$compile', function ($compile) { return function(scope, element, attrs) { scope.$watch( function(scope) { // watch the 'bindUnsafeHtml' expression for changes return scope.$eval(attrs.bindDynamicHtml); }, function(value) { // when the 'bindUnsafeHtml' expression changes // assign it into the current DOM element.html(value); // compile the new DOM and link it to the current // scope. // NOTE: we only compile .childNodes so that // we don't get into infinite loop compiling ourselves $compile(element.contents())(scope); } ); }; }]); app.controller("InterfaceController", function ($scope, $http, $sce) { $http.get("/login") .then(function(response) { $scope.pageContent = response.data; }); }); app.controller("LoginController", function($scope, $http, $sce) { $scope.user = { "userName": "", "password": "", "remembered": true, }; }); })();<file_sep>/routes/api/parcel.js var express = require('express'); var utils = require('./utils'); var router = express.Router(); var restful = require('node-restful'); var mongoose = restful.mongoose; var stormpath = require('express-stormpath'); var Parcel = mongoose.model('Parcel', Parcel); var Batch = mongoose.model('ParcelBatch', Batch); var Content = mongoose.model('ParcelContent', Content); var Voucher = mongoose.model('ParcelVoucher', Voucher); router.post('/', stormpath.apiAuthenticationRequired, function(req, res, next) { console.log(req.user.username); if(utils.isSet([req.body.batchId])) { Batch.findOne({'_id': req.body.batchId}, function(err) { if(err) { res.send(utils.GenerateError("110","Batch not found")); return; } }); } var result = utils.BuildParcelFromData(req); if(!result["errorCode"]) { var parcels = new Array(); var contents = new Array(); parcels.push(JSON.parse(JSON.stringify(result.parcel))); contents.push(JSON.parse(JSON.stringify(result.content))); var resultObj = {}; var error = ""; for(var i=1; i < req.body.content.vouchers.length; i++) { resultObj = utils.BlindBatchParcelConstructor(result.parcel, result.content, i, req.body.content.vouchers); if(Object.keys(resultObj).length !== 0) { parcels.push(JSON.parse(JSON.stringify(resultObj.parcel))); contents.push(JSON.parse(JSON.stringify(resultObj.content))); } } Parcel.insertMany(parcels, function (err){ if (err) { error=err; } }); if(error.length === 0) { Content.insertMany(contents, function (err){ if (err) { error=err; } }); } if(error.length === 0) { result.batch.save(function(err){ if(err) { error=err; } }); } if(error) { res.send(error); } } res.send(contents); }); router.get('/parcel/:id', function (req, res, next) { if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Parcel.findOne({'_id': req.params.id}, function (err, parcel) { if (err){ res.send(err); } res.send(parcel); }); } }); router.get('/batch/:id', function (req, res, next) { if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Batch.findOne({'_id':req.params.id}, function(err, batch) { if(err) { res.send(err); } else { res.send(batch); } }); } }); router.get('/batch/', function (req, res, next) { Batch.find( function(err, batch) { if(err) { res.send(err); } else { res.send(batch); } }); }); router.get('/parcel/', function (req, res, next) { Parcel.find( function(err, parcel) { if(err) { res.send(err); } else { res.send(parcel); } }); }); router.post('/batch', function (req,res,next) { var result = utils.GenerateBatch(req); if(!result["errorCode"]) { result.save(function(err){ if(err != null) { result = err; } }); } res.send(result); }); //TODO: To test router.put('/parcel/:id/pass',function (req,res,next){ if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Parcel.findOne({'_id': req.params.id}, function (err, parcel) { if(err) { res.send(err); } else { var result = utils.PassParcel(parcel, "TODO", req.body.newOwner); //TODO: Replace todo with actual user id making the call if(typeof result.errorCode !== 'undefined' || typeof result.parcel === 'undefined') { res.send(result.errorCode); } else { result.parcel.save(function(err) { if(err) { res.send(err); } else { res.send(result.parcel); } }); } } }); } }); //TODO: To test router.put('/parcel/:id/open', function (req,res,next) { if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Parcel.findOne({'_id': req.params.id}, function (err, parcel) { if(err) { res.send(err); } else { var result = utils.OpenParcel(parcel, "TODO"); //TODO: Replace todo with actual user id making the call if(typeof result.errorCode !== 'undefined' || typeof result.parcel === 'undefined') { res.send(result.errorCode); } else { result.parcel.save(function(err) { if(err) { res.send(err); } else { res.send(result.parcel); } }); } } }); } }); //TODO: To test router.get('/batch/:id/all', function (req,res,next) { if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Batch.findOne({'_id': req.params.id}), function (err, batch) { if(err) { res.send(err); } else { if(!batch) { //No results found res.send(utils.GenerateError("110","Batch not found")); } else { Parcel.find({'batchId': req.params.id}, function (err, parcels) { if(err) { res.send(err); } else if(!parcels) { res.send(utils.GenerateError("120","Parcels not found for Batch")); } else { res.send(parcels); } }); } } } } }); //TODO: To test router.get('/parcel/:id/content', function (req,res,next) { //Get content of parcel by parcel id if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Parcel.findOne({'_id': req.params.id}, function (err, parcel) { if(err) { res.send(err); } else if (!parcel) { res.send(utils.GenerateError("111","Parcel not found")); } else { if(utils.isSet([parcel.contentId])) { Content.findOne({'_id': parcel.contentId}, function(err, content) { if(err) { res.send(err); } else if(!content) { res.send(utils.GenerateError("112","Content not found")); } else { res.send(content); } }); } else { res.send(utils.GenerateError("102","Parcel contains no content")); } } }); } }); //TODO: To test router.get('/parcel/:id/voucher', function (req,res,next) { //Get voucher code where parcel id is X if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Parcel.findOne({'_id': req.params.id}, function (err, parcel) { if (err) { res.send(err); } else if (!parcel) { res.send(utils.GenerateError("111", "Parcel not found")); } else { if(utils.isSet([parcel.contentId])) { Content.findOne({'_id': parcel.contentId},{ code: 1, _id:0}, function(err, voucher) { if(err) { res.send(err); } else if(!voucher) { res.send(utils.GenerateError("112","Content not found")); } else { res.send(voucher); } }); } else { res.send(utils.GenerateError("102","Parcel contains no content")); } } }); } }); router.get('/parcel/', function (req, res, next) { Parcel.find( function(err, parcel) { if(err) { res.send(err); } else { res.send(parcel); } }); }); //TODO: To test //TODO: Add If deleted checks to all gets and updates router.delete('parcel/:id/delete', function (req,res,next) { //Delete parcel by id if(!utils.isSet([req.params.id])) { res.send(utils.GenerateError("100","The Message was missing parameters",["Id"])); } else { Parcel.findOne({'_id': req.params.id}, function (err, parcel) { if (err) { res.send(err); } else if (!parcel) { res.send(utils.GenerateError("111", "Parcel not found")); } else { if(parcel.deleted === true) { res.send(utils.GenerateError("103", "Parcel has already been deleted")); } else { parcel.deleted = true; parcel.save(function(err) { if(err) { res.send(err); } else { res.send(parcel); } }); } } }); } }); //POST User //Registers a user //Map submitted request into a User Model -> Validate Model -> Post if successful, return error if not //POST User/UserData //Register User data //Map submitted request into a User Data Model -> Validate Model -> Validate User exists and is authorised -> //Post if successful, return error if not //POST User/Login //Crypto submitted password -> Compare username/password with that in the database -> Return Login message if successful //-> Else return incorrect login/pass //POST User/Logout //Check if logged in -> If Logged in then clear current session and log out else return not logged in error //PUT User/UserData //Update User Data //Map submitted request into a User Data Model -> Validate Model -> Validate User exists and is authorised -> //Post if successful, return error if not //GET User/ //RetrieveUserDetails //Check if logged in or authorised to access -> If authorised then return the user, else error //GET User/UserData //Retrieve User Details //Check if logged in or authorised to access -> If authorised then return the user, else error //POST Parcel // Add parcel to DB //PUT Parcel //Update Parcel //PUT Parcel/Content //Update Parcel Contents //GET Parcel //Retrieve a Parcel //GET Parcel/Content //Retrieve a Parcels contents //GET Parcel/User //Get Parcels assigned to a user //POST Advert //Add advert to DB //POST Advert/Parcel //Join advert to parcel //GET Advert //Retrieve Advert data to device //GET Category //Retrieve list of all categories //POST Category //Add a new category //GET Provider //Retrieve list of all categories //POST Provider //Add a new provider //POST Security/Activation // ??? //GET Security/Activation // ??? module.exports = router; <file_sep>/models/parcel.js var restful = require('node-restful'); var mongoose = restful.mongoose; var Advert = mongoose.model('Advert', Advert); var VoucherSchema = new mongoose.Schema({ id: {type: Number, index:true}, code: {type:String, required:true} }); var ParcelContentSchema = new mongoose.Schema({ id: {type: Number, index: true}, dateCreated: { type: Date, default:Date.now }, dateUpdated: { type: Date, default:Date.now }, name: {type:String, required:true}, voucher: {type: VoucherSchema, required: true}, extensionData: {type:String}, }); //TODO: Adverts update and schema change var ParcelSchema = new mongoose.Schema({ id: {type: Number, index: true}, dateCreated: { type: Date, default:Date.now }, dateUpdated: { type: Date, default:Date.now }, expiryDate: {type: Date, default: new Date(new Date().setYear(new Date().getFullYear() + 1))}, name: {type: String, required: true}, openMethods: [{ id: {type: Number}, name: {type: String}, description: {type: String}, }], currentUser: {type: String, required: true}, previousUsers:[{type:String}], contentId: {type: String , required: true}, batchId: {type: String, required: true}, adverts: [{ advert:{type: Advert.schema, required: true} }], opened: {type:Boolean, required: true, default: false}, deleted: {type: Boolean, required: true, default:false}, }); var ParcelBatchSchema = new mongoose.Schema({ id: {type: Number, index: true}, dateCreated: {type: Number, default: Date.now()}, dateUpdated: { type: Date, default:Date.now() }, name: {type: String, required: true}, ownerId: {type: String}, //TODO: Implement as required when owner ID is implemented }); module.exports = restful.model('Parcel', ParcelSchema); module.exports = restful.model('ParcelContent', ParcelContentSchema); module.exports = restful.model('ParcelBatch', ParcelBatchSchema); module.exports = restful.model('ParcelVoucher', VoucherSchema); // Parcel Content schema change to id, name, content, extensionData, date updated, expiry of coupon // Parcel schema to contain id, expiry date, name, content, category, open method, probability, current owner id and previous owners(s) - string array, batch id, date updated // Parcel Batch schema - date created, name, owner id, description, date updated // Add ID to openMethod //In batch creation they would pass Name of batch, description of batch, expiry date of parcels, category of parcels, list of coupon codes, expiry date of coupon codes
7c9162dd81eb7161349d93a98cec6847e7ca1528
[ "JavaScript", "INI" ]
8
INI
mrmrtalbot/PassIParcel2.0
e679d5e67d1e69d08eba9bc15c2a1e689efa72a5
56d716eb639c96e2877126fa32f61e1033738fad
refs/heads/master
<repo_name>Andresdst/slider-Frameworkless<file_sep>/main.js class IndexForSiblings { static get(el) { let children = el.parentNode.children; for (let i = 0; i < children.length; i++) { let child = children[i]; if (child == el) return i; } } } class Slider { constructor(selector) { this.move = this.move.bind( this ); /* ya que this se reescribe y cambia en js*/ this.moveByButton = this.moveByButton.bind(this); this.slider = document.querySelector(selector); this.itemsCount = this.slider.querySelectorAll(".container > *").length; this.interval = null; this.contador = 0; this.start(); this.buildControls(); this.bindEvent(); } start() { this.interval = window.setInterval(this.move, 3000); } bindEvent() { this.slider.querySelectorAll(".controls li").forEach((element) => { element.addEventListener("click", this.moveByButton); }); } moveByButton(ev) { //evento que paso el eventListener let index = IndexForSiblings.get(ev.currentTarget); this.contador = index; this.moveTo(index); if (this.interval) window.clearInterval(this.interval); this.start(); } //crear controles dinamicamente buildControls() { for (let i = 0; i < this.itemsCount; i++) { let control = document.createElement("li"); if (i == 0) control.classList.add("active"); this.slider.querySelector(".controls ul").appendChild(control); //insertando elementos creados } } move() { this.contador++; if (this.contador >= this.itemsCount) this.contador = 0; this.moveTo(this.contador); } resetControl() { this.slider .querySelectorAll(".controls li.active") .forEach((element) => element.classList.remove("active")); } moveTo(index) { let left = index * 100; this.resetControl(); //para limpiar indicador this.slider .querySelector(".controls li:nth-child(" + (index + 1) + ")") .classList.add("active"); this.slider.querySelector(".container").style.left = "-" + left + "%"; } } (function () { //closure para que no haya variables globales new Slider(".slider"); })();
5e01df86328776ddd5a09ce89a548af48d5a30e9
[ "JavaScript" ]
1
JavaScript
Andresdst/slider-Frameworkless
888e3cdfb087d36bc4d605ffb8be857f644d5dcd
b41b093a2a8ca7c1b5b35bc1fb8b532fb0d4afb3
refs/heads/master
<repo_name>samerxy/QM<file_sep>/Inventory_Management/PL/F_sale.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_sale : Form { BL.C_Order _Order = new BL.C_Order(); DataTable dt = new DataTable(); void Calculateamount() { if (textBoxprice.Text != string.Empty && textBoxqte.Text != string.Empty) textBoxamount.Text = (Convert.ToDouble(textBoxprice.Text) * Convert.ToInt32(textBoxqte.Text)).ToString(); } void totalcost() { if (textBoxdis.Text != string.Empty && textBoxamount.Text!=string.Empty) { double discount = Convert.ToDouble(textBoxdis.Text); double amount = Convert.ToDouble(textBoxamount.Text); double total = amount - (amount * (discount / 100)); textBoxcost.Text = total.ToString(); } } void clearbox() { txtidpro.Clear(); textBoxname.Clear(); textBoxprice.Clear(); textBoxqte.Clear(); textBoxamount.Clear(); textBoxdis.Clear(); textBoxcost.Clear(); button2.Focus(); } void CreateDataTable() { dt.Columns.Add("ID"); dt.Columns.Add("produt name"); dt.Columns.Add("price"); dt.Columns.Add("QTE"); dt.Columns.Add("Amount"); dt.Columns.Add("Discount(%)"); dt.Columns.Add("Total cost"); dataGridView1.DataSource = dt; //DataGridViewButtonColumn btn = new DataGridViewButtonColumn(); //btn.HeaderText = "select"; //btn.Text = "search"; //btn.UseColumnTextForButtonValue = true; //dataGridView1.Columns.Insert(0, btn); } public F_sale() { InitializeComponent(); CreateDataTable(); txtsaller.Text = Program.salesman.ToString(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void btnOK_Click(object sender, EventArgs e) { this.txtorid.Text = _Order.Get_last_Order_id().Rows[0][0].ToString(); } private void btnser_Click(object sender, EventArgs e) { F_allcus _Allcus = new F_allcus(); _Allcus.ShowDialog(); this.txtcusid.Text = _Allcus.dvc.CurrentRow.Cells[0].Value.ToString(); this.txtfname.Text = _Allcus.dvc.CurrentRow.Cells[1].Value.ToString(); this.txtlname.Text = _Allcus.dvc.CurrentRow.Cells[2].Value.ToString(); this.txtph.Text = _Allcus.dvc.CurrentRow.Cells[3].Value.ToString(); this.txtemail.Text = _Allcus.dvc.CurrentRow.Cells[4].Value.ToString(); } private void label13_Click(object sender, EventArgs e) { } private void groupBox3_Enter(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { clearbox(); F_prodview f_Prodview = new F_prodview(); f_Prodview.ShowDialog(); txtidpro.Text = f_Prodview.dvp.CurrentRow.Cells[0].Value.ToString(); textBoxname.Text = f_Prodview.dvp.CurrentRow.Cells[1].Value.ToString(); textBoxprice.Text = f_Prodview.dvp.CurrentRow.Cells[3].Value.ToString(); textBoxqte.Focus(); } private void textBoxqte_KeyPress(object sender, KeyPressEventArgs e) { if(!char.IsDigit(e.KeyChar)&& e.KeyChar!=8) { e.Handled = true; } } private void textBoxprice_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8 && e.KeyChar != Convert.ToChar( System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)) { e.Handled = true; } } private void textBoxprice_KeyDown(object sender, KeyEventArgs e) { if(e.KeyCode==Keys.Enter && textBoxprice.Text!=string.Empty) { textBoxqte.Focus(); } } private void textBoxqte_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter && textBoxqte.Text != string.Empty) { textBoxqte.Focus(); } } private void textBoxprice_KeyUp(object sender, KeyEventArgs e) { Calculateamount(); totalcost(); } private void textBoxqte_KeyUp(object sender, KeyEventArgs e) { Calculateamount(); totalcost(); } private void textBoxdis_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar) && e.KeyChar != 8) { e.Handled = true; } } private void textBoxdis_KeyUp(object sender, KeyEventArgs e) { totalcost(); } private void textBoxdis_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { } private void button1_Click(object sender, EventArgs e) { _Order.Add_order(Convert.ToInt32(txtorid.Text),Convert.ToInt32(txtcusid.Text),txtdesor.Text,txtsaller.Text,dateTimePicker1.Value); //for(int i =0; i<dataGridView1.Rows.Count - 1; i++) //{ // _Order.Add_order_details(Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value.ToString()), // txtorid.Text, // Convert.ToInt32(dataGridView1.Rows[i].Cells[3].Value), // Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value), // Convert.ToString(dataGridView1.Rows[i].Cells[5].Value), // dataGridView1.Rows[i].Cells[4].Value.ToString(), // dataGridView1.Rows[i].Cells[6].Value.ToString() // ); //} MessageBox.Show("succsfully Added", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void textBoxdis_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { for(int i = 0; i<dataGridView1.Rows.Count - 1;i++) { if (dataGridView1.Rows[i].Cells[0].Value.ToString() == txtidpro.Text) { MessageBox.Show("product exist", "alert", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } } DataRow dr = dt.NewRow(); dr[0] = txtidpro.Text; dr[1] = textBoxname.Text; dr[2] = textBoxprice.Text; dr[3] = textBoxqte.Text; dr[4] = textBoxamount.Text; dr[5] = textBoxdis.Text; dr[6] = textBoxcost.Text; dt.Rows.Add(dr); dataGridView1.DataSource = dt; clearbox(); texttoalprice.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[6].FormattedValue.ToString() != string.Empty select Convert.ToDouble(row.Cells[6].FormattedValue)).Sum().ToString(); } } private void dataGridView1_DoubleClick(object sender, EventArgs e) { try { txtidpro.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString(); textBoxname.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString(); textBoxprice.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString(); textBoxqte.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString(); textBoxamount.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString(); textBoxdis.Text = this.dataGridView1.CurrentRow.Cells[5].Value.ToString(); textBoxcost.Text = this.dataGridView1.CurrentRow.Cells[6].Value.ToString(); dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index); textBoxqte.Focus(); } catch { return; } } private void dataGridView1_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { texttoalprice.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[6].FormattedValue.ToString() != string.Empty select Convert.ToDouble(row.Cells[6].FormattedValue)).Sum().ToString(); } private void btnPrint_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; int orderid = Convert.ToInt32(_Order.Get_last_Order_id_print().Rows[0][0]); REPORT.bill bill = new REPORT.bill(); REPORT.F_RPT_PRODUCT f_RPT_PRODUCT = new REPORT.F_RPT_PRODUCT(); bill.SetDataSource(_Order.Getorders(orderid)); f_RPT_PRODUCT.crystalReportViewer1.ReportSource = bill; f_RPT_PRODUCT.ShowDialog(); this.Cursor = Cursors.Default; } } } <file_sep>/Inventory_Management/BL/C_Products.cs using Inventory_Management.DAL; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Inventory_Management.BL { class C_Products { DataAccessLayer cs = new DataAccessLayer(); public DataTable Get_All_Categories() { DataTable dt = new DataTable(); dt = cs.SelectData("Get_All_Categories", null); return dt; } public DataTable Get_All_Products() { DataTable dt = new DataTable(); dt = cs.SelectData("Get_All_Products", null); return dt; } public DataTable search_product(string name) { DataTable dt = new DataTable(); SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@ID", SqlDbType.NVarChar, 30); parameters[0].Value = name; dt = cs.SelectData("search_product", parameters); cs.Close(); return dt; } public DataTable search_cos(string name) { DataTable dt = new DataTable(); SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@name", SqlDbType.NVarChar, 50); parameters[0].Value = name; dt = cs.SelectData("search_cos", parameters); cs.Close(); return dt; } public DataTable getimage(string name) { DataTable dt = new DataTable(); SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@ID", SqlDbType.NVarChar, 30); parameters[0].Value = name; dt = cs.SelectData("getimge", parameters); cs.Close(); return dt; } public void Add_Product(int ID_Catg,string ID_PROD,string PROD_NAME,int QTE,string PRICE,byte[] IMG) { cs.Open(); SqlParameter[] param = new SqlParameter[6]; param[0] = new SqlParameter("@ID_Catg", SqlDbType.Int); param[0].Value = ID_Catg; param[1] = new SqlParameter("@ID_PROD", SqlDbType.NVarChar); param[1].Value = ID_PROD; param[2] = new SqlParameter("@name", SqlDbType.NVarChar); param[2].Value = PROD_NAME; param[3] = new SqlParameter("@QTE", SqlDbType.Int); param[3].Value = QTE; param[4] = new SqlParameter("@price", SqlDbType.NVarChar); param[4].Value = PRICE; param[5] = new SqlParameter("@img", SqlDbType.Image); param[5].Value = IMG; cs.ExecuteCommand("Add_Product", param); cs.Close(); } public void UpdateProdect(int ID_Catg, string ID_PROD, string PROD_NAME, int QTE, string PRICE, byte[] IMG) { SqlParameter[] param = new SqlParameter[6]; param[0] = new SqlParameter("@ID_Catg", SqlDbType.Int); param[0].Value = ID_Catg; param[1] = new SqlParameter("@ID_PROD", SqlDbType.NVarChar); param[1].Value = ID_PROD; param[2] = new SqlParameter("@name", SqlDbType.NVarChar); param[2].Value = PROD_NAME; param[3] = new SqlParameter("@QTE", SqlDbType.Int); param[3].Value = QTE; param[4] = new SqlParameter("@price", SqlDbType.NVarChar); param[4].Value = PRICE; param[5] = new SqlParameter("@img", SqlDbType.Image); param[5].Value = IMG; cs.Open(); cs.ExecuteCommand("UpdateProdect", param); cs.Close(); } public DataTable checkProductID(string id) { cs.Open(); DataTable dt = new DataTable(); SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@ID", SqlDbType.NVarChar ,30); param[0].Value = id; dt = cs.SelectData("checkProductID", null); cs.Close(); return dt; } public void Delete_Product(string ID_Prod) { cs.Open(); SqlParameter[] param = new SqlParameter[1]; param[0] = new SqlParameter("@ID", SqlDbType.NVarChar); param[0].Value = ID_Prod; cs.ExecuteCommand("delete_product", param); cs.Close(); } } } <file_sep>/Inventory_Management/PL/F_Login.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_Login : Form { BL.C_Login log = new BL.C_Login(); F_Main main = new F_Main(); public F_Login() { InitializeComponent(); } private void btn_exit_Click(object sender, EventArgs e) { Close(); } private void btn_log_Click(object sender, EventArgs e) { DataTable dt = log.login(textBox1.Text, textBox2.Text); if (dt.Rows.Count > 0) { if (dt.Rows[0][2].ToString() == "Admin") { F_Main main = Application.OpenForms["F_Main"] as F_Main; main.cusomersToolStripMenuItem.Enabled = true; main.productToolStripMenuItem.Enabled = true; main.backupDataToolStripMenuItem.Enabled = true; main.usersToolStripMenuItem.Enabled = true; Program.salesman = dt.Rows[0]["FullName"].ToString(); Close(); } else if (dt.Rows[0][2].ToString() == "User") { F_Main main = Application.OpenForms["F_Main"] as F_Main; main.cusomersToolStripMenuItem.Enabled = true; main.productToolStripMenuItem.Enabled = true; main.usersToolStripMenuItem.Enabled = false; Program.salesman = dt.Rows[0]["FullName"].ToString(); Close(); } } else { MessageBox.Show("Username or password is wrong"); } } } } <file_sep>/Inventory_Management/PL/F_Backup.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Security.AccessControl; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_Backup : Form { SqlConnection SqlConnection = new SqlConnection(@"Server=.\SQLEXPRESS;Database=QM;Integrated Security=true"); SqlCommand cmd = new SqlCommand(); public F_Backup() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { if(folderBrowserDialog1.ShowDialog()==DialogResult.OK) { textBox1.Text = folderBrowserDialog1.SelectedPath; } } private void btnCnl_Click(object sender, EventArgs e) { Close(); } private void btnOK_Click(object sender, EventArgs e) { string fileName = textBox1.Text + "\\QM"+DateTime.Now.ToShortDateString().Replace('/','-')+" - "+DateTime.Now.ToLongTimeString().Replace(':','-'); string str = "Backup Database QM to Disk='" + fileName+".bak'"; cmd = new SqlCommand(str, SqlConnection); SqlConnection.Open(); cmd.ExecuteNonQuery(); SqlConnection.Close(); MessageBox.Show("done"); } } } <file_sep>/Inventory_Management/PL/F_Users.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_Users : Form { BL.C_Products prd = new BL.C_Products(); SqlConnection SqlConnection = new SqlConnection(@"Server=.\SQLEXPRESS;Database=QM;Integrated Security=true"); SqlDataAdapter da; DataTable dt = new DataTable(); BindingManagerBase bmb; SqlCommandBuilder builder; public F_Users() { InitializeComponent(); da = new SqlDataAdapter("select ID_CUSTOMER as 'ID', FIRST_NAMR as 'First name',LAST_NAME as 'Last name',TEL,EMAIL from CUSTOMERS", SqlConnection); da.Fill(dt); dataGridView1.DataSource = dt; textBox1.DataBindings.Add("text", dt, "First name"); textBox2.DataBindings.Add("text", dt, "Last name"); textBox3.DataBindings.Add("text", dt, "TEL"); textBox4.DataBindings.Add("text", dt, "EMAIL"); textBox6.DataBindings.Add("text", dt, "ID"); bmb = this.BindingContext[dt]; countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void groupBox2_Enter(object sender, EventArgs e) { } private void btnOK_Click(object sender, EventArgs e) { bmb.AddNew(); btnedit.Enabled = true; btnOK.Enabled = false; textBox1.Focus(); textBox2.Focus(); textBox3.Focus(); textBox4.Focus(); textBox6.Focus(); } private void btnedit_Click(object sender, EventArgs e) { bmb.EndCurrentEdit(); builder = new SqlCommandBuilder(da); da.Update(dt); MessageBox.Show("succsfully Added", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); btnedit.Enabled = false; btnOK.Enabled = true; countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnDel_Click(object sender, EventArgs e) { bmb.RemoveAt(bmb.Position); bmb.EndCurrentEdit(); builder = new SqlCommandBuilder(da); da.Update(dt); MessageBox.Show("succsfully ", "Deleting Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnset_Click(object sender, EventArgs e) { bmb.EndCurrentEdit(); builder = new SqlCommandBuilder(da); da.Update(dt); MessageBox.Show("succsfully ", "Editting Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void button1_Click(object sender, EventArgs e) { bmb.Position = 0; countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void button2_Click(object sender, EventArgs e) { bmb.Position -= 1; countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void button3_Click(object sender, EventArgs e) { bmb.Position += 1; countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void button4_Click(object sender, EventArgs e) { bmb.Position = bmb.Count; countlbl.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnser_Click(object sender, EventArgs e) { DataTable dt = new DataTable(); dt = prd.search_cos(textBox5.Text); dataGridView1.DataSource = dt; } } } <file_sep>/Inventory_Management/PL/F_Main.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.VisualStyles; namespace Inventory_Management.PL { public partial class F_Main : Form { public F_Main() { InitializeComponent(); this.productToolStripMenuItem.Enabled = false; this.usersToolStripMenuItem.Enabled = false; this.cusomersToolStripMenuItem.Enabled = false; this.backupDataToolStripMenuItem.Enabled = false; this.restoreDataToolStripMenuItem.Enabled = false; this.button4.Enabled = false; this.button3.Enabled = false; this.button5.Enabled = false; } private void F_Main_Load(object sender, EventArgs e) { } private void logInToolStripMenuItem_Click(object sender, EventArgs e) { F_Login login = new F_Login(); login.ShowDialog(); this.button4.Enabled = true; this.button3.Enabled = true; this.button5.Enabled = true; } private void addProductToolStripMenuItem_Click(object sender, EventArgs e) { F_AddProduct f_Add = new F_AddProduct(); f_Add.ShowDialog(); } private void productManagingToolStripMenuItem_Click(object sender, EventArgs e) { F_ProductsManaging managing = new F_ProductsManaging(); managing.ShowDialog(); } private void categuryManagingToolStripMenuItem_Click(object sender, EventArgs e) { F_CatManaging _CatManaging = new F_CatManaging(); _CatManaging.ShowDialog(); } private void usersManagingToolStripMenuItem_Click(object sender, EventArgs e) { F_AddUsers f_AddUsers = new F_AddUsers(); f_AddUsers.ShowDialog(); } private void newSellToolStripMenuItem_Click(object sender, EventArgs e) { F_sale f_Sale = new F_sale(); f_Sale.ShowDialog(); } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void button3_Click(object sender, EventArgs e) { productManagingToolStripMenuItem.PerformClick(); } private void button4_Click(object sender, EventArgs e) { customersManagingToolStripMenuItem.PerformClick(); } private void button5_Click(object sender, EventArgs e) { newSellToolStripMenuItem.PerformClick(); } private void button2_Click(object sender, EventArgs e) { logInToolStripMenuItem.PerformClick(); } private void customersManagingToolStripMenuItem_Click(object sender, EventArgs e) { F_Users f_Users = new F_Users(); f_Users.ShowDialog(); } private void backupDataToolStripMenuItem_Click(object sender, EventArgs e) { F_Backup f_Backup = new F_Backup(); f_Backup.ShowDialog(); } } } <file_sep>/Inventory_Management/PL/F_allcus.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_allcus : Form { SqlConnection SqlConnection = new SqlConnection(@"Server=.\SQLEXPRESS;Database=QM;Integrated Security=true"); SqlDataAdapter da; DataTable dt = new DataTable(); BindingManagerBase bmb; SqlCommandBuilder builder; public F_allcus() { InitializeComponent(); da = new SqlDataAdapter("select ID_CUSTOMER as 'ID', FIRST_NAMR as 'First name',LAST_NAME as 'Last name',TEL,EMAIL from CUSTOMERS", SqlConnection); da.Fill(dt); dvc.DataSource = dt; } private void dvc_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void dvc_DoubleClick(object sender, EventArgs e) { this.Close(); } } } <file_sep>/Inventory_Management/BL/C_Order.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using Inventory_Management.DAL; using System.Data; namespace Inventory_Management.BL { class C_Order { DataAccessLayer cs = new DataAccessLayer(); public DataTable Get_last_Order_id() { DataTable dt = new DataTable(); dt = cs.SelectData("get_lastorder_id", null); return dt; } public DataTable Get_last_Order_id_print() { DataTable dt = new DataTable(); dt = cs.SelectData("get_lastorder_id_print", null); return dt; } public DataTable Getorders(int id_order) { DAL.DataAccessLayer dataAccessLayer = new DataAccessLayer(); DataTable DT = new DataTable(); SqlParameter[] parameters = new SqlParameter[1]; parameters[0] = new SqlParameter("@id_order", SqlDbType.Int); parameters[0].Value = id_order; DT = dataAccessLayer.SelectData("get_orders", parameters); dataAccessLayer.Close(); return DT; } public void Add_order(int id_order, int CUSTOMER_ID, string DESCRPTION_ORDER, string SALESMAN, DateTime DATE_ORDER) { cs.Open(); SqlParameter[] param = new SqlParameter[5]; param[0] = new SqlParameter("@date", SqlDbType.DateTime); param[0].Value = DATE_ORDER; param[1] = new SqlParameter("@Order_des", SqlDbType.NVarChar); param[1].Value = DESCRPTION_ORDER; param[2] = new SqlParameter("@ID_customer", SqlDbType.Int); param[2].Value = CUSTOMER_ID; param[3] = new SqlParameter("@saller", SqlDbType.NVarChar); param[3].Value = SALESMAN; param[4] = new SqlParameter("@ID_order", SqlDbType.Int); param[4].Value = id_order; cs.ExecuteCommand("add_orderr ", param); cs.Close(); } public void Add_order_details(int id_order, string ID_product,int qte,float discount, string price, string amount, string total_amount) { cs.Open(); SqlParameter[] param = new SqlParameter[7]; param[0] = new SqlParameter("@ID_order", SqlDbType.Int); param[0].Value = id_order; param[1] = new SqlParameter("@ID_product", SqlDbType.NVarChar); param[1].Value = ID_product; param[2] = new SqlParameter("@qte", SqlDbType.Int); param[2].Value = qte; param[3] = new SqlParameter("@price", SqlDbType.NVarChar); param[3].Value = price; param[4] = new SqlParameter("@discount", SqlDbType.Float); param[4].Value = discount; param[5] = new SqlParameter("@amount", SqlDbType.NVarChar); param[5].Value = price; param[6] = new SqlParameter("@total_amount", SqlDbType.NVarChar); param[6].Value = total_amount; cs.ExecuteCommand("add_order_details", param); cs.Close(); } } } <file_sep>/Inventory_Management/PL/F_AddProduct.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_AddProduct : Form { BL.C_Products prd = new BL.C_Products(); public string state = "add"; public F_AddProduct() { InitializeComponent(); comboBox1.DataSource = prd.Get_All_Categories(); comboBox1.DisplayMember = "DESCRPTION_CAT"; comboBox1.ValueMember = "ID"; } private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog(); openFile.Filter="Image File |*.jpg; *.png;"; if(openFile.ShowDialog()==DialogResult.OK) { pictureBox1.Image = Image.FromFile(openFile.FileName); } } private void button3_Click(object sender, EventArgs e) { Close(); } private void btnOK_Click(object sender, EventArgs e) { if (state == "add") { MemoryStream stream = new MemoryStream(); pictureBox1.Image.Save(stream, pictureBox1.Image.RawFormat); byte[] byteimage = stream.ToArray(); prd.Add_Product(Convert.ToInt32(comboBox1.SelectedValue), txtDes.Text, txtID.Text, Convert.ToInt32(txtQun.Text), txtPrice.Text, byteimage); MessageBox.Show("succsfully Added", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MemoryStream stream = new MemoryStream(); pictureBox1.Image.Save(stream, pictureBox1.Image.RawFormat); byte[] byteimage = stream.ToArray(); prd.UpdateProdect(Convert.ToInt32(comboBox1.SelectedValue), txtDes.Text, txtID.Text, Convert.ToInt32(txtQun.Text), txtPrice.Text, byteimage); MessageBox.Show("succsfully Updated", "Update product", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void txtID_Validating(object sender, CancelEventArgs e) { //DataTable dt = new DataTable(); ////dt = prd.checkProductID(txtID.Text); ////if(dt.Rows.Count>0) ////{ //// MessageBox.Show("Already Exist", "Warrning", MessageBoxButtons.OK, MessageBoxIcon.Warning); ////} } private void txtID_Validated(object sender, EventArgs e) { //DataTable dt = new DataTable(); //dt = prd.checkProductID(txtID.Text); //if (dt.Rows.Count > 0) //{ // MessageBox.Show("Already Exist", "Warrning", MessageBoxButtons.OK, MessageBoxIcon.Warning); //} } } } <file_sep>/Inventory_Management/PL/F_AddUsers.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_AddUsers : Form { BL.C_Login lg = new BL.C_Login(); public F_AddUsers() { InitializeComponent(); } private void label2_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void btnOK_Click(object sender, EventArgs e) { if(textBox1.Text==string.Empty||textBox2.Text==string.Empty||textBox3.Text==string.Empty||textBox4.Text==string.Empty) { MessageBox.Show("please fill the blanks", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (textBox3.Text != textBox4.Text) { MessageBox.Show("password not the same", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } lg.Add_User(textBox1.Text,textBox2.Text,textBox3.Text,comboBox1.Text); MessageBox.Show("succsfully Added", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); textBox1.Clear(); textBox2.Clear(); textBox3.Clear(); textBox4.Clear(); textBox1.Focus(); } private void btnCnl_Click(object sender, EventArgs e) { this.Close(); } private void textBox4_Validated(object sender, EventArgs e) { if(textBox3.Text!=textBox4.Text) { MessageBox.Show("password not the same", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } } <file_sep>/Inventory_Management/BL/C_Login.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; using Inventory_Management.DAL; namespace Inventory_Management.BL { class C_Login { DataAccessLayer cs = new DataAccessLayer(); public DataTable login(string username, string password) { SqlParameter[] parameters = new SqlParameter[2]; parameters[0] = new SqlParameter("@ID", SqlDbType.NVarChar, 50); parameters[0].Value = username; parameters[1] = new SqlParameter("@PWD", SqlDbType.NVarChar, 50); parameters[1].Value = password; DataTable dt = new DataTable(); dt = cs.SelectData("sp_login", parameters); return dt; } public void Add_User( string ID, string FULLNAME, string PWD,string USERTYPE) { cs.Open(); SqlParameter[] param = new SqlParameter[4]; param[0] = new SqlParameter("@ID", SqlDbType.NVarChar); param[0].Value = ID; param[1] = new SqlParameter("@FULLNAME", SqlDbType.NVarChar); param[1].Value = FULLNAME; param[2] = new SqlParameter("@PWD", SqlDbType.NVarChar); param[2].Value = PWD; param[3] = new SqlParameter("@USERTYPE", SqlDbType.NVarChar); param[3].Value = USERTYPE; cs.ExecuteCommand("add_user", param); cs.Close(); } } } <file_sep>/Inventory_Management/PL/F_CatManaging.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace Inventory_Management.PL { public partial class F_CatManaging : Form { SqlConnection SqlConnection = new SqlConnection(@"Server=.\SQLEXPRESS;Database=QM;Integrated Security=true"); SqlDataAdapter da; DataTable dt=new DataTable(); BindingManagerBase bmb; SqlCommandBuilder builder; public F_CatManaging() { InitializeComponent(); da = new SqlDataAdapter("select ID,DESCRPTION_CAT as 'Category' from CATEGORIES", SqlConnection); da.Fill(dt); dataGridView1.DataSource = dt; txtID.DataBindings.Add("text", dt, "ID"); txtDes.DataBindings.Add("text", dt, "Category"); bmb = this.BindingContext[dt]; label3.Text = (bmb.Position+1) + " / " + bmb.Count; } private void button2_Click(object sender, EventArgs e) { bmb.Position -= 1; label3.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void button4_Click(object sender, EventArgs e) { bmb.Position = bmb.Count; label3.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void button1_Click(object sender, EventArgs e) { bmb.Position = 0; label3.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void button3_Click(object sender, EventArgs e) { bmb.Position += 1; label3.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnOK_Click(object sender, EventArgs e) { bmb.AddNew(); btnedit.Enabled = true; btnOK.Enabled = false; int id = Convert.ToInt32(dt.Rows[dt.Rows.Count - 1][0])+1; txtID.Text = id.ToString(); txtDes.Focus(); } private void btnedit_Click(object sender, EventArgs e) { bmb.EndCurrentEdit(); builder = new SqlCommandBuilder(da); da.Update(dt); MessageBox.Show("succsfully Added", "Adding Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); btnedit.Enabled = false; btnOK.Enabled = true; label3.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnDel_Click(object sender, EventArgs e) { bmb.RemoveAt(bmb.Position); bmb.EndCurrentEdit(); builder = new SqlCommandBuilder(da); da.Update(dt); MessageBox.Show("succsfully ", "Deleting Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); label3.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnset_Click(object sender, EventArgs e) { bmb.EndCurrentEdit(); builder = new SqlCommandBuilder(da); da.Update(dt); MessageBox.Show("succsfully ", "Editting Opration", MessageBoxButtons.OK, MessageBoxIcon.Information); label3.Text = (bmb.Position + 1) + " / " + bmb.Count; } private void btnPrint_Click(object sender, EventArgs e) { REPORT.rpt_cat_single rpt_Getall_ = new REPORT.rpt_cat_single(); REPORT.F_RPT_PRODUCT rPT_PRODUCT = new REPORT.F_RPT_PRODUCT(); rpt_Getall_.SetParameterValue("@ID", Convert.ToInt32(txtID.Text)); rPT_PRODUCT.crystalReportViewer1.ReportSource = rpt_Getall_; rPT_PRODUCT.ShowDialog(); } } } <file_sep>/Inventory_Management/PL/F_prodview.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_prodview : Form { BL.C_Products C_Products = new BL.C_Products(); public F_prodview() { InitializeComponent(); dvp.DataSource = C_Products.Get_All_Products(); } private void dvp_DoubleClick(object sender, EventArgs e) { Close(); } } } <file_sep>/Inventory_Management/PL/F_ProductsManaging.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Inventory_Management.PL { public partial class F_ProductsManaging : Form { BL.C_Products prd = new BL.C_Products(); public F_ProductsManaging() { InitializeComponent(); this.dataGridView1.DataSource = prd.Get_All_Products(); } private void button4_Click(object sender, EventArgs e) { Close(); } private void textBox1_TextChanged(object sender, EventArgs e) { DataTable dt = new DataTable(); dt = prd.search_product(textBox1.Text); dataGridView1.DataSource = dt; } private void btnOK_Click(object sender, EventArgs e) { F_AddProduct f_ = new F_AddProduct(); f_.ShowDialog(); } private void button1_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure ?", "Deleting item", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes) { prd.Delete_Product(dataGridView1.CurrentRow.Cells[0].Value.ToString()); MessageBox.Show("Done", "Deleting item", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Canceld", " Deleting item", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } dataGridView1.DataSource = prd.Get_All_Products(); } private void button2_Click(object sender, EventArgs e) { F_AddProduct f_ = new F_AddProduct(); f_.txtID.Text = dataGridView1.CurrentRow.Cells[0].Value.ToString(); f_.txtDes.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString(); f_.txtQun.Text = dataGridView1.CurrentRow.Cells[2].Value.ToString(); f_.txtPrice.Text = dataGridView1.CurrentRow.Cells[3].Value.ToString(); f_.comboBox1.Text = dataGridView1.CurrentRow.Cells[4].Value.ToString(); f_.Text = "Update Prodect" + dataGridView1.CurrentRow.Cells[1].Value.ToString(); f_.state = "update"; byte[] image = (byte[])prd.getimage(dataGridView1.CurrentRow.Cells[0].Value.ToString()).Rows[0][0]; MemoryStream ms = new MemoryStream(image); f_.pictureBox1.Image = Image.FromStream(ms); f_.ShowDialog(); } private void button3_Click(object sender, EventArgs e) { F_view f_ = new F_view(); byte[] image = (byte[])prd.getimage(dataGridView1.CurrentRow.Cells[0].Value.ToString()).Rows[0][0]; MemoryStream ms = new MemoryStream(image); f_.pictureBox1.Image = Image.FromStream(ms); f_.ShowDialog(); } private void button5_Click(object sender, EventArgs e) { REPORT.RPT_PRODUCT_1 rPT_ = new REPORT.RPT_PRODUCT_1(); rPT_.SetParameterValue("@ID", this.dataGridView1.CurrentRow.Cells[0].Value.ToString()); REPORT.F_RPT_PRODUCT rPT_PRODUCT = new REPORT.F_RPT_PRODUCT(); rPT_PRODUCT.crystalReportViewer1.ReportSource = rPT_; rPT_PRODUCT.ShowDialog(); } private void button6_Click(object sender, EventArgs e) { REPORT.rpt_getall_products rpt_Getall_ = new REPORT.rpt_getall_products(); REPORT.F_RPT_PRODUCT rPT_PRODUCT = new REPORT.F_RPT_PRODUCT(); rPT_PRODUCT.crystalReportViewer1.ReportSource = rpt_Getall_; rPT_PRODUCT.ShowDialog(); } } }
c3a3d3f937ffd06460df0b33b65f39d5f9b239d5
[ "C#" ]
14
C#
samerxy/QM
4a39a8d90f2c931237da96a2679e24c74e3a7c9c
bb6db4ae794c55dbae98a0f8f8cb715bf855882a
refs/heads/master
<file_sep>from dotenv import load_dotenv load_dotenv() import os import logging import traceback import contextlib import sys from pathlib import Path from io import StringIO from jigsaw.PluginLoader import PluginLoader import nextcord from nextcord.ext import commands from prometheus_async.aio.web import start_http_server from Plugin import AutomataPlugin from Globals import DISABLED_PLUGINS IGNORED_LOGGERS = [ "discord.client", "discord.gateway", "discord.state", "discord.gateway", "discord.http", "websockets.protocol", ] # Configure logger and silence ignored loggers logging.basicConfig( format="{%(asctime)s} (%(name)s) [%(levelname)s]: %(message)s", datefmt="%x, %X", level=logging.DEBUG, ) for logger in IGNORED_LOGGERS: logging.getLogger(logger).setLevel(logging.WARNING) logger = logging.getLogger("Automata") AUTOMATA_TOKEN = os.getenv("AUTOMATA_TOKEN", None) if not AUTOMATA_TOKEN: logger.error( "AUTOMATA_TOKEN environment variable not set, have you created a .env file and populated it yet?" ) exit(1) intents = nextcord.Intents.default() intents.members = os.getenv("AUTOMATA_MEMBER_INTENTS_ENABLED", "True") == "True" bot = commands.Bot( "!", description="A custom, multi-purpose moderation bot for the MUN Computer Science Society Discord server.", intents=intents, ) bot = commands.Bot(command_prefix="!", help_command=None) @bot.event async def on_message(message): # Log messages if isinstance(message.channel, nextcord.DMChannel): name = message.author.name else: name = message.channel.name logger.info(f"[{name}] {message.author.name}: {message.content}") await bot.process_commands(message) @bot.event async def on_ready(): # When the bot is ready, start the prometheus client await start_http_server(port=9000) if os.getenv("SENTRY_DSN", None): @bot.event async def on_error(event, *args, **kwargs): raise @bot.event async def on_command_error(ctx, exception): raise exception @contextlib.contextmanager def stdioreader(): old = (sys.stdout, sys.stderr) stdout = StringIO() stderr = StringIO() sys.stdout = stdout sys.stderr = stderr yield stdout, stderr sys.stdout = old[0] sys.stderr = old[1] @bot.command(name="eval") @commands.is_owner() async def eval_code(ctx: commands.Context, code: str): """Evaluates code for debugging purposes.""" try: result = f"```\n{eval(code)}\n```" colour = nextcord.Colour.green() except: result = f"```py\n{traceback.format_exc(1)}```" colour = nextcord.Colour.red() result.replace("\\", "\\\\") embed = nextcord.Embed() embed.add_field(name=code, value=result) embed.colour = colour await ctx.send(embed=embed) @bot.command(name="exec") @commands.is_owner() async def exec_code(ctx: commands.Context, code: str): """Executes code for debugging purposes.""" with stdioreader() as (out, err): try: exec(code) result = f"```\n{out.getvalue()}\n```" colour = nextcord.Colour.green() except: result = f"```py\n{traceback.format_exc(1)}```" colour = nextcord.Colour.red() result.replace("\\", "\\\\") embed = nextcord.Embed() embed.add_field(name=code, value=result) embed.colour = colour await ctx.send(embed=embed) @bot.command() async def plugins(ctx: commands.Context): """Lists all enabled plugins.""" embed = nextcord.Embed() embed.colour = nextcord.Colour.blurple() for plugin in loader.get_all_plugins(): if plugin["plugin"]: embed.add_field( name=plugin["manifest"]["name"], value="{}\nVersion: {}\nAuthor: {}".format( plugin["plugin"].__doc__.rstrip(), plugin["manifest"]["version"], plugin["manifest"]["author"], ), ) await ctx.send(embed=embed) class CustomHelp(commands.DefaultHelpCommand): # ( ͡° ͜ʖ ͡°) """Custom help command""" async def send_bot_help(self, mapping): """Shows a list of commands""" embed = nextcord.Embed(title="Commands Help") embed.colour = nextcord.Colour.blurple() for cog, commands in mapping.items(): command_signatures = [self.get_command_signature(c) for c in commands] if command_signatures: cog_name = getattr(cog, "qualified_name", "No Category") embed.add_field( name=cog_name, value="\n".join(command_signatures), inline=False ) channel = self.get_destination() await channel.send(embed=embed) async def send_command_help(self, command): """Shows how to use each command""" embed_command = nextcord.Embed( title=self.get_command_signature(command), description=command.help ) embed_command.colour = nextcord.Colour.green() channel = self.get_destination() await channel.send(embed=embed_command) async def send_group_help(self, group): """Shows how to use each group of commands""" embed_group = nextcord.Embed( title=self.get_command_signature(group), description=group.short_doc ) for c in group.walk_commands(): embed_group.add_field(name=c, value=c.short_doc, inline=False) embed_group.colour = nextcord.Colour.yellow() channel = self.get_destination() await channel.send(embed=embed_group) async def send_cog_help(self, cog): """Shows how to use each category""" embed_cog = nextcord.Embed( title=cog.qualified_name, description=cog.description ) comms = cog.get_commands() for c in comms: embed_cog.add_field(name=c, value=c.short_doc, inline=False) embed_cog.colour = nextcord.Colour.green() channel = self.get_destination() await channel.send(embed=embed_cog) async def send_error_message(self, error): "shows if command does not exist" embed_error = nextcord.Embed(title="Error", description=error) embed_error.colour = nextcord.Colour.red() channel = self.get_destination() await channel.send(embed=embed_error) bot.help_command = CustomHelp() plugins_dir = Path("./plugins") mounted_plugins_dir = Path("./mounted_plugins") mounted_plugins_dir.mkdir(exist_ok=True) loader = PluginLoader( plugin_paths=(str(plugins_dir), str(mounted_plugins_dir)), plugin_class=AutomataPlugin, ) loader.load_manifests() for plugin in loader.get_all_plugins(): manifest = plugin["manifest"] if manifest["main_class"] not in DISABLED_PLUGINS: loader.load_plugin(manifest, bot) else: logger.info(f"{manifest['name']} disabled.") for plugin in loader.get_all_plugins(): if plugin["plugin"]: plugin["plugin"].enable() bot.run(AUTOMATA_TOKEN) <file_sep>aiohttp==3.7.4.post0 anyio==3.3.2 appdirs==1.4.4 async-timeout==3.0.1 attrs==21.2.0 beautifulsoup4==4.9.3 black==21.7b0 certifi==2021.5.30 chardet==4.0.0 charset-normalizer==2.0.3 click==8.0.1 coverage==5.5 dpytest==0.5.3 h11==0.12.0 httpcore==0.13.7 httpx==0.19.0 idna==3.2 inflection==0.5.1 iniconfig==1.1.1 Jigsaw==3.2.0 lxml==4.6.3 MechanicalSoup==1.1.0 motor==2.4.0 multidict==5.1.0 mypy-extensions==0.4.3 nextcord==2.0.0a3 packaging==21.0 pathspec==0.9.0 pluggy==0.13.1 prometheus-async==19.2.0 prometheus-client==0.11.0 py==1.10.0 pydantic==1.8.2 pyhumps==3.0.2 pymongo==3.12.0 pyparsing==2.4.7 pytest==6.2.4 pytest-asyncio==0.15.1 pytest-cov==2.12.1 python-dotenv==0.18.0 pytz==2021.3 regex>=2021.7.6 requests==2.26.0 rfc3986==1.5.0 sentry-sdk==1.3.0 setuptools-scm==6.0.1 sniffio==1.2.0 soupsieve==2.2.1 toml==0.10.2 tomli==1.0.4 typed-ast==1.4.3 typing-extensions==3.10.0.0 urllib3==1.26.6 websockets==9.1 wrapt==1.12.1 yarl==1.6.3 nltk~=3.6.5
b335f7b75eecb8a50d14d74c911333135e700db8
[ "Python", "Text" ]
2
Python
Irfanul383/Automata
f34a329d161111ee42caaf5fd2bca8d3a202ed39
d806a0c995adebc2e54d5d472a83ddce81449978
refs/heads/master
<file_sep>/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const AdminConnection = require('composer-admin').AdminConnection; const BrowserFS = require('browserfs/dist/node/index'); const BusinessNetworkConnection = require('composer-client').BusinessNetworkConnection; const BusinessNetworkDefinition = require('composer-common').BusinessNetworkDefinition; const path = require('path'); require('chai').should(); const bfs_fs = BrowserFS.BFSRequire('fs'); const NS = 'org.acme.mynetwork'; describe('Saying Thanks', () => { // let adminConnection; let businessNetworkConnection; before(() => { BrowserFS.initialize(new BrowserFS.FileSystem.InMemory()); const adminConnection = new AdminConnection({ fs: bfs_fs }); return adminConnection.createProfile('defaultProfile', { type: 'embedded' }) .then(() => { return adminConnection.connect('defaultProfile', 'admin', 'adminpw'); }) .then(() => { return BusinessNetworkDefinition.fromDirectory(path.resolve(__dirname, '..')); }) .then((businessNetworkDefinition) => { return adminConnection.deploy(businessNetworkDefinition); }) .then(() => { businessNetworkConnection = new BusinessNetworkConnection({ fs: bfs_fs }); return businessNetworkConnection.connect('defaultProfile', 'thanks-point', 'admin', 'adminpw'); }); }); describe('#sayThanks', () => { it('should be able to say thanks', () => { const factory = businessNetworkConnection.getBusinessNetwork().getFactory(); // create the company const nec = factory.newResource(NS, 'Company', '6701'); nec.name = 'NEC'; const fj = factory.newResource(NS, 'Company', '6702'); fj.name = 'Fujitsu'; // create the employee const tom = factory.newResource(NS, 'Employee', '6701-000000'); tom.name = 'Tom'; tom.thanksPoint = 100; tom.virtuePoint = 0; tom.employer = factory.newRelationship(NS, 'Company', nec.$identifier); const john = factory.newResource(NS, 'Employee', '6702-000000'); john.name = 'John'; john.thanksPoint = 100; john.virtuePoint = 0; john.employer = factory.newRelationship(NS, 'Company', fj.$identifier); // create the thanks transaction const thanks = factory.newTransaction(NS, 'Thanks'); thanks.sourcer = factory.newRelationship(NS, 'Employee', tom.$identifier); thanks.destinator = factory.newRelationship(NS, 'Employee', john.$identifier); thanks.givePointValue = 10; thanks.message = 'Thank you for your nice idea.'; // thw employer of each employee should be right tom.employer.$identifier.should.equal(nec.$identifier); john.employer.$identifier.should.equal(fj.$identifier); // Get the asset registry. let employeeRegistry; return businessNetworkConnection.getParticipantRegistry(NS + '.Employee') .then((empRegistry) => { employeeRegistry = empRegistry; // add the commodity to the asset registry. return empRegistry.addAll([tom, john]); }) .then(() => { return businessNetworkConnection.getParticipantRegistry(NS + '.Company'); }) .then((participantRegistry) => { // add the traders return participantRegistry.addAll([nec, fj]); }) .then(() => { // submit the transaction return businessNetworkConnection.submitTransaction(thanks); }) .then(() => { // re-get the Tom return employeeRegistry.get(tom.$identifier); }) .then((newTom) => { // the thanksPoint of Tom should be 90 (100 - 10) newTom.thanksPoint.should.equal(90); // the virtuePoint of Tom shoud be 0 (not changed) newTom.virtuePoint.should.equal(0); // re-get the John return employeeRegistry.get(john.$identifier); }) .then((newJohn) => { // the thanksPoint of John should be 100 (not changed) newJohn.thanksPoint.should.equal(100); // the virtuePoint of John shoud be 10 (0 + 10) newJohn.virtuePoint.should.equal(10); }); }); }); });<file_sep># 感謝ポイントシステム ## はじめに Hyperledger Composerを用いたシンプルなポイントシステムのサンプルです。 本サンプルで定義されるエンティティは以下です。 * Participant * Company * Employee * Asset * Candy * Transaction * Thanks * Exchange ## コンセプト Employee同士で感謝をトランザクションThanksとしてやり取りします。<BR> Thanksでは行為の発生元/発生先の他に、やり取りするポイントとメッセージを必要とします。<BR> 人にあげられるポイントと、人からもらったポイントは区別され、両者が循環することはありません。<BR> メッセージに感謝の心がこもっていない場合、トランザクションは成立しません。
3391608e406d8e0ab9f514a4b6c1d2be1f5de565
[ "JavaScript", "Markdown" ]
2
JavaScript
vt750s/thanks-point
52471903403d17fa647ca16c11035b27131ca6e8
614585e750c0fcd222efdd02981dc5258319268c
refs/heads/main
<file_sep>import React, { Component } from "react"; import { connect } from 'react-redux' import { MDBContainer, MDBRow, MDBCol, MDBBtn } from 'mdbreact'; import { setUser, unsubUser } from "../store/actionsCreators/UserActionCreator"; class Users extends Component { constructor(props) { super(props); this.state = { name: "", age: 0 } } renderLoginForm = () => { return ( <> <MDBContainer> <MDBRow> <MDBCol md="6"> <p className="h4 text-center mb-4">Sign in</p> <label htmlFor="defaultFormLoginEmailEx" className="grey-text"> Your name </label> <input type="text" id="defaultFormLoginEmailEx" className="form-control" value={this.state.name} onChange={(e) => { this.setState({ name: e.target.value }) }} /> <br /> <label htmlFor="defaultFormLoginPasswordEx" className="grey-text"> Your age </label> <input type="number" id="defaultFormLoginPasswordEx" className="form-control" value={this.state.age} onChange={(e) => { this.setState({ age: e.target.value }) }} /> <div className="text-center mt-4"> <button onClick={() => { this.handleSetUsers() }} >Subscribe</button> </div> </MDBCol> </MDBRow> </MDBContainer> </> ) } handleSetUsers = () => { this.props.setUserfunct(this.state.name, this.state.age) } handleUnsubscribeUser = () => { this.props.unsubUserfunct() } render() { return ( <React.Fragment> {this.props.userName != "N-A" ? ( <> <p>Current subscribed user is: </p> <b>Name: </b><p>{this.props.userName}</p> <b>Age: </b><p>{this.props.age}</p> <button onClick={() => { this.handleUnsubscribeUser() }} >Unsubscribe</button> </> ) : this.renderLoginForm()} </React.Fragment> ) } } const mapStateToProps = (state, ownProps) => ({ userName: state.MyReducer.userName, age: state.MyReducer.userAge }) const mapDispatchToProps = (dispatch) => { return { setUserfunct: (name, age) => dispatch(setUser(name, age)), unsubUserfunct: () => dispatch(unsubUser()) } }; // We normally do both in one step, like this: export default connect(mapStateToProps, mapDispatchToProps)(Users) //export default Users <file_sep>// src\store\reducers\index.js import { combineReducers } from "redux"; import MyReducer from "./MyReducer"; /* import other reducers here. . . */ export default combineReducers({ MyReducer }); <file_sep>export const SUBSCRIBE = "SUBSCRIBE"; export const UNSUBSCRIBE = "UNSUBSCRIBE";<file_sep>//src\store\actionsCreators\UserActionCreator.js import { SUBSCRIBE, UNSUBSCRIBE } from "../actionTypes"; import store from "../store"; export const setUser = (name, age) => { return store.dispatch({ type: SUBSCRIBE, payload: { userName: name, userAge: age }, }); } //unsubUser export const unsubUser = (name, age) => { return store.dispatch({ type: UNSUBSCRIBE, payload: { userName: "N-A", userAge: 0 }, }); }
8a21cc5ea99a64d4181b9597b9c8c08cb397c5e3
[ "JavaScript" ]
4
JavaScript
awaisiftikhar003/react-redux-blog
ae2f94efadcdaec1d19d47c5895d6cebc4a1e8b8
bf16b4d2e1072b471e256344028537f556d4b462
refs/heads/master
<file_sep>import { Component } from '@angular/core'; import { Platform } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { AuthService } from './providers/auth/auth.service' import { GeofenceService } from './providers/geofence/geofence.service' @Component({ selector: 'app-root', templateUrl: 'app.component.html' }) export class AppComponent { constructor( private platform: Platform, private splashScreen: SplashScreen, private statusBar: StatusBar, private auth: AuthService, private geofence: GeofenceService, ) { this.initializeApp(); } async initializeApp() { await this.platform.ready() await this.auth.getStoredUser() await this.geofence.getLocations() this.geofence.setUpGeofence() this.statusBar.styleDefault() this.splashScreen.hide() } }<file_sep>import { Injectable } from '@angular/core'; import { Events } from '@ionic/angular' import { ApiProviderService } from '../api/api-provider.service' import { Storage } from '@ionic/storage' @Injectable({ providedIn: 'root' }) export class AuthService { user: any = null USER_STORAGE_KEY = 'user' clientId = 1 clientSecret = '<KEY>' socialGrantId = 2 socialGrantSecret = '<KEY>' constructor( private api: ApiProviderService, private storage: Storage, private events: Events, ) { } async getToken (username, password) { const params = { client_id: this.clientId, client_secret: this.clientSecret, grant_type: 'password', username, password, } try { const resp = await this.api.performPost('/oauth/token', params); if(resp.error) { return resp } const user = await this.fetchUserDetails(resp.access_token, resp.refresh_token) return user } catch(err) { console.log(err) return err } } async fetchUserDetails (accessToken, refreshToken = null, provider = false ) { try { const user = await this.api.performGet('/api/user', { headers: {'Authorization': `Bearer ${accessToken}`} }) if(!user.error) { this.user = { ...user, accessToken, refreshToken, provider } await this.storeUser() } return user } catch(err) { console.log(err) return err } } async getStoredUser () { const user = await this.storage.get(this.USER_STORAGE_KEY) if(user && !this.user) { this.user = user } return user } async storeUser (toStore = this.user) { const user = await this.storage.set(this.USER_STORAGE_KEY, toStore) this.events.publish('user:logged-in', user) return user } async logoutUser () { await this.storage.remove(this.USER_STORAGE_KEY) this.user = null await this.events.publish('user:logged-out') return } async loginUsingSocial(token, provider) { const data = { client_id: this.socialGrantId, client_secret: this.socialGrantSecret, grant_type: 'social', provider, access_token: token, } const providerUser = await this.api.performPost('/oauth/token', data) const user = this.fetchUserDetails(providerUser.access_token, providerUser.refresh_token, provider) return user } } <file_sep>import { TestBed } from '@angular/core/testing'; import { AccidentReportingService } from './accident-reporting.service'; describe('AccidentReportingService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: AccidentReportingService = TestBed.get(AccidentReportingService); expect(service).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { NavigationEnd, Router, ActivatedRoute } from '@angular/router'; import { LoadingController } from '@ionic/angular' import { ApiProviderService } from '../providers/api/api-provider.service' import { AccidentService } from '../providers/accident/accident.service' import { AuthService } from '../providers/auth/auth.service' @Component({ selector: 'app-accident-details', templateUrl: './accident-details.page.html', styleUrls: ['./accident-details.page.scss'], }) export class AccidentDetailsPage implements OnInit { accident: any loading: any sub user: any constructor( private router: Router, public api: ApiProviderService, private loadingCtrl: LoadingController, private accidentService: AccidentService, private route: ActivatedRoute, private auth: AuthService ) { this.user = this.auth.user } async ngOnInit() { await this.onEnter(); } async onEnter(): Promise<void> { try { await this.presentLoading() this.sub = this.route.params.subscribe( async routeParams => { const id = routeParams['id'] console.log(id) this.accident = await this.accidentService.getAccident(id) this.hideLoading() }) } catch(err) { console.log(err) this.hideLoading() } } async presentLoading(message = null) { this.loading = await this.loadingCtrl.create({ message: message || 'Preparing data...' }) this.loading.present() } hideLoading() { if(this.loading) { this.loading.dismiss() } } async markAccidentAsResolved() { await this.presentLoading('Please wait...') await this.api.performPut(`/accidents/${this.accident.id}`, { ...this.accident, status: 0, } ) this.accident.status = 0 await this.loading.dismiss() } async viewMap() { this.router.navigateByUrl(`/accidents/${this.accident.id}/map`) } } <file_sep>import { Injectable, NgZone, Output, EventEmitter } from '@angular/core' import { Events } from '@ionic/angular' import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx' import { Geolocation } from '@ionic-native/geolocation/ngx' import { Geocoder, GeocoderResult, BaseArrayClass} from '@ionic-native/google-maps/ngx' import 'rxjs/add/operator/filter' @Injectable({ providedIn: 'root' }) export class LocationProviderService { @Output() locationChanged = new EventEmitter<any>() userPosition = { lat: null, lng: null, } watch: any constructor( private backgroundGeolocation: BackgroundGeolocation, private geolocation: Geolocation, private zone: NgZone, private events: Events ) {} /** * Gets the user's initial position */ async getInitialPosition() { try { await this.getUserPosition() } catch( err ) { console.log(err) } } async getUserPosition(): Promise<any>{ try { let resp = await this.geolocation.getCurrentPosition({ timeout: 10000 }) this.userPosition.lat = resp.coords.latitude this.userPosition.lng = resp.coords.longitude return this.userPosition } catch( err ) { console.log(err) } return false } /** * Tracks location in the background and foreground */ startTracking( cb = null ) { // Background tracking this.backgroundGeolocation.configure(bgConfig).subscribe((location) => { console.log('Position changed') if(location) { this.zone.run(() => { console.log('Position changed') if(this.userPosition.lat !== location.latitude || this.userPosition.lng !== location.longitude) { this.userPosition.lat = location.latitude; this.userPosition.lng = location.longitude; this.events.publish('location:changed', this.userPosition) } }) } }, err => { console.log(err) }) this.backgroundGeolocation.start().then(() => { console.log('Tracker Started') }) // Foreground tracking // this.watch = this.geolocation.watchPosition(fgConfig).filter((p: any) => p.code === undefined).subscribe((position: Geoposition) => { // // Run update inside of Angular's zone // this.zone.run(() => { // if(this.userPosition.lat !== position.coords.latitude && this.userPosition.lng !== position.coords.longitude) { // this.userPosition.lat = position.coords.latitude; // this.userPosition.lng = position.coords.longitude; // this.events.publish('location:changed', this.userPosition) // } // }); // }); } /** * Ends tracking */ stopTracking() { this.backgroundGeolocation.finish(); this.watch.unsubscribe(); } /** * Extracts the address of a certain location * * @param locations the locations to geocode */ async geocode (place, reverse = false) { let options = {} if(reverse) { options['position'] = place } else{ options['address'] = place } const results: GeocoderResult[] | BaseArrayClass<GeocoderResult[]> = await Geocoder.geocode(options) return results } } const bgConfig = { desiredAccuracy: 0, stationaryRadius: 20, distanceFilter: 10, debug: true, interval: 3000 } const fgConfig = { frequency: 3000, enableHighAccuracy: true }<file_sep>import { Injectable } from '@angular/core'; import { Base64 } from '@ionic-native/base64/ngx' import { AuthService } from '../auth/auth.service' import { ApiProviderService } from '../api/api-provider.service' import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer/ngx' import { SERVER_URL } from '../../../environments/environment' @Injectable({ providedIn: 'root' }) export class AccidentReportingService { fields: any images: any constructor( private base64: Base64, private api: ApiProviderService, private auth: AuthService, private fileTransfer: FileTransfer ) { } addFields (fields: Object) { this.fields = {...this.fields, ...fields} } clearFields () { this.fields = {} } async submit () { console.log(this.fields); const payload = { ...this.fields, user_id: this.auth.user.id, status: 1, } this.images = this.fields.images delete payload.images delete this.fields.images console.log(this.images) const results = await this.api.performPost('/api/accident', payload) let res = results if(this.images.length > 0) { this.images.forEach(async image => { res = await this.uploadImages(results.data.id, image) }) } return res } async processImageUrl (url) { const b64file = await this.base64.encodeFile(url) return b64file } async uploadImages (id, image) { const options = { fileKey: 'accident_photo', fileName: Math.random().toString(16).substr(2, 5), headers: { Authorization: `Bearer ${this.auth.user.accessToken}`, Accept: 'application/json' } } const fileTransfer: FileTransferObject = this.fileTransfer.create() const result = await fileTransfer.upload(image, `${SERVER_URL}/api/accident/${id}/photos`, options) return result } } <file_sep>import { Component, OnInit } from '@angular/core'; import { AuthService } from '../providers/auth/auth.service' import { AlertController, Events } from '@ionic/angular' import { Router } from '@angular/router' @Component({ selector: 'app-profile', templateUrl: './profile.page.html', styleUrls: ['./profile.page.scss'], }) export class ProfilePage implements OnInit { user: any alert: any constructor( private auth: AuthService, private alertCtrl: AlertController, private router: Router, private events: Events ) { } async ngOnInit() { this.user = this.auth.user this.events.subscribe('user:logged-in', (user) => { this.user = user }) } async showAlert() { this.alert = await this.alertCtrl.create({ message: "Are you sure?", buttons: [ { text: 'Dismiss', }, { text: 'Log out', handler: () => { this.logout() } } ] }) this.alert.present() } async logout () { await this.auth.logoutUser() this.user = null this.router.navigate(['/app']) } async goToLogin() { this.router.navigateByUrl('/login') } getUserProfileImage () { return this.user.image_url || `https://api.adorable.io/avatars/155/${this.user.id}.png` } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Platform } from '@ionic/angular' import { AccidentService } from '../providers/accident/accident.service' @Component({ selector: 'app-tabs', templateUrl: 'tabs.page.html', styleUrls: ['tabs.page.scss'] }) export class TabsPage implements OnInit { constructor( private accidentService: AccidentService ) { } async ngOnInit () { await this.accidentService.fetchAccidents() } } <file_sep>import { Component, OnInit, NgZone } from '@angular/core'; import { LoadingController } from '@ionic/angular' import { Platform, } from '@ionic/angular' import { Router } from '@angular/router' import { LocationProviderService } from '../providers/location/location-provider.service' import { AccidentReportingService } from '../providers/accident-reporting/accident-reporting.service' // Google Map import { GoogleMaps, GoogleMap, GoogleMapsEvent, Marker, } from '@ionic-native/google-maps' import { mapStyle } from '../mapStyles' @Component({ selector: 'app-chooselocation', templateUrl: './chooselocation.page.html', styleUrls: ['./chooselocation.page.scss'], }) export class ChooselocationPage implements OnInit { map: GoogleMap userMarker: Marker loadingMessage: any userPosition: { lat: '', lng: '', } constructor( private platform: Platform, private location: LocationProviderService, private router: Router, private loadingCtrl: LoadingController, private zone: NgZone, private accidentReporting: AccidentReportingService ) { } async ngOnInit() { await this.platform.ready() await this.showLoading('Preparing map...') this.userPosition = this.location.userPosition await this.loadMap() } async loadMap() { const {lat, lng} = this.location.userPosition this.map = GoogleMaps.create('location_map', { camera: { target: { lat: lat ? lat: 16.41666, lng: lng ? lng : 120.5999976, }, zoom: 17, tilt: 30 }, styles: mapStyle }) // add a marker this.userMarker = this.map.addMarkerSync({ title: 'Press and drag me or press anywhere on the map to select a location!', position: { lat: lat ? lat: 16.41666, lng: lng ? lng : 120.5999976, }, draggable: true, }); // show the infoWindow this.userMarker.showInfoWindow() if(this.loadingMessage) { this.loadingMessage.dismiss() } this.userMarker.on(GoogleMapsEvent.MARKER_DRAG_END).subscribe((params) => { console.log(params);this.updateUserLocation(params[0]) }) this.map.on(GoogleMapsEvent.MAP_CLICK).subscribe((params) => this.updateUserLocation(params[0])) } goToStepThree() { const { lat, lng } = this.userPosition this.accidentReporting.addFields({lat, lng}) this.router.navigateByUrl('stepthree') } async showLoading(message) { this.loadingMessage = await this.loadingCtrl.create({ message }) this.loadingMessage.present() } updateUserLocation (latLng) { this.userMarker.setPosition(latLng) this.zone.run(() => { this.userPosition = latLng }) } } <file_sep>var schema = { "type": "object", "properties": { "users": { "type": "array", "minItems": 5, "maxItems": 5, "items": { "type": "object", "properties": { "id": { "type": "integer", "initialOffset": 1, "autoIncrement": true, }, "fistname": { "type": "string", "faker": "name.firstName" }, "lastname": { "type": "string", "faker": "name.lastName" }, "email": { "type": "string", "format": "email", "faker": "internet.email" } }, "required": ["id", "firstname", "lastname", "email"] } }, "accidents": { "type": "array", "minItems": 5, "maxItems": 5, "items": { "type": "object", "properties": { "lat": { "type": "number", "minimum": 16.4100, "maximum": 16.4150 }, "lng": { "type": "number", "minimum": 120.600, "maximum": 120.650 }, "user_id": { "type": "integer", "minimum": 1, "maximum": 5, }, "id": { "type": "integer", "initialOffset": 1, "autoIncrement": true, }, "date": { "type": "string", "format": "soon" }, "images": { "type": "array", "minItems": 1, "maxItems": 3, "items": { "uri": { "type": "string", "default": "https://picsum.photos/200/300/?random" } } }, "description": { "type": "string", "faker": "lorem.paragraph" }, "title": { "type": "string", "faker": "lorem.sentence" }, "status": { "type": "integer", "minimum": 0, "maximum": 1, }, "user_id": { "type": "integer", "minimum": 1, "maximum": 5, } }, "required": ["lat", "lng", "id", "date", "images", "status", "description", "title", "user_id"] } }, }, "required": ["users", "accidents"] }; module.exports = schema;<file_sep>import { Component, OnInit } from '@angular/core'; import { LoadingController, Platform } from '@ionic/angular' import { NavigationEnd, Router, ActivatedRoute } from '@angular/router' import { AccidentService } from '../providers/accident/accident.service' // Google Map import { GoogleMaps, GoogleMap, Marker, GoogleMapsAnimation } from '@ionic-native/google-maps'; import {mapStyle} from '../mapStyles' @Component({ selector: 'app-accident-map-view', templateUrl: './accident-map-view.page.html', styleUrls: ['./accident-map-view.page.scss'], }) export class AccidentMapViewPage implements OnInit { loading: any map: GoogleMap accident: any constructor( private router: Router, private accidentService: AccidentService, private route: ActivatedRoute, private loadingCtrl: LoadingController, private platform: Platform ) { } async ngOnInit() { await this.platform.ready() await this.showLoader() this.route.params.subscribe( async ({id}) => { this.accident = await this.accidentService.getAccident(id) await this.prepareMap() await this.hideLoading() }) } async prepareMap() { const {lat, lng} = this.accident this.map = GoogleMaps.create('map', { camera: { target: { lat, lng }, zoom: 17, tilt: 30 }, styles: mapStyle }) this.map.addMarkerSync({ position: { lat, lng, }, icon: { url: require('../../assets/icon/caraccident.png') }, }) this.map.addCircleSync({ 'center': {lat, lng}, 'radius': 200, 'strokeColor' : '#88A000', 'strokeWidth': 1, 'fillColor' : '#880000' }) } async showLoader () { this.loading = await this.loadingCtrl.create({ message: 'Preparing Map' }) this.loading.present() } async hideLoading () { if(this.loading) { await this.loading.dismiss() } return } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { AuthGuardService } from './providers/auth-guard/auth-guard.service' const routes: Routes = [ { path: 'login', loadChildren: './login/login.module#LoginPageModule' }, { path: 'app', loadChildren: './tabs/tabs.module#TabsPageModule', canActivate: [AuthGuardService] }, { path: 'warning', loadChildren: './warning/warning.module#WarningPageModule' }, { path: 'stepone', loadChildren: './stepone/stepone.module#SteponePageModule' }, { path: 'steptwo', loadChildren: './steptwo/steptwo.module#SteptwoPageModule' }, { path: 'stepthree', loadChildren: './stepthree/stepthree.module#StepthreePageModule' }, { path: 'thankyou', loadChildren: './thankyou/thankyou.module#ThankyouPageModule' }, { path: 'chooselocation', loadChildren: './chooselocation/chooselocation.module#ChooselocationPageModule' }, { path: 'accidents-list', loadChildren: './accidents-list/accidents-list.module#AccidentsListPageModule' }, { path: 'accidents/:id', loadChildren: './accident-details/accident-details.module#AccidentDetailsPageModule' }, { path: 'accidents/:id/map', loadChildren: './accident-map-view/accident-map-view.module#AccidentMapViewPageModule' }, { path: '**', redirectTo: 'app' }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule {} <file_sep>import { Component, OnInit } from '@angular/core' import { Router, RouterModule } from '@angular/router' import { Validators, FormBuilder, FormGroup } from '@angular/forms' import { AccidentReportingService } from '../providers/accident-reporting/accident-reporting.service' @Component({ selector: 'app-stepone', templateUrl: './stepone.page.html', styleUrls: ['./stepone.page.scss'], }) export class SteponePage implements OnInit { form: FormGroup constructor( private router: Router, private formBuilder: FormBuilder, private accidentReporting: AccidentReportingService ) { this.form = this.formBuilder.group({ name: ['', Validators.required], description: ['', Validators.maxLength(30)] }) } ngOnInit() { } goToStepTwo() { this.router.navigateByUrl('/steptwo') } processForm() { this.accidentReporting.addFields(this.form.value) this.goToStepTwo() } } <file_sep>import { Injectable } from '@angular/core'; import { ApiProviderService } from '../api/api-provider.service' import { AuthService } from '../auth/auth.service' @Injectable({ providedIn: 'root' }) export class AccidentService { selectedAccident: any accidents: Array<any> = [] accidentProneAreas: Array<any> = [] headers: any = null constructor( private api: ApiProviderService, private auth: AuthService ) { } async fetchAccidents (): Promise<Array<any>> { try { const accidents = await this.api.performGet('/api/accidents') this.accidents = accidents.data return this.accidents } catch(err) { console.log(err) } } async getAccidentPrones (): Promise<Array<any>> { return new Promise <Array<any>>((resolve) => { if(!this.accidents) resolve() let group = [] this.accidents.forEach(accident => { const place = `${accident.street}, ${accident.city}, ${accident.state}, ${accident.region}` const groupData = group.find(el => el.place === place) if(groupData) { groupData.numOfAccidents = groupData.numOfAccidents + 1 } else { group.push({ place, numOfAccidents: 1, }) } }) this.accidentProneAreas = group.filter( el => el.numOfAccidents > 5 ) resolve(this.accidentProneAreas) }) } async fetchAccident (id) { try { this.selectedAccident = await this.api.performGet(`/accidents/${id}`) this.accidents.push(this.selectedAccident) return this.selectedAccident } catch(err) { console.log(err) } } async getAccident (id, setSelected = false) { if( this.accidents !== null ) { const accident = this.accidents.find( accident => accident.id == id ) if(setSelected) this.selectedAccident = accident return accident } else { return await this.fetchAccident(id) } } } <file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { RouteReuseStrategy } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms' import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http' import { IonicModule, IonicRouteStrategy } from '@ionic/angular'; import { SplashScreen } from '@ionic-native/splash-screen/ngx'; import { StatusBar } from '@ionic-native/status-bar/ngx'; import { BackgroundGeolocation } from '@ionic-native/background-geolocation/ngx' import { Geolocation } from '@ionic-native/geolocation/ngx' import { Geofence } from '@ionic-native/geofence/ngx' import { ImagePicker } from '@ionic-native/image-picker/ngx' import { Base64 } from '@ionic-native/base64/ngx' import { Camera } from '@ionic-native/camera/ngx' // import { NativeStorage } from '@ionic-native/native-storage/ngx' import { IonicStorageModule } from '@ionic/storage' import { GooglePlus } from '@ionic-native/google-plus/ngx' import { Facebook } from '@ionic-native/facebook/ngx' import { WebView } from '@ionic-native/ionic-webview/ngx' import { FileTransfer } from '@ionic-native/file-transfer/ngx' import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AuthGuardService } from './providers/auth-guard/auth-guard.service' import { AuthInterceptorService } from './providers/auth-interceptor/auth-interceptor.service' @NgModule({ declarations: [AppComponent], entryComponents: [], imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule, FormsModule, ReactiveFormsModule, HttpClientModule,IonicStorageModule.forRoot()], providers: [ StatusBar, SplashScreen, { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }, BackgroundGeolocation, Geolocation, Geofence, ImagePicker, Base64, Camera, IonicStorageModule, { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptorService, multi: true }, AuthInterceptorService, AuthGuardService, GooglePlus, Facebook, WebView, FileTransfer, ], bootstrap: [AppComponent] }) export class AppModule {} <file_sep>import { Component, OnInit, NgZone } from '@angular/core'; import { LoadingController, Events } from '@ionic/angular' import { Moment } from 'moment' import { Platform, } from '@ionic/angular'; import { Router } from '@angular/router'; // Google Map import { GoogleMaps, GoogleMap, GoogleMapsEvent, Marker, GoogleMapsAnimation } from '@ionic-native/google-maps'; // Services import { LocationProviderService } from '../providers/location/location-provider.service' import { AuthService } from '../providers/auth/auth.service' import { AccidentService } from '../providers/accident/accident.service' // MapStyles import { mapStyle } from '../mapStyles' @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage implements OnInit { map: GoogleMap userMarker: Marker loading: any accidents = [] selectedMarker = null user = null constructor( private platform: Platform, private location: LocationProviderService, private accidentService: AccidentService, private zone: NgZone, private router: Router, private loadingCtrl: LoadingController, private events: Events, private auth: AuthService ) { } async ngOnInit() { await this.platform.ready() await this.presentLoading() await this.accidentService.fetchAccidents() await this.location.getInitialPosition() await this.loadMap() this.user = this.auth.user this.events.subscribe('user:logged-in', (user) => { this.user = user }) this.events.subscribe('user:logged-out', () => { this.user = null }) } async loadMap() { const {lat, lng} = this.location.userPosition this.map = GoogleMaps.create('map', { camera: { target: { lat: lat ? lat: 16.41666, lng: lng ? lng : 120.5999976, }, zoom: 17, tilt: 30 }, styles: mapStyle }) this.map.on(GoogleMapsEvent.MAP_CLICK).subscribe((data) => { this.zone.run(() => { this.selectedMarker = null }) }) // add a marker this.userMarker = this.map.addMarkerSync({ title: 'You are here!', position: { lat: lat ? lat: 16.41666, lng: lng ? lng : 120.5999976, }, icon: { url: require('../../assets/icon/car.png') }, }); // show the infoWindow this.userMarker.showInfoWindow() this.location.startTracking() this.events.subscribe('location:changed', (userPosition) => { this.zone.run(() => { this.userMarker.setPosition(userPosition) this.map.setCameraTarget(userPosition) }) }) this.addMarkers() if(this.loading) { this.loading.dismiss() } } addMarkers() { if(this.accidentService.accidents) { this.accidentService.accidents.map(async (location) => { if(!location.status) return false const { title, lat, lng, } = location this.map.addMarker({ title, position: { lat, lng }, icon: require('../../assets/icon/caraccident.png') }).then((marker: Marker) => { marker.on(GoogleMapsEvent.MARKER_CLICK).subscribe(() => this.zone.run(() => { const { id, date } = location this.accidents.push({id, lat, lng, status, title, date }) this.onMarkerClick({id, lat, lng, status, title, date}) })); }) this.map.addCircle({ 'center': {lat, lng}, 'radius': 100, 'strokeColor' : '#88A000', 'strokeWidth': 1, 'fillColor' : '#880000' }) }) } return false; } toggleSelected (val:any) { this.selectedMarker = val } onMarkerClick (marker: any) { this.toggleSelected(marker) } goToWarning() { this.router.navigateByUrl('/warning') } goToDetails () { if(!this.selectedMarker) return this.router.navigateByUrl(`/accidents/${this.selectedMarker.id}`) } async presentLoading () { this.loading = await this.loadingCtrl.create({ message: "Please wait. We're setting up data." }) this.loading.present() } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http' import { SERVER_URL } from '../../../environments/environment' @Injectable({ providedIn: 'root' }) export class ApiProviderService { constructor( private http: HttpClient, ) {} async performGet (url, params = {}): Promise<any> { return this.http.get(`${SERVER_URL}${url}`, params).toPromise() } async performPost (url, data, params = {}): Promise<any> { return this.http.post(`${SERVER_URL}${url}`, data, params).toPromise() } async performPut (url, params = {}) { return this.http.put(`${SERVER_URL}${url}`, params).toPromise() } } <file_sep>import { Pipe, PipeTransform } from '@angular/core'; import * as moment from 'moment' @Pipe({ name: 'momentDate' }) export class MomentDatePipe implements PipeTransform { transform(value: any, args?: any): any { let date = value ? value : new Date() console.log(value) return moment(date).format('dddd, MMMM DD,YYYY h:m A') } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { AuthService } from '../providers/auth/auth.service' import { Validators, FormBuilder, FormGroup } from '@angular/forms' import { LoadingController, AlertController } from '@ionic/angular' import { GooglePlus } from '@ionic-native/google-plus/ngx' import { Facebook } from '@ionic-native/facebook/ngx' import { ApiProviderService } from '../providers/api/api-provider.service'; import { GOOGLE_WEB_CLIENT_ID } from '../../environments/environment' @Component({ selector: 'app-login', templateUrl: './login.page.html', styleUrls: ['./login.page.scss'], }) export class LoginPage implements OnInit { form: FormGroup loading: any alert: any constructor( private router: Router, private auth: AuthService, private formBuilder: FormBuilder, private alertCtrl: AlertController, private loadingCtrl: LoadingController, private googlePlus: GooglePlus, private facebook: Facebook, ) { this.form = this.formBuilder.group({ username: ['', Validators.required], password: ['', Validators.required] }) } ngOnInit() { } async processForm() { const { username, password } = this.form.value await this.showLoader() let res = await this.auth.getToken(username, password) if(res.error) { await this.hideLoader() await this.showAlert(res.error.message) } await this.hideLoader() this.form.reset() this.router.navigateByUrl('/app/tabs/(home:home)') } async showLoader () { this.loading = await this.loadingCtrl.create({ message: 'Please wait...' }) this.loading.present() } async hideLoader () { if(this.loading) await this.loading.dismiss() } async showAlert (message) { this.alert = await this.alertCtrl.create({ message, buttons: [ 'Dismiss' ] }) this.alert.present() } async loginWithGoogle () { try { await this.showLoader() const googleUser = await this.googlePlus.login({ webClientId: GOOGLE_WEB_CLIENT_ID }) await this.auth.loginUsingSocial(googleUser.accessToken, 'google') await this.hideLoader() this.router.navigateByUrl('/app/tabs/(home:home)') } catch(err) { console.log(err) } } async loginWithFacebook () { try { await this.showLoader() const facebookUser = await this.facebook.login(['email', 'public_profile']) console.log(facebookUser) const user = await this.auth.loginUsingSocial(facebookUser.authResponse.accessToken, 'facebook') await this.hideLoader() this.router.navigateByUrl('/app/tabs/(home:home)') } catch(err) { console.log(err) } } } <file_sep>import { Injectable, NgZone } from '@angular/core'; import { Router } from '@angular/router' import { Platform } from '@ionic/angular' import { Geofence } from '@ionic-native/geofence/ngx' import { HttpClient } from '@angular/common/http' import { AccidentService } from '../accident/accident.service' import { LocationProviderService } from '../location/location-provider.service' @Injectable({ providedIn: 'root' }) export class GeofenceService { locations: any accidentProneAreas: any accidentProneAreasIds: Array<any> = [] fences = [] inBackground = false constructor( private geofence: Geofence, private http: HttpClient, private accidents: AccidentService, private location: LocationProviderService, private platform: Platform, private router: Router, private zone: NgZone, ) {} async setUpGeofence() { await this.geofence.initialize() await this.addGeoFence() this.platform.pause.subscribe(() => { this.inBackground = true console.log('Paused') }) this.platform.resume.subscribe(() => { this.inBackground = false console.log('Resumed') }) } private async addGeoFence () { if(this.locations) { this.locations.map(accident => { const { id, lat, lng, status } = accident if(status) { let fence = { id: id, latitude: parseFloat(lat), //center of geofence radius longitude: parseFloat(lng), radius: 150, transitionType: 1, notification: { id: id, title: "Accident near you!", text: "An accident near you was detected. Be careful.", openAppOnClick: true, } } this.geofence.addOrUpdate(fence).then( () => { console.log('Adding geofence done') } ) } }) if(this.accidentProneAreas) { console.log(this.accidentProneAreas) this.accidentProneAreas.map(async (area, index) => { const results = await this.location.geocode(area.place) const key = index + Math.random().toString().substr(2,7) + "" this.accidentProneAreasIds.push({key: index}) console.log(key) let fence = { id: parseInt(key), latitude: parseInt(results[0].position.lat), //center of geofence radius longitude: parseInt(results[0].position.lng), radius: 150, transitionType: 1, notification: { id: parseInt(key), title: "Accident prone area near you!", text: "There have been numerous reports of accidents near your area", openAppOnclick: true, } } this.geofence.addOrUpdate(fence).then( () => console.log('Geofence for accident prone area added'), (err) => console.log('Geofence failed to add', err) ); }) } } this.geofence.onTransitionReceived().subscribe((event) => { const notification = event[0] if(!this.inBackground) { const location = this.locations.find(location => parseInt(location.id) === parseInt(notification.id)) if(location) { this.zone.run( () => { this.router.navigateByUrl(`/accidents/${location.id}`) }) } } }) } async getLocations() { const resp = await this.accidents.fetchAccidents() const accidentProneAreas = await this.accidents.getAccidentPrones() this.locations = resp this.accidentProneAreas = accidentProneAreas } } <file_sep>import { Component, OnInit } from '@angular/core' import { Router } from '@angular/router' import { LoadingController } from '@ionic/angular' import { FormBuilder, FormGroup, Validators } from '@angular/forms' import { AccidentReportingService } from '../providers/accident-reporting/accident-reporting.service' import { LocationProviderService } from '../providers/location/location-provider.service' @Component({ selector: 'app-steptwo', templateUrl: './steptwo.page.html', styleUrls: ['./steptwo.page.scss'], }) export class SteptwoPage implements OnInit { loading: any LOCATION_TYPE_USER_LOC = 'userLocation' LOCATION_TYPE_CUSTOM = 'customLocation' form: FormGroup constructor( private router: Router, private formBuilder: FormBuilder, private locationService: LocationProviderService, private accidentReporting: AccidentReportingService, private loadingCtrl: LoadingController ) { this.form = this.formBuilder.group({ location: [this.LOCATION_TYPE_USER_LOC, Validators.required] }) } ngOnInit() { } goToNextPage () { if(this._getLocationType() === 'customLocation') { this.router.navigateByUrl('/chooselocation') return } this.router.navigateByUrl('/stepthree') } async processForm () { if(this._getLocationType() === 'userLocation') { this.showLoading() try { const position = await this.locationService.getUserPosition() await this.locationService.geocode(position) this.accidentReporting.addFields({lat: position.lat, lng: position.lng}) } catch( err ) { console.log(err) } if(this.loading) { this.loading.dismiss() } } // this.goToNextPage() } private _getLocationType () { const { location } = this.form.value return location } private async showLoading() { this.loading = await this.loadingCtrl.create({ message: "Please wait. We're fetching your location." }) this.loading.present() } } <file_sep>import { Component, OnInit } from '@angular/core'; import { Subscription } from 'rxjs/Subscription'; import { NavigationEnd, Router } from '@angular/router'; import { LoadingController, Events } from '@ionic/angular' import { ApiProviderService } from '../providers/api/api-provider.service' import { AccidentService } from '../providers/accident/accident.service' import { AuthService } from '../providers/auth/auth.service' @Component({ selector: 'app-accidents-list', templateUrl: './accidents-list.page.html', styleUrls: ['./accidents-list.page.scss'], }) export class AccidentsListPage implements OnInit { private subscription: Subscription; accidents: Array<any> = [] loading: any user: any = null constructor( private router: Router, public api: ApiProviderService, private loadingCtrl: LoadingController, private accident: AccidentService, private auth: AuthService, private events: Events ) { } async ngOnInit() { await this.onEnter(); this.user = this.auth.user this.events.subscribe('user:logged-in', (user) => { this.user = user }) this.events.subscribe('user:logged-out', () => { this.user = null }) this.subscription = this.router.events.subscribe( async (event) => { if (event instanceof NavigationEnd && event.url === '/app/tabs/(accidents-list:accidents-list)') { await this.onEnter(); } }); } public async onEnter(): Promise<void> { try { await this.presentLoading() if(this.user) { const accidents = await this.accident.fetchAccidents() this.accidents = (accidents.filter(accident => accident.user_id === this.auth.user.id)) } }catch(err) { console.log(err) } this.hideLoading() } async presentLoading() { this.loading = await this.loadingCtrl.create({ message: 'Fetching data...' }) this.loading.present() } hideLoading() { if(this.loading) { this.loading.dismiss() } } goToDetails (id) { this.router.navigateByUrl(`/accidents/${id}`) } goToLogin() { this.router.navigateByUrl('/login') } goToWarning() { this.router.navigateByUrl('/warning') } } <file_sep>export const environment = { production: true }; export const SERVER_URL = "http://localhost:8000" export const GOOGLE_WEB_CLIENT_ID = "897970861884-d7v4sjnqs02dgtrhf3agqkj9t5lfgtkm.apps.googleusercontent.com" <file_sep>import { Injectable } from '@angular/core'; import { Router, CanActivate, ActivatedRouteSnapshot } from '@angular/router' import { AuthService } from '../auth/auth.service' @Injectable({ providedIn: 'root' }) export class AuthGuardService implements CanActivate { constructor( private router: Router, private auth: AuthService ) { } async canActivate(route: ActivatedRouteSnapshot): Promise<boolean> { console.log(route) return new Promise<boolean>(async(resolve, reject) => { const user = await this.auth.getStoredUser() if(!user) { // this.router.navigate(['login']) resolve(true) } resolve(true) }) } } <file_sep>import { Component, OnInit, NgZone} from '@angular/core'; import { Router } from '@angular/router'; import { LoadingController } from '@ionic/angular' import { WebView } from '@ionic-native/ionic-webview/ngx' import { ImagePicker } from '@ionic-native/image-picker/ngx'; import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; import { ActionSheetController } from '@ionic/angular'; import { AccidentReportingService } from '../providers/accident-reporting/accident-reporting.service' @Component({ selector: 'app-stepthree', templateUrl: './stepthree.page.html', styleUrls: ['./stepthree.page.scss'], }) export class StepthreePage implements OnInit { images: Array<any> = [] dateTime loading: any constructor( private imagePicker: ImagePicker, private router: Router, private accidentReporting: AccidentReportingService, private loadingCtrl: LoadingController, private actionSheetController: ActionSheetController, private camera: Camera, private zone: NgZone, private webview: WebView ) { } ngOnInit() { } async selectImageOption() { const actionsheet = await this.actionSheetController.create({ buttons: [ { text: 'Take a Photo', icon: 'camera', handler: () => { this.takePicture() } }, { text: 'Choose from gallery', icon: 'photos', handler: () => { this.chooseImage() } }, ] }) await actionsheet.present() } async takePicture () { const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } try { let photo = await this.camera.getPicture(options) this.zone.run(() => { this.images.push(photo) }) } catch(err) { console.log(err) } } async chooseImage() { this.imagePicker.getPictures({}).then( async (results) => { await this.showLoader("Processing images.") this.zone.run(() => { this.images = [...this.images, ...results] }) this.hideLoader() }, (err) => { console.log(err) }) } goToThankYouPage() { this.router.navigateByUrl('thankyou') } async processForm () { this.accidentReporting.addFields({ images: this.images, date: this.dateTime }) await this.showLoader("Wrapping up your report.") await this.accidentReporting.submit() await this.hideLoader() this.goToThankYouPage() } async showLoader(message = '') { this.loading = await this.loadingCtrl.create({ message }) this.loading.present() } normalizeImage(url) { return this.webview.convertFileSrc(url) } async hideLoader() { if(this.loading) { await this.loading.dismiss() } } async removeImage (index) { this.images.splice(index, 1) } } <file_sep>import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AccidentsListPage } from './accidents-list.page'; describe('AccidentsListPage', () => { let component: AccidentsListPage; let fixture: ComponentFixture<AccidentsListPage>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ AccidentsListPage ], schemas: [CUSTOM_ELEMENTS_SCHEMA], }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(AccidentsListPage); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>var jsf = require('json-schema-faker'); var mockDataSchema = require('./schema'); var fs = require('fs'); var faker = require('faker') jsf.option({ useDefaultValue: true }) jsf.extend('faker', () => { return faker }) jsf.format('soon', () => faker.date.past()) var json = JSON.stringify(jsf.generate(mockDataSchema)); fs.writeFile("./db.json", json, function (err) { if (err) { return console.log(err); } else { console.log("Mock data generated."); } });
f7548aed4e80b4f5764158754d3daa8cbc9e0894
[ "JavaScript", "TypeScript" ]
27
TypeScript
johnveeuminga/safetravel
55c9b3658d4af1e8213611fecb358c101329076a
c6e4f915364c9bd183b350598682b9fdd800fdff
refs/heads/master
<repo_name>nokazn/nest-auth-example<file_sep>/src/auth/auth.service.ts import { Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { User } from '../users/interfaces/users.interfaces'; import { UsersService } from 'src/users/users.service'; @Injectable() export class AuthService { constructor( private usersService: UsersService, private jwtService: JwtService, ) {} async validateUser( username: string, password: string, ): Promise<Omit<User, 'password'> | null> { const user = await this.usersService.findOne(username); // @WARN 普通はハッシュ化したものを比較する if (user != null && user.password === password) { // eslint-disable-next-line @typescript-eslint/no-unused-vars const { password: _, ...result } = user; return result; } return null; } async login(user: { username: string; userId: number }) { // JWT の標準に倣って sub という名前にしている const payload = { username: user.username, sub: user.userId, }; const access_token = this.jwtService.sign(payload); return { access_token }; } } <file_sep>/src/auth/auth.module.ts import { Module } from '@nestjs/common'; import { PassportModule } from '@nestjs/passport'; import { LocalStrategy } from './local.strategy'; import { JwtModule } from '@nestjs/jwt'; import * as dotenv from 'dotenv'; import { UsersModule } from '../users/users.module'; import { AuthService } from './auth.service'; import { AuthController } from './auth.controller'; import { JwtStrategy } from './jwt.strategy'; dotenv.config(); const { SECRET } = process.env; if (SECRET == null) { console.error('環境変数が設定されていません。', process.env); throw new Error(); } @Module({ imports: [ UsersModule, PassportModule, JwtModule.register({ secret: SECRET, signOptions: { expiresIn: '60s', }, }), ], providers: [AuthService, LocalStrategy, JwtStrategy], controllers: [AuthController], }) export class AuthModule {} <file_sep>/src/app.controller.ts import { Controller, Get, Request, UseGuards } from '@nestjs/common'; import { AppService } from './app.service'; import { JwtAuthGuard } from './auth/guard/jwtAuth.guard'; import { TODO } from './types'; @Controller() export class AppController { constructor(private readonly appService: AppService) {} @UseGuards(JwtAuthGuard) @Get('profile') getProfile(@Request() req: TODO) { return req.user; } }
ba1c17971f2e982d94819d7cb2cb35d00f8d4d56
[ "TypeScript" ]
3
TypeScript
nokazn/nest-auth-example
7d67d4cea6dbff8e3d6db94deb0f51d052bfcb80
352dff5df2370fd8b904da22429b1c2c24420893
refs/heads/master
<file_sep>using System; using Tranform.Try; namespace console_app { public static class Program { public static void Main() { Console.WriteLine("A simple console application that uses a NuGet package."); Calculator calculator = new Calculator(); string result = calculator.Add(3, 4); Console.WriteLine("3 + 4{0}", result); } } }
d9629df569596a210b242a27be92010eed3a240d
[ "C#" ]
1
C#
sdepouw/nuget-ci
ecc68d72a2713009a42b743e8eefee6a7ce9dc86
70ea9d650634a940916533ee4c62f2b38292115e
refs/heads/main
<file_sep>const firebaseConfig = { apiKey: "<KEY>", authDomain: "fir-first-project-13-3-21.firebaseapp.com", projectId: "fir-first-project-13-3-21", storageBucket: "fir-first-project-13-3-21.appspot.com", messagingSenderId: "281061790702", appId: "1:281061790702:web:7c2933a66d64333e0d34ff" }; export default firebaseConfig;
e5892b0a6278063ccfb153b8efce716e277752df
[ "JavaScript" ]
1
JavaScript
git11hub/fire-auth
62bb461bd072b859ad5631e3140ac071ebea5166
62584d2324575fa600e184be505c2d24de28e36f
refs/heads/master
<file_sep>import React, { Component } from 'react'; import httpInstance from '../../axios'; import List from '../../component/List/List'; import Spinner from '../../component/Spinner/Spinner'; import Input from '../../component/Input/Input'; import Filter from '../../component/Filter/Filter'; class Home extends Component { state = { data: [], filterUser: [], error: false, selectedFilter: "", searchVal: '', SelectVal: '' } componentDidMount() { httpInstance.get("/character") .then((response) => { console.log(response.data) this.setState({ data: response.data, filterUser: response.data.results }) }).catch(error => { this.setState({ error: true }) }); } inputChangeHandler = (event) => { this.Searchdata(event.target.value); } filterHandler = (event) => { this.Searchdata(event.target.innerText); this.setState({ selectedFilter: event.target.innerText, SelectVal: 'Ascending' }); } handleChange = (event) => { const update = { ...this.state.filterUser } let reverse; if (event.target.value !== this.state.SelectVal) { reverse = Object.assign([], update).reverse(); } this.setState({ SelectVal: event.target.value }); this.setState({ filterUser: reverse }); } clearFilter = () => { this.setState({ selectedFilter: '' }); this.setState({ filterUser: this.state.data.results, SelectVal: "Ascending" }); } Searchdata = (val) => { let listData = this.state.data.results if (listData) { let finalData = listData.filter(result => { if (val === "Human" || val === "Alien") { return result.species.toUpperCase().indexOf(val.toUpperCase()) > -1; } else if (val === "Male" || val === "Female") { return result.gender.toUpperCase() === val.toUpperCase(); } else { return result.name.toUpperCase().indexOf(val.toUpperCase()) > -1; } }) const updateIng = { ...this.state.data, ...this.state.filterUser } if (finalData) { updateIng.filterUser = finalData; this.setState({ filterUser: updateIng.filterUser, SelectVal: "Ascending" }); } } } render() { let list = this.props.error ? <p>Something went wrong</p> : <Spinner /> if (this.state.data.results) { list = ( <> <Filter filter={(event) => this.filterHandler(event)} selectedFilter={this.state.selectedFilter} name="sort" value={this.state.SelectVal} handleChange={this.handleChange} clearFilter={() => this.clearFilter()} /> <Input changed={(event) => this.inputChangeHandler(event)} /> <div style={{ clear: "both" }}></div> <List data={this.state.filterUser}></List> </> ) } return ( <> {list} </> ) } } export default Home;<file_sep>import React from 'react'; import Home from './container/Home/Home'; import Navbar from './component/NavBar/NavBar'; function App() { return ( <div> <Navbar> <NAME> Morty </Navbar> <Home /> </div> ); } export default App; <file_sep>import axios from 'axios'; const httpInstance=axios.create({ baseURL:'https://rickandmortyapi.com/api/' }) export default httpInstance;<file_sep>import React from 'react'; import classes from './NavBar.css'; const navbar = (props) => ( <header className={classes.Toolbar}> <nav className={classes.nav}> <p><NAME> </p> </nav> </header> ) export default navbar;<file_sep>import React from 'react'; import classes from './Input.css' const input = (props) => { // console.log(props); return ( <div className={classes.Input}> <label className={classes.Label}>Search User by name:</label> <input className={classes.InputElement} value={props.value} onChange={props.changed} /> </div> ) } export default input
d531e9066dd6ecadcb016fbfcb9643f658450b53
[ "JavaScript" ]
5
JavaScript
angular2015/rick-and-morty-app
3f87214620d145b4469debfb214e90ad27bc9825
c0e9f250f2cdc84eab4a86c3ebfe7f2cb14f9aeb
refs/heads/master
<file_sep>module.exports = { presets: [ '@vue/cli-plugin-babel/preset' ], // common + es6 共存 sourceType: 'unambiguous' } <file_sep>import utils from '@/utils' export default { namespaced: true, mutations: { /** * @description 显示版本信息 * @param {Object} state state */ versionShow () { utils.log.capsule(`${process.env.VUE_APP_TITLE}`, `v${process.env.VUE_APP_VERSION}`) } } } <file_sep>import request from '@/plugin/axios/request' export function SYS_ADMIN_LOGIN (data) { return request({ url: '/auth/login', method: 'post', data }) } export function SYS_ADMIN_CAPTCHA () { return request({ url: '/auth/captcha', method: 'post' }) } <file_sep># chic-admin chic-admin 一个基于 Vue.js 的管理后台快速开发脚手架 <file_sep>import { uniqueId } from 'lodash' /** * @description 给菜单数据补充上 path 字段 * @description https://github.com/projects/admin/issues/209 * @param {Array} menu 原始的菜单数据 */ function supplementPath (menu) { return menu.map(e => ({ ...e, path: e.path || uniqueId('menu-empty-'), ...e.children ? { children: supplementPath(e.children) } : {} })) } // 菜单 侧边栏 export const menuAside = supplementPath([ ]) // 菜单 顶栏 export const menuHeader = supplementPath([ { path: '/index', title: '首页', icon: 'home' } ]) <file_sep>import Vue from 'vue' import Container from './container' import ContainerFrame from './container-frame' // 注意 有些组件使用异步加载会有影响 Vue.component('container', Container) Vue.component('container-frame', ContainerFrame) Vue.component('count-up', () => import('./count-up')) Vue.component('icon', () => import('./icon')) Vue.component('icon-svg', () => import('./icon-svg/index.vue')) Vue.component('icon-select', () => import('./icon-select/index.vue')) Vue.component('icon-svg-select', () => import('./icon-svg-select/index.vue')) Vue.component('scrollbar', () => import('./scrollbar'))
906e81997945eb6550c2e0029a1dd9dfc59538cd
[ "JavaScript", "Markdown" ]
6
JavaScript
Septillions/chic-admin
9ead6c51a6f1aa03033579246961e06d4fa019e9
40054b05550bf5cb0109f0324160420cc308ba1a
refs/heads/master
<repo_name>kevwan/ChatterBot<file_sep>/service.py import grpc import signal from concurrent import futures import talkaholic_pb2, talkaholic_pb2_grpc from chatterbot import ChatBot chatbot = ChatBot( 'bot@liao', trainer='chatterbot.trainers.ChatterBotCorpusTrainer', storage_adapter='chatterbot.adapters.storage.MongoDatabaseAdapter', database="chatterbot-100k" ) class TalkaholicServicer(talkaholic_pb2_grpc.TalkaholicServicer): def talk(self, request, context): resp = chatbot.get_response(request.question) return talkaholic_pb2.TalkaholicResponse(answer=resp.text) server = grpc.server(futures.ThreadPoolExecutor(max_workers=8)) talkaholic_pb2_grpc.add_TalkaholicServicer_to_server(TalkaholicServicer(), server) server.add_insecure_port(":9400") server.start() try: signal.pause() except KeyboardInterrupt: pass <file_sep>/Dockerfile FROM python MAINTAINER <EMAIL> RUN pip install grpcio RUN pip install jsondatabase RUN pip install fuzzywuzzy RUN pip install python-Levenshtein RUN pip install textblob RUN pip install requests RUN mkdir /app ADD . /app EXPOSE 9400 CMD ["python", "/app/service.py"] <file_sep>/prepare_corpus.py import argparse parser = argparse.ArgumentParser() parser.add_argument("-i", nargs="?") parser.add_argument("-o", nargs="?") args = parser.parse_args() with open(args.i, "r") as ifile, open(args.o, "w") as ofile: print("{\n\t\"conversations\": [", file=ofile) index = 0 for line in ifile: index += 1 line = line.strip().replace('\\', '\\\\').replace('"', '\\"') if index % 2 == 1: if index != 1: ofile.write(",\n") ofile.write("\t\t[\n\t\t\t\"{}\",\n".format(line)) else: ofile.write("\t\t\t\"{}\"\n\t\t]".format(line)) print("\n\t]\n}", file=ofile) <file_sep>/chatterbot/adapters/storage/__init__.py from .storage_adapter import StorageAdapter from .jsonfile import JsonFileStorageAdapter from .mongodb import MongoDatabaseAdapter <file_sep>/bot.py from chatterbot import ChatBot chatbot = ChatBot( 'bot@liao', trainer='chatterbot.trainers.ChatterBotCorpusTrainer', storage_adapter='chatterbot.adapters.storage.MongoDatabaseAdapter', database="chatterbot" ) # Train based on the english corpus chatbot.train("chatterbot.corpus.chinese.quarter") # Get a response to an input statement while True: content = input("> ") if content == "exit": break resp = chatbot.get_response(content) print(resp) <file_sep>/train.py from chatterbot import ChatBot chatbot = ChatBot( 'bot@liao', trainer='chatterbot.trainers.ChatterBotCorpusTrainer', storage_adapter='chatterbot.adapters.storage.MongoDatabaseAdapter', database="chatterbot-100k" ) # Train based on the english corpus chatbot.train("chatterbot.corpus.chinese.100k") <file_sep>/talkaholic_pb2_grpc.py import grpc from grpc.framework.common import cardinality from grpc.framework.interfaces.face import utilities as face_utilities import talkaholic_pb2 as talkaholic__pb2 import talkaholic_pb2 as talkaholic__pb2 class TalkaholicStub(object): def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.talk = channel.unary_unary( '/Talkaholic/talk', request_serializer=talkaholic__pb2.TalkaholicRequest.SerializeToString, response_deserializer=talkaholic__pb2.TalkaholicResponse.FromString, ) class TalkaholicServicer(object): def talk(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_TalkaholicServicer_to_server(servicer, server): rpc_method_handlers = { 'talk': grpc.unary_unary_rpc_method_handler( servicer.talk, request_deserializer=talkaholic__pb2.TalkaholicRequest.FromString, response_serializer=talkaholic__pb2.TalkaholicResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'Talkaholic', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
1891ad85de8cb7243e51b51947380619f9b0c5dd
[ "Python", "Dockerfile" ]
7
Python
kevwan/ChatterBot
075707165a83dddfd7d283f3073131a2d81c1d46
20d2a3558aef33650e2022ed0111ced501cb362a
refs/heads/master
<repo_name>hassanawdah/java-script-example2<file_sep>/script.js 'use strict'; const modal = document.querySelector('.modal'); const overlay = document.querySelector('.overlay'); const btnClosedModal = document.querySelector('.close-modal'); const btnOpenModal = document.querySelectorAll('.show-modal'); console.log(btnOpenModal); function openModal() { console.log('Button Clicked '); modal.classList.remove('hidden'); overlay.classList.remove('hidden'); } for (let i = 0; i < btnOpenModal.length; i++) { btnOpenModal[i].addEventListener('click', openModal) } function closedModal() { modal.classList.add('hidden'); overlay.classList.add('hidden'); } btnClosedModal.addEventListener('click', closedModal); overlay.addEventListener('click', closedModal); document.addEventListener('keydown', function (event) { console.log('A Key Pressed ' + event.key); if (event.key === 'Escape' && !modal.classList.contains('hidden')) { closedModal(); } })
6b14d958aa97d376765bfdebf51884292cd60598
[ "JavaScript" ]
1
JavaScript
hassanawdah/java-script-example2
597dc4479f11e60d7b04dd27f61668e0ff622e85
d0404666ec3540aced72e6cdf82c0b0df1028b88
refs/heads/master
<repo_name>fawnatkins/fizzbuzz<file_sep>/name_address.rb def my_name_and_address(fname,address,phone) puts "name: " + fname puts "address: #{address}" puts "phone: " + phone.to_s end my_name_and_address("Fawn","100 Hamon", 3043345676) my_name_and_address("MArv","123 Elm", "3045567890") my_name_and_address("Jack","1 River", "3045553938") my_name_and_address("Fawn","100 Hamon","3045458214") <file_sep>/loop_to_100.rb 1.upto(100) do |x| if x % 3 == 0 && x % 5 == 0 puts "mined minds" elsif x % 3 == 0 puts "mined" elsif x % 5 == 0 puts "minds" elsif x % 7 == 0 puts "seven" else puts x end end<file_sep>/hello_world.rb "hello world" puts "1" puts "2" puts "3" puts "4" puts "5" puts "6" puts "7" puts "8" puts "9" puts "10" end
e2a7b1782acb074e3af2af761a9eb4b41ae4f1cc
[ "Ruby" ]
3
Ruby
fawnatkins/fizzbuzz
fabca0f1da082cd8208a2b719fdd9e6668ab85cc
94340c6a3b0424ee89d3db9a70d8f16daedad84b
refs/heads/master
<file_sep>import * as actionTypes from './actionTypes' import axios from 'axios' import { fromJS } from 'immutable' const changList = (data) => { return { type: actionTypes.CHANGE_LIST, totalPage: Math.ceil(data.data.length / 7), data: fromJS(data) } } export const focus = () => { return { type: actionTypes.SEARCH_FOCUS } } export const blur = () => { return { type: actionTypes.SEARCH_BLUR } } export const getList = () => { return (dispatch) => { axios.get('/api/listdata.json').then((res) => { dispatch(changList(res.data)) }) } } export const mouseEnter = () => { return { type: actionTypes.MOUSE_ENTER } } export const mouseLeave = () => { return { type: actionTypes.MOUSE_LEAVE } } export const togglePage = (page) => { return { type: actionTypes.TOGGLE_PAGE, page } }<file_sep>import { combineReducers } from 'redux-immutable' import { HeaderReducer } from '../components/header/store' import { ListReducer } from '../components/home/store' export default combineReducers({ header: HeaderReducer, home: ListReducer })<file_sep>import React from 'react' import { RecommendItem,RecommendApp,RecommendCode,RecommendLetter } from '../style' import member from '../../../images/member.png' import copyright from '../../../images/copyright.png' import university from '../../../images/university.png' import serial from '../../../images/serial.png' class Recommend extends React.Component{ render(){ return ( <> <RecommendItem imgUrl={member}></RecommendItem> <RecommendItem imgUrl={serial}></RecommendItem> <RecommendItem imgUrl={copyright}></RecommendItem> <RecommendItem imgUrl={university}></RecommendItem> <RecommendApp> <RecommendCode></RecommendCode> <RecommendLetter> <p>下载简书手机App ></p> <p style={{fontSize:"12px",color:'#aaa',marginTop:'8px'}}>随时随地发现和创作内容</p> </RecommendLetter> </RecommendApp> </> ) } } export default Recommend<file_sep>import ListReducer from './reducer' export { ListReducer }<file_sep>import * as actionTypes from './actionTypes' import { fromJS } from 'immutable' const defalutState = fromJS({ focused: false, list: [], mouseIn: false, page: 1, totalPage: 1 }) export default (state = defalutState,actions) => { switch(actions.type){ case actionTypes.SEARCH_FOCUS : return state.set('focused',true) case actionTypes.SEARCH_BLUR : return state.set('focused',false) case actionTypes.CHANGE_LIST : return state.set('list',actions.data).set('totalPage',actions.totalPage) case actionTypes.MOUSE_ENTER : return state.set('mouseIn',true) case actionTypes.MOUSE_LEAVE : return state.set('mouseIn',false) case actionTypes.TOGGLE_PAGE : return state.set('page',actions.page) default: return state } }<file_sep>import {createGlobalStyle} from 'styled-components' export default createGlobalStyle` @font-face {font-family: "iconfont"; src: url('iconfont.eot?t=1555929414076'); /* IE9 */ src: url('iconfont.eot?t=1555929414076#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAPMAAsAAAAAB9gAAAN9AAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCDHAqDFIJ5ATYCJAMQCwoABCAFhG0HSBvrBsgeB875LI6kmJiQy+8IqjWyZ28PnggVBsoDeQKhYkxiRBwLhxZ0hGIj/n/brA+0I9BZ1YyqIIE6fTQroieTk6uftAECgsFfHE6b1nk437Jcxpw053kYYLw1sDUWBlwgCXrD2AUtcTaBVpNCUJfzSmrATWY2CsQzk8KDW0YlNySGRqgqemaIl/SaNCNdBPAi+H78h6jcQFIWYLa88iBXgoxfHq/jmPHn46HFQ2BPZwDrR4F1IBOPKk13MJF3HaNVLa9zCDQaiamKQl7H/f+POEcRNdZfHqGQiArM+Hawj3wFvzwcKsGvEFaVOA7GSfBBejSo8Rz4ACZu3GhJFjMGN7ee3MARdSei70you33bxs+suXkTP7721q1ys+rvVNfO52a9XmIvN9y5U19ykps3O7N1hhrWwjU2LRjELhtu4A9ws0BrsEfZmT+oCbfrJwSvOKrduRbGr+NmfaWoUTOD5F4L2Jmvekhrd/<KEY>') format('woff2'), url('iconfont.woff?t=1555929414076') format('woff'), url('iconfont.ttf?t=1555929414076') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */ url('iconfont.svg?t=1555929414076#iconfont') format('svg'); /* iOS 4.1- */ } .iconfont { font-family: "iconfont" !important; font-size: 20px; font-style: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }` <file_sep>import HeaderReducer from './reducer' import * as Actions from './actions' export { HeaderReducer, Actions}<file_sep>import * as ActionTypes from './actionTypes' import axios from 'axios' const getHomeAction = (data) => { return { type: ActionTypes.CHANGE_HOME_LIST, data } } const getMoreList = (data) => { return { type: ActionTypes.MORE_LIST, data } } export const getHomeList = () => { return (dispatch) => { axios.get('/api/homelist.json').then(res => { dispatch(getHomeAction(res.data.article)) }) } } export const loadMore = () => { return (dispatch) => { axios.get('/api/morelist.json').then(res => { dispatch(getMoreList(res.data.article)) }) } } export const toTop = (res) => { return { type: ActionTypes.TO_TOP, res } } <file_sep>import React from 'react' import { connect } from 'react-redux'; import { CSSTransition } from 'react-transition-group' import {Actions} from './store' import { HeaderWapper,Login,Nav,NavItem,NavSearch, Sign,Write,SearchWrap,SearchInput,SearchInfo, SearchItem,SearchInfoTitle,SearchTitleLeft, SearchTitleRight,HeaderIn } from './style' function Header(props){ return( <HeaderWapper> <HeaderIn> <Login/> <Nav> <NavItem className='left active'>首页</NavItem> <NavItem className='left'>下载App</NavItem> <NavItem className='right'>登录</NavItem> <NavItem className='right beta'></NavItem> <NavItem className='right'> <span className="iconfont">&#xe636;</span> </NavItem> <SearchWrap> <CSSTransition in={props.focused} timeout={300} classNames='slide'> <SearchInput className={props.focused?'focused':''} onFocus={() => props.handleFoucus(props.list)} onBlur={props.handleBlur} ></SearchInput> </CSSTransition> <i className="iconfont">&#xe60d;</i> { getShow(props) } </SearchWrap> </Nav> <NavSearch> <Sign>注册</Sign> <Write>写文章</Write> </NavSearch> </HeaderIn> </HeaderWapper> ) } const getShow = (props) => { const { focused,list,handleMouseEnter,handleMouseLeave,mouseIn,handleToggle,page,totalPage } = props const newArr = list.toJS().data const pageList = [] if(!(focused||mouseIn)) return if(newArr){ for(let i = (page - 1)*7;i < page*7;i++){ pageList.push( <SearchItem key={i}>{newArr[i]}</SearchItem> ) } return ( <SearchInfo onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave}> <SearchInfoTitle> <SearchTitleLeft>热门搜索</SearchTitleLeft> <SearchTitleRight onClick={() => handleToggle(page,totalPage)}>换一批</SearchTitleRight> </SearchInfoTitle> {pageList} </SearchInfo> ) } } const mapStateToProps = (state) => { return { focused: state.get('header').get('focused'), list: state.get('header').get('list'), mouseIn: state.get('header').get('mouseIn'), page: state.get('header').get('page'), totalPage: state.get('header').get('totalPage'), } } const mapDispatchToProps = (dispatch) => { return { handleFoucus: (list) => { (list.size === 0) && dispatch(Actions.getList()) dispatch(Actions.focus()) }, handleBlur: () => { dispatch(Actions.blur()) }, handleMouseEnter: () => { dispatch(Actions.mouseEnter()) }, handleMouseLeave: () => { dispatch(Actions.mouseLeave()) }, handleToggle: (page,totalPage) => { if(page < totalPage){ dispatch(Actions.togglePage(page + 1)) }else { dispatch(Actions.togglePage(1)) } } } } export default connect(mapStateToProps,mapDispatchToProps)(Header)<file_sep>import { fromJS } from 'immutable' import * as ActionTypes from './actionTypes' const defalutValue = fromJS({ list: [], hidden: true }) export default (state = defalutValue,actions) => { switch(actions.type){ case ActionTypes.CHANGE_HOME_LIST: return state.set('list',fromJS(actions.data)) case ActionTypes.MORE_LIST: return state.set('list',state.get('list').concat(fromJS(actions.data))) case ActionTypes.TO_TOP: return state.set('hidden',fromJS(actions.res)) default: return state } }<file_sep>import React from 'react' import { connect } from 'react-redux' import {HomeBody,HomeLeft,HomeRight,BackTop} from './style' import List from './components/List' import Recommend from './components/Recommend' import * as Actions from './store/actions' class Home extends React.Component{ constructor(props){ super(props) this.backTop = this.backTop.bind(this) } backTop(){ window.scrollTo(0,0) } componentDidMount(){ this.props.homeList() document.addEventListener('scroll',this.props.handleScroll) } render(){ const {hidden} = this.props return ( <HomeBody> <HomeLeft> <img className='banner' src="//upload.jianshu.io/admin_banners/web_images/4592/22f5cfa984d47eaf3def6a48510cc87c157bf293.png?imageMogr2/auto-orient/strip|imageView2/1/w/1250/h/540" alt="540"></img> <List></List> </HomeLeft> <HomeRight> <Recommend></Recommend> </HomeRight> <BackTop onClick={this.backTop} className={hidden?'hidden':''}> <span className='iconfont'>&#xe62c;</span> </BackTop> </HomeBody> ) } } const mapState = (state) => { return { hidden: state.get('home').get('hidden') } } const mapDispatch = (dispatch) => { return { homeList: () => { dispatch(Actions.getHomeList()) }, handleScroll: () => { if(document.documentElement.scrollTop > 200 ){ dispatch(Actions.toTop(false)) }else{ dispatch(Actions.toTop(true)) } } } } export default connect(mapState,mapDispatch)(Home)<file_sep>import React from 'react' import { connect } from 'react-redux' import { ListItem,ListItemLeft,ListItemRight,LoadMore } from '../style' import * as Actions from '../store/actions' function List(props){ const { list,loadMore } = props return( <div>{ list.map((item,index) => { return ( <ListItem key={index}> <ListItemLeft> <a className='title' href='/'>{ item.get('title') }</a> <p className='content'>{ item.get('content') }</p> </ListItemLeft> <ListItemRight> <img className='pic' src= {item.get('imgUrl')} alt=""/> </ListItemRight> </ListItem> ) }) } <LoadMore onClick={ loadMore }>阅读更多</LoadMore> </div> ) } const mapState = (state) => { return { list: state.getIn(['home','list']) } } const mapDispatch = (dispatch) => { return { loadMore: () => { dispatch(Actions.loadMore()) } } } export default connect(mapState,mapDispatch)(List)<file_sep>import styled from 'styled-components' import code from '../../images/qrcode.png' export const HomeBody = styled.div` width: 960px; margin: 30px auto; padding-left: 20px; overflow: hidden; position: relative; ` export const HomeLeft = styled.div` width: 625px; float: left; .banner { width: 625px; } ` export const HomeRight = styled.div` width: 290px; padding: 0 5px; float: right; ` export const ListItem = styled.div` margin-top: 30px; width: 100%; border-bottom: 1px solid #ccc; position: relative; padding-bottom: 20px; ` export const ListItemLeft = styled.div` width: 460px; display: inline-block; min-height: 100px; .title{ font-weight: bold; font-size: 18px; line-height: 1.5; } .content{ font-size: 13px; line-height: 24px; color: #999; } ` export const ListItemRight = styled.a.attrs({ href: '/' })` .pic { position: absolute; right: 0; width: 150px; } ` export const RecommendItem = styled.div` cursor: pointer; width: 100%; height: 50px; background: url(${props => props.imgUrl}); background-size: contain; margin-bottom: 5px; ` export const RecommendApp = styled.div` width: 100%; box-sizing: border-box; border-radius: 5px; border: 1px solid #ccc; height: 80px; margin-top: 10px; padding: 10px 20px; ` export const RecommendCode = styled.div` width: 60px; height: 60px; display: inline-block; background: url(${code}); background-size: contain; vertical-align: middle; ` export const RecommendLetter = styled.div` display: inline-block; margin-left: 10px; vertical-align: middle; ` export const LoadMore = styled.div` width: 100%; background: #888; color: #fff; height: 40px; line-height: 40px; border-radius: 20px; text-align: center; margin-top: 30px; cursor: pointer; ` export const BackTop = styled.div` width: 50px; height: 50px; border: 1px solid #ccc; position: fixed; bottom: 70px; right: 50px; text-align: center; line-height: 50px; cursor: pointer; &.hidden{ display:none; } `
85957e23db0a13049fa66fbf16e5605078d829a7
[ "JavaScript" ]
13
JavaScript
ruanyangfan/jianshu
94b63fdc4675858f074c0750feedfb2b17f3008c
b70e829a82f90cf22de47da699a600dc54f3a6ac
refs/heads/master
<file_sep><?php namespace JS\DatatablesBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class JSDatatablesBundle extends Bundle { } <file_sep><?php namespace JS\DatatablesBundle\Service; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; class JSDataTablesManager implements ContainerAwareInterface { /** * @var \Symfony\Component\DependencyInjection\ContainerInterface */ protected $container; public function getDt($name, Request $request) { $dataTablesConfig = $this->container->getParameter('js.datatables'); if (array_key_exists($name, $dataTablesConfig)) { $dtConfig = $this->getDtConfig($name); if (isset($dtConfig['is_service'])) { return $this->container->get($dtConfig['service_name']); } else { if (isset($dtConfig['class_dt'])) { $instance = new $dtConfig['class_dt']; return $this->injectDependencies($instance, $this->getDtConfig($name), $request); } else { return $this->injectDependencies(new JSDataTables(), $this->getDtConfig($name), $request); } } } else { throw new \InvalidArgumentException(sprintf('Invalid DataTables %s', $name)); } } public function injectDependencies(JSDataTables $dataTable, $dtConfig, Request $request) { return $dataTable->setDtArrayConfig($dtConfig) ->setEntityManager($this->container->get('doctrine.orm.entity_manager')) ->setListClause($this->container->get('js.datatables.list_clause')) ->setParams($request->query->all()) ->setValidator($this->container->get('validator')); } public function getDtConfig($name) { return $this->container->getParameter('js.datatables')[$name]['dt_config']; } public function setContainer(ContainerInterface $container = null) { $this->container = $container; } }
ebfcd3248e5a282f330bf848223b965d1206bc6f
[ "PHP" ]
2
PHP
markovmihail83/jsdatatables-symfony
f84c2c87a1f4a451a1265971c913503cdb66c504
f70024845a6a347163f301d6ed4db44e1e583841
refs/heads/master
<file_sep>// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. 'use strict'; // Standard Google Universal Analytics code (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); // Note: https protocol here ga('create', 'UA-129010212-1', 'auto'); // Enter your GA identifier ga('set', 'checkProtocolTask', function(){}); // Removes failing protocol check. @see: http://stackoverflow.com/a/22152353/1958200 ga('require', 'displayfeatures'); chrome.runtime.onInstalled.addListener(() => { chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { if (changeInfo.status === 'complete' && tab.url.match(/github.com/)) { chrome.pageAction.show(tabId); } else { chrome.pageAction.hide(tabId); } }); }); const firebaseConfig = { apiKey: `<KEY>`, authDomain: `992016867099.firebaseapp.com`, databaseURL: `https://level-maintenance-plugin.firebaseio.com`, storageBucket: `level-maintenance-plugin.appspot.com` } // firebase init firebase.initializeApp(firebaseConfig) function getMaintenanceLevel(fullName) { const [owner, name] = fullName.split(`/`) return new Promise(resolve => { firebase .database() .ref(`/projects`) .once(`value`) .then(res => { const projectOwner = res.val()[owner] projectOwner ? resolve(projectOwner[name]) : resolve(null) }) }) } function getRepositoryInfo(repository) { return window.fetch(`https://api.github.com/repos/${repository}`) .then(result => result.json()) } function handleUpdated(tabId, changeInfo, tabInfo) { if (changeInfo.status === "complete" && tabInfo.url.match(`github\.com\/[^\n\r\/]+\/[^\n\r\/]+`)) { const url = tabInfo.url.split('/'); const repository = `${url[3]}/${url[4]}` getRepositoryInfo(repository).then(({ full_name }) => { getMaintenanceLevel(full_name).then(result => { chrome.tabs.sendMessage(tabId, { maintenanceInfo: result }) }) }) } } function handleMessage({ event }) { if (event.type === 'click') { ga('send', 'event', { event }) } return false } chrome.tabs.onUpdated.addListener(handleUpdated) chrome.runtime.onMessage.addListener(handleMessage)
3d0a31f256594a5e6cea4dada11aa0c149130d75
[ "JavaScript" ]
1
JavaScript
pedroscaff/isMaintained-extension
17ea0607ce02e86597546a12e74cafc3e8eb4c36
77a70756a96fe42c3e2a9828bea3b4eb2369c784
refs/heads/master
<repo_name>kevinlozada1102/php_api_jsonplaceholder<file_sep>/app/Controller/PostController.php <?php namespace App\Controller; use App\Service\PostService; class PostController implements BaseController { private $postService; public function __construct(){ $this->postService = new PostService(); } public function index() { $posts = $this->postService->listarTodos('posts'); $this->view('post_listado',$posts); } public function createupdate() { // TODO: Implement create() method. } public function delete() { if(isset($_REQUEST['id'])){ $status = $this->postService->eliminarPorId('posts', $_REQUEST['id']); } if ($status == 200){ $posts = $this->postService->listarTodos('posts'); $mensaje = "ELIMINACIÓN EXITOSA. Importante, el recurso no se eliminará realmente en el servidor, pero se falsificará como si lo fuera."; $posts['mensaje'] = $mensaje; $this->view('post_listado',$posts); } else { } } public function obtener() { if(isset($_REQUEST['id'])){ $post = $this->postService->obtenerPorId('posts', $_REQUEST['id']); $comments = $this->postService->obtenerPorIdAdicional('posts', $_REQUEST['id'],'comments'); } $post['comentarios'] = $comments; $this->view('post_info',$post); } public function formulario() { if(isset($_REQUEST['id'])){ $post = $this->postService->obtenerPorId('posts', $_REQUEST['id']); $this->view('post_form',$post); } else { $this->view('post_form'); } } public function view($vista,$datos = null){ $data = $datos; require_once __DIR__ . "/../../resources/views/" . $vista . ".php"; } }<file_sep>/README.md # php_api_jsonplaceholder Proyecto base PHP API JSONplaceholder Ejecutar el script de la base de datos MySQL. Ejecutar en la carpeta del proyecto composer install. <file_sep>/public/index.php <?php require '../vendor/autoload.php'; require '../config/database.php'; $controller = "\App\Controller\PostController"; if(!isset($_REQUEST['c'])) { $controller = new $controller; $controller->index(); } else { $controller = strtolower($_REQUEST['c']); $accion = isset($_REQUEST['a']) ? $_REQUEST['a'] : 'index'; // Instanciamos el controlador $controller = '\App\Controller\\'. ucwords($controller) . 'Controller'; $controller = new $controller; call_user_func( array( $controller, $accion ) ); }<file_sep>/resources/views/post_listado.php <?php include("components/header.php")?> <div class="container"> <div class="row"> <h3>Listado de Post - API</h3> <!--<a class='btn waves-effect waves-light red darken-1' type='submit' name='action' href='?c=Post&a=formulario'>Crear Post <i class="material-icons right">create_new_folder</i> </a>--> <br> <?php if (isset($data["mensaje"])) { echo " <script> var texto ='<span>{$data["mensaje"]}</span>' M.toast({html: texto, classes: 'rounded'}); </script>"; } foreach ($data as $post) { if (isset($post["id"])){ print_r( " <div class=\"col m12\"> <div class=\"card horizontal\"> <div class=\"card-stacked\"> <div class=\"card-content\"> <a class=\"card-title activator grey-text text-darken-4\" href=\"?c=Post&a=obtener&id={$post["id"]}\">{$post["id"]}. {$post["title"]}</a> </div> <div class=\"card-action\"> <a class='btn waves-effect waves-light red darken-1' type='submit' name='action' href='?c=Post&a=delete&id={$post["id"]}'>Eliminar <i class=\"material-icons right\">delete</i> </a> </div> </div> </div> </div>" ); } } ?> </div> </div> <?php include("components/footer.php")?> <file_sep>/app/Controller/BaseController.php <?php namespace App\Controller; interface BaseController { public function index(); public function obtener(); public function createupdate(); public function delete(); public function formulario(); }<file_sep>/script.sql CREATE DATABASE phpcrud CHARACTER SET utf8 COLLATE utf8_unicode_ci; CREATE TABLE albums ( id INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY, title VARCHAR(200), created_at timestamp DEFAULT CURRENT_TIMESTAMP, updated_at timestamp DEFAULT CURRENT_TIMESTAMP )<file_sep>/app/Service/BaseService.php <?php namespace App\Service; interface BaseService { public function listarTodos($url); public function obtenerPorId($url, $id); public function eliminarPorId($url, $id); public function obtenerPorIdAdicional($url, $id, $add); }<file_sep>/app/GuzzleRequest.php <?php namespace App; use GuzzleHttp\Client; class GuzzleRequest { public $cliente; public function __construct(){ $this->cliente = new Client(); } protected function get($url) { $res = $this->cliente->request('GET', $url); return json_decode($res->getBody()->getContents(),true); } protected function delete($url) { $res = $this->cliente->request('DELETE', $url); return json_decode($res->getStatusCode(),true); } }<file_sep>/app/Service/PostService.php <?php namespace App\Service; use App\GuzzleRequest; class PostService extends GuzzleRequest implements BaseService { public function listarTodos($url) { return $this->get('http://jsonplaceholder.typicode.com/'.$url); } public function obtenerPorId($url, $id) { return $this->get('http://jsonplaceholder.typicode.com/'.$url.'/'.$id); } public function obtenerPorIdAdicional($url, $id, $add) { return $this->get('http://jsonplaceholder.typicode.com/'.$url.'/'.$id.'/'.$add); } public function eliminarPorId($url, $id) { return $this->delete('http://jsonplaceholder.typicode.com/'.$url.'/'.$id); } }<file_sep>/resources/views/album_list.php <?php include("components/header.php")?> <div class="container"> <div class="row"> <h3>Listado de Album - Base de Datos</h3> <a class='btn waves-effect waves-light red darken-1' type='submit' name='action' href='?c=Album&a=formulario'>Crear Album <i class="material-icons right">create_new_folder</i> </a> <br> <?php foreach ($data as $post) { if (isset($post["id"])){ print_r( " <div class=\"col m12\"> <div class=\"card horizontal\"> <div class=\"card-stacked\"> <div class=\"card-content\"> <a class=\"card-title activator grey-text text-darken-4\">{$post["title"]}</a> </div> <div class=\"card-action\"> <a class='btn waves-effect waves-light blue darken-4' type='submit' name='action' href='?c=Album&a=formulario&id={$post["id"]}'>Editar <i class=\"material-icons right\">edit</i> </a> <a class='btn waves-effect waves-light red darken-1' type='submit' name='action' href='?c=Album&a=delete&id={$post["id"]}'>Eliminar <i class=\"material-icons right\">delete</i> </a> </div> </div> </div> </div>" ); } } ?> </div> </div> <?php include("components/footer.php")?> <file_sep>/resources/views/post_form.php <?php include("components/header.php")?> <div class="container"> <div class="row"> <h3>Formulario</h3> </div> </div> <?php include("components/footer.php")?> <file_sep>/resources/views/album_form.php <?php include("components/header.php")?> <div class="container"> <div class="row"> <h3>Formulario</h3> <?php print_r(" <div class=\"row\"> <form class=\"col s12\" action='?c=Album&a=createupdate&id={$data["id"]}' method='POST' enctype='multipart/form-data'> <div class=\"row\"> <div class='input-field col s6'> <input id='last_name' type='text' name='title' required value='{$data["title"]}'> <label for='last_name'>Titulo</label> </div> </div> <button class='btn waves-effect waves-light blue darken-4' type='submit'>Guardar <i class='material-icons right'>save</i> </button> </form> </div> "); ?> <!--<div class="row"> <form class="col s12" action="?c=Album&a=createupdate&id=<?php /*$data["id"] */?>" method="POST" enctype="multipart/form-data"> <div class="row"> <div class="input-field col s6"> <input id="last_name" type="text" name="title" class="validate" required value="<?/*= $data["id"] */?>"> <label for="last_name">Titulo</label> </div> </div> <button class='btn waves-effect waves-light blue darken-4' type='submit'>Guardar <i class='material-icons right'>save</i> </button> </form> </div>---> </div> </div> <?php include("components/footer.php")?> <file_sep>/app/Controller/AlbumController.php <?php namespace App\Controller; use App\Entities\Album; class AlbumController implements BaseController { public function index() { $albunes = Album::get(); $this->view('album_list', $albunes); } public function obtener() { // TODO: Implement obtener() method. } public function createupdate() { if ($_REQUEST['id'] > 0) { $album = Album::find($_REQUEST['id']); $album->title = $_REQUEST['title']; $album->save(); $this->index(); } else { $album = new Album(); $album->title = $_REQUEST['title']; $album->save(); $this->index(); } } public function delete() { if(isset($_REQUEST['id'])){ $album = Album::find($_REQUEST['id']); $album->delete(); $this->index(); } } public function formulario() { if(isset($_REQUEST['id'])){ $album = Album::find($_REQUEST['id']); $this->view('album_form',$album); } else { $this->view('album_form'); } } public function view($vista,$datos = null){ $data = $datos; require_once __DIR__ . "/../../resources/views/" . $vista . ".php"; } }
ec3a32f6984223f3c8b0ce72382d251be188f51c
[ "Markdown", "SQL", "PHP" ]
13
PHP
kevinlozada1102/php_api_jsonplaceholder
801d38c717d326756390ab0e455da5b3b94e8465
a9e34bd36075fc99a645d713c51d4d8c27181f30
refs/heads/master
<repo_name>bobyang9/Eat-the-Cake<file_sep>/LeaderboardUserComparator.java import java.util.*; class LeaderboardUserComparator implements Comparator<LeaderboardUser>{ public int compare(LeaderboardUser lu1, LeaderboardUser lu2) { if(lu1.getProgressDouble() > lu2.getProgressDouble()) { return 1; // lu1 is greater than lu2 } else if(lu1.getProgressDouble() < lu2.getProgressDouble()) { return -1; // lu2 is greater than lu1 } else { if(lu1.getPrestige() > lu2.getPrestige()) { return 1; // lu1 is greater than lu2 } else if(lu1.getPrestige() < lu2.getPrestige()) { return -1; // lu2 is greater than lu1 } else { if(lu1.getLevel() > lu2.getLevel()) { return 1; // lu1 is greater than lu2 } else if(lu1.getLevel() < lu2.getLevel()) { return -1; // lu2 is greater than lu1 } else { if(lu1.getName().compareTo(lu2.getName()) > 0) { return 1; // lu1 is greater than lu2 } else if(lu1.getName().compareTo(lu2.getName()) < 0) { return -1; // lu2 is greater than lu1 } else { return 0; } } } } } }<file_sep>/ProgressBarVersion5Branch1.java import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.Writer; /** * TODO: Add permanent leaderboard * TODO: Make buttons bounce off wall * TODO: Make algorithm for increasing point values per click and increasing amount of points needed per level (logarithmic is best) * TODO: Make abbreviations (k for thousand, m for million, b for billion, t for trillion) make separate method, enter number return string * TODO: Powerups (freeze, speedup to troll, increased points, 100*factor free points, minus points, minus damage, make buttons appear or disappear) * TODO: Make 'prestige' * TODO: Make random point values * TODO: Each click background changes color * TODO: Images on buttons and different type of images have different effects * * "Strange Color" addition: Press up arrow to change the background color for one second, press down arrow to cancel * "Speed Up" addition: Press right arrow to speed up, press left arrow to return animation to normal * Logarithmic increment and exp points requirement added * Prestige started but did not finish, what Prestige does is multiply base increment by * amount of levels / 5 (change increment to double value since you can * cast to int at the end anyways) * Square buttons easier to press added, might add easy, medium, hard mode based on size and shape of buttons (easy is * big, square buttons, medium is rectangular buttons like normal, and hard is buttons of different shapes (random) and * small on average * hard mode also moves quicker (maybe turnMod = 1? that is evil) * * * @author <NAME> * @version May 31, 2018 * @sources I used ntu.edu Java Game Framework for the general template to start * writing this program. I also used some code from java2novice.com for * learning how to write strings to a file */ public class ProgressBarVersion5Branch1 extends JPanel // main class for the game { // ================================================================================================ // instance fields // ================================================================================================ // Define constants for the game static final int CANVAS_WIDTH = 800; // width and height of the game screen static final int CANVAS_HEIGHT = 600; static final int UPDATES_PER_SEC = 100; // number of game update per second static final long UPDATE_PERIOD_NSEC = 1000000000L / UPDATES_PER_SEC; // nanoseconds private final static double multiplier = 1.6; private final static String newline = "\n"; // ...... // Enumeration for the states of the game. static enum GameState { INITIALIZED, PLAYING, PAUSED, GAMEOVER, DESTROYED } Color[] colorArray = new Color[] {Color.GREEN, new Color(255, 200, 255), Color.MAGENTA, Color.PINK, Color.BLUE, Color.RED, Color.CYAN, Color.YELLOW, Color.ORANGE}; static GameState state; // current state of the game // Define instance variables for the game objects // ...... // ...... static File myFile = new File("/Users/Susan/Documents/Java Workspace/Random Graphics/src/ProgressBarGameLeaderboard"); private double progress = 0; // the amount of progress (amount of pages already read) private double numPages = 10; // number of pages to read in assignment, default is 10 pages // Handle for the custom drawing panel private GameCanvas canvas; // the canvas on which objects are drawn private ArrayList<JButton> buttonList; private JButton button; // button to increase progress (increments it by 1 each time) private int level = 1; // level of player private int turn = 0; // for movement to get rid of bug (when the squares move every turn they move a lot more than twice as fast?) private int turnMod = 2; // for testing bug stated in above line private int increment = 1; // increment each time press button private int baseIncrement = 1; // for prestige private int prestige = 0; // for prestige private boolean strangeColor = false; // for strangeColor private int strangeColorCooldown = 0; // for strangeColor addition private String name = "bob"; //for leaderboard private JTextField textField; // the text field with which the user can enter their goal (how many pages) private String text = "10"; // text from textField goes to here, defaults is 10 pages // ================================================================================================ // constructor // ================================================================================================ // Constructor to initialize the UI components and game objects /** * constructor */ public ProgressBarVersion5Branch1() { // Initialize the game objects gameInit(); //gameStart(); // UI components canvas = new GameCanvas(); canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT)); this.add(canvas); //creates a new button; the user clicks it to increase progress by 1 each time button = new JButton("Increase progress"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { // if progress is less than the number of pages in the goal, then increment progress // to prevent progress bar from overflowing if(progress < numPages) { progress = progress + increment; } } }); //canvas.add(button); // Other UI components such as button, score board, if any. // ...... buttonList = new ArrayList<JButton>(); buttonList.add(button); } // ================================================================================================ // methods // ================================================================================================ // All the game related codes here /** * Initialize all the game objects, run only once in the constructor of the main * class. */ public void gameInit() { // ...... state = GameState.INITIALIZED; } /** * Shutdown the game, clean up code that runs only once. */ public void gameShutdown() { System.out.println("here"); BufferedWriter bufferedWriter = null; try { String strContent = name + " " + (int) progress + " " + level + " " + prestige; System.out.println(strContent); //File myFile = new File("C:/MyTestFile.txt"); // check if file exist, otherwise create the file before writing if (!myFile.exists()) { myFile.createNewFile(); } Writer writer = new FileWriter(myFile); bufferedWriter = new BufferedWriter(writer); bufferedWriter.write(strContent); } catch (IOException e) { e.printStackTrace(); } finally{ try{ if(bufferedWriter != null) bufferedWriter.close(); } catch(Exception ex){ } } state = GameState.GAMEOVER; System.exit(0); } /** * To start and re-start the game. */ public void gameStart() { // Create a new thread Thread gameThread = new Thread() { // Override run() to provide the running behavior of this thread. @Override public void run() { gameLoop(); } }; // Start the thread. start() calls run(), which in turn calls gameLoop(). gameThread.start(); } /** * Run the game loop here. */ private void gameLoop() { // Regenerate the game objects for a new game // ...... state = GameState.PLAYING; // Game loop long beginTime, timeTaken, timeLeft; // in msec while (state != GameState.GAMEOVER) { beginTime = System.nanoTime(); if (state == GameState.PLAYING) { // not paused // Update the state and position of all the game objects, // detect collisions and provide responses. gameUpdate(); } // Refresh the display repaint(); // Delay timer to provide the necessary delay to meet the target rate timeTaken = System.nanoTime() - beginTime; timeLeft = (UPDATE_PERIOD_NSEC - timeTaken) / 1000000L; // in milliseconds if (timeLeft < 10) timeLeft = 10; // set a minimum try { // Provides the necessary delay and also yields control so that other thread can // do work. Thread.sleep(timeLeft); } catch (InterruptedException ex) { } } } /** * Update the state and position of all the game objects, detect collisions and provide responses. */ public void gameUpdate() { } /** * Refresh the display. Called back via repaint(), which invoke the * paintComponent(). * * @param g2d */ private void gameDraw(Graphics2D g2d) { switch (state) { case INITIALIZED: g2d.setFont(new Font("Monospaced", Font.PLAIN, 24)); g2d.setColor(Color.CYAN); g2d.drawString("Welcome to the progress bar game! Enter your username:", 10, 100); textField = new JTextField(20); textField.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { //puts the text that the user enters into String text and checks if it is a number name = textField.getText(); //textField.setEditable(false); //canvas.remove(textField); //System.out.println("hello"); //textField.setVisible(false); //textField.setEditable(false); //textField = null; for(JButton b : buttonList) { b.setBounds(300, 5, 100, 100); //IMPORTANT } gameStart(); } }); //adds the textField to the canvas canvas.add(textField); Font f = new Font("Monospaced", Font.PLAIN, 24); textField.setBounds(200,150,400,50); textField.setFont(f); textField.setHorizontalAlignment(JTextField.CENTER); break; case PLAYING: //draw progress bar g2d.setColor(Color.CYAN); g2d.drawRect(10, 75, 301, 50); g2d.setColor(Color.BLUE); g2d.fillRect(15, 80, (int)(progress/numPages*290.0)+1, 40); // printing texts g2d.setColor(Color.CYAN); g2d.drawString("Level: " + level, 500, 20); g2d.setFont(new Font("Monospaced", Font.PLAIN, 12)); g2d.drawString("Press the button to increase the page #", 10, 20); //button.setBounds(300, 5, 100, 100); turn++; for(JButton b : buttonList) { if(turn%turnMod==0) { if(b.getX() > CANVAS_WIDTH && b.getY() > CANVAS_HEIGHT) { b.setBounds(0, 0, 100, 100); } //Wow, I just noticed that "else if" is an anagram for "selfie " haha else if(b.getX() > CANVAS_WIDTH) { b.setBounds(0, b.getY()+1, 100, 100); } else if(b.getY() > CANVAS_HEIGHT) { b.setBounds(b.getX()+1, 0, 100, 100); } else { b.setBounds(b.getX()+1, b.getY()+1, 100, 100); } } } // printing more texts in different font (progress as a fraction // and "Congrats!" when progress bar is full), also adjusts for // position of "Congrats!" so the fraction does not overlap with // the "Congrats!" g2d.setFont(new Font("Eurostile", Font.PLAIN, 24)); g2d.drawString("" + (int)(progress) + "/" + (int)numPages, 325, 110); if(progress == numPages || (progress > numPages && progress < numPages+increment)) { g2d.drawString("Congrats!", 370 + ("" + (int)numPages).length()*30, 110); level++; increment = (int)(increment * Math.pow(multiplier-0.1, level) * 0.8); numPages = (int)(numPages * Math.pow(multiplier, level) * 0.8); JButton newButton = new JButton("Increase progress"); newButton.setBounds(300, 5, 100, 100); newButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { // if progress is less than the number of pages in the goal, then increment progress // to prevent progress bar from overflowing if(progress < numPages) { progress = progress + increment; } } }); canvas.add(newButton); buttonList.add(newButton); } break; case PAUSED: // ...... break; case GAMEOVER: System.out.println("here"); BufferedWriter bufferedWriter = null; try { String strContent = name + " " + progress + " " + level + " " + prestige; //File myFile = new File("C:/MyTestFile.txt"); // check if file exist, otherwise create the file before writing if (!myFile.exists()) { myFile.createNewFile(); } Writer writer = new FileWriter(myFile); bufferedWriter = new BufferedWriter(writer); bufferedWriter.write(strContent); } catch (IOException e) { e.printStackTrace(); } finally{ try{ if(bufferedWriter != null) bufferedWriter.close(); } catch(Exception ex){ } } break; } // ...... } /** * Process a key-pressed event. Update the current state. * * @param keyCode */ public void gameKeyPressed(int keyCode) { switch (keyCode) { case KeyEvent.VK_UP: strangeColor = true; break; case KeyEvent.VK_DOWN: strangeColor = false; break; case KeyEvent.VK_LEFT: turnMod = 2; break; case KeyEvent.VK_RIGHT: turnMod = 1; break; case KeyEvent.VK_SPACE: progress = progress + increment; break; case KeyEvent.VK_N: gameShutdown(); break; } } // Other methods // ...... // Custom drawing panel, written as an inner class. /** * @author <NAME> * @version May 31, 2018 * @sources I used ntu.edu Java Game Framework for the general template to start * writing */ class GameCanvas extends JPanel implements KeyListener { // Constructor public GameCanvas() { setFocusable(true); // so that can receive key-events requestFocus(); addKeyListener(this); } // Override paintComponent to do custom drawing. // Called back by repaint(). @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g; super.paintComponent(g2d); // paint background if(strangeColorCooldown > 0) { strangeColorCooldown--; } else if(strangeColor == false && strangeColorCooldown == 0) { setBackground(Color.BLACK); // may use an image for background } else { setBackground(colorArray[(int)(Math.random()*9)]); strangeColor = false; strangeColorCooldown = 100; } // Draw the game objects gameDraw(g2d); } // KeyEvent handlers @Override public void keyPressed(KeyEvent e) { gameKeyPressed(e.getKeyCode()); } @Override public void keyReleased(KeyEvent e) { } @Override public void keyTyped(KeyEvent e) { } } /** * main * * @param args */ public static void main(String[] args) { // Use the event dispatch thread to build the UI for thread-safety. SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("Progress Bar Version 4 Branch 1 (Game)"); // Set the content-pane of the JFrame to an instance of main JPanel frame.setContentPane(new ProgressBarVersion5Branch1()); // main JPanel as content pane // frame.setJMenuBar(menuBar); // menu-bar (if defined) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); // center the application window frame.setVisible(true); // show it } }); } }<file_sep>/LeaderboardUser.java /** * Works with the leaderboard function in ProgressBarVersion4Branch1 or higher (except version 5) * @author <NAME> * */ public class LeaderboardUser{ private String name; private double progress; private int level; private int prestige; public LeaderboardUser(String name, double progress, int level, int prestige) { this.name = name; this.progress = progress; this.level = level; this.prestige = prestige; } public String getName() { return name; } public double getProgressDouble() { return progress; } public String getProgressString() { String s = "" + progress; return s; } public int getLevel() { return level; } public int getPrestige() { return prestige; } }<file_sep>/README.md # Eat-the-Cake A game about eating cakes. Farm until you're full with trillions of experience points -- ahem, I mean cakes.
bf0b6ef212a80aaf552514caaa2e29fbadc73522
[ "Markdown", "Java" ]
4
Java
bobyang9/Eat-the-Cake
c10a256ac148ea8315ccca159712e27f3aed7d75
1159e77cb80005dac5d16ed186a917fb37fa5020
refs/heads/main
<repo_name>php83projects/bankapp<file_sep>/header.php <?php /* Start the Session, required for Session-based authentication. Remeber to call session_start() before sending any output to the remote client. Also, make sure to set a proper session cookie lifetime in your php.ini. For example, this sets the cookie lifetime to 7 days: session.cookie_lifetime=604800 */ session_start(); ?> <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="icon" type="image/png" href="images/favicon.png"/> <link rel="stylesheet" href="styles.css"> <title>The Internet Bank</title> </head> <body> <header> <div> <a href="index.php"> <img src="images/logo.jpg" class="logo" alt="logo" > </a> </div> </header> <div class="hero"> <img src="images/hero.jpg" class="hero" alt=""> </div><file_sep>/admin.php <?php require './db.php'; include './header.php'; ?> <div class="main"> <h1>You are now logged into the Admin Area</h1> <div class="display-grid"> <?php include 'menu-left.php'; ?> <div class="content"> admin area </div> </div> </div> <file_sep>/register.php <?php include './header.php'; ?> <div class="main"> <h1>Register your account for the bank</h1> <section> <div class="login-form"> <form action="register-form.php" method="POST"> <label for="username">Username:</label><br> <input type="text" id="username" name="username"><br> <span class="error" id="username"><?php echo isset($error['username'])?$error['username']:''; ?></span> <label for="email">Email:</label><br> <input type="text" id="email" name="email"><br> <span class="error" id="email"><?php echo isset($error['email'])?$error['email']:''; ?></span> <label for="pword">Password:</label><br> <input type="text" id="pword" name="pword"><br> <span class="error" id="pword"><?php echo isset($error['pword'])?$error['pword']:''; ?></span> <input type="submit" /> </form> </div> </section> </div><file_sep>/login.php <?php require './db.php'; include './header.php'; //print_r($_POST); $statement = $connection->prepare('SELECT * FROM users WHERE username = :username'); if($statement){ $result = $statement->fetchAll(PDO::FETCH_ASSOC); if(!empty($result)){ header('Location: index.php'); exit; } else { //header('Location: register.php'); //exit; } } ?> <div class="main"> <h1>Login to the bank</h1> <section> <div class="login-form"> <form action="login-form.php" method="POST"> <label for="username">Username:</label><br> <input type="text" id="username" name="username"><br> <label for="pword">Password:</label><br> <input type="text" id="pword" name="pword"><br> <input type="submit" /> </form> </div> </section> </div><file_sep>/index.php <?php require './db.php'; require './Account.php'; include './header.php'; ?> <div class="main homepage"> <h1>Welcome to the bank</h1> <span class="homepage-links"><a href="./register.php">Register a new account</a></span><br /> <span class="homepage-links"><a href="./login.php">Login to an existing account</a></span> </div> <!-- // enter username and email -> checks if existing user -> redirects to role screen based on user-role // Admin Role Screen -> create user -> update user -> delete user // User Role Screen -> Account information -> Balance -> Statement --><file_sep>/db.php <?php $data = $_POST; $dsn = 'mysql:dbname=bank;host=localhost'; $dbUser = 'root'; $dbPassword ='<PASSWORD>'; try { $connection = new PDO($dsn,$dbUser,$dbPassword); } catch (PDOException $exception) { exit; } ?> <file_sep>/login-form.php <?php require './db.php'; include './header.php'; $data = $_POST; $statement = $connection->prepare('SELECT * FROM users WHERE username = :username'); if($statement){ $statement->execute([ ':username' => $data['username'], ]); $result = $statement->fetchAll(PDO::FETCH_ASSOC); if(!empty($result)){ header('Location: admin.php'); exit; } else { header('Location: index.php'); exit; } }<file_sep>/Account.php <?php /** * Created by PhpStorm. * User: carlsimpson * Date: 05/11/2020 * Time: 10:04 */ class Account { private $id; private $name; private $authenticated; public function __construct() { $this->id = NULL; $this->name = NULL; $this->authenticated = FALSE; } public function __destruct() { } public function getId() { return $this->id; } public function getName() { return $this->name; } public function isAuthenticated() { return $this->authenticated; } }<file_sep>/register-form.php <?php require './db.php'; include './header.php'; $data = $_POST; if(empty($_POST['username']) || empty($_POST['email']) || empty($_POST['pword'])) { echo "<div class='main'>"; echo "<p class=''>Please Fill in :</p>"; echo "<p class='error'>Username :</p>"; echo "<p class='error'>Email :</p>"; echo "<p class='error'>Password :</p>"; echo "<a href='register.php'>BACK :</a>"; echo "</div>"; } else { $statement = $connection->prepare('INSERT INTO users (username, email, pword) VALUES (:username , :email , :pword)'); if($statement) { $result = $statement->execute([ ':username' => $data['username'], ':email' => $data['email'], ':pword' => $data['pword'] ]); echo "<div class='main'>"; echo "</p>your details were entered into the Database</p>"; echo "<a href='index.php'>Continue -></a>"; echo "</div>"; } else { echo 'did not enter statement into database'; } } ?>
89886a487b2db8ac0af4cf1241327e4561793252
[ "PHP" ]
9
PHP
php83projects/bankapp
29f58cc789dc187f34883818d15639c30981946a
710d1bb6ed38c14c55a81aece20cf311f8b20773
refs/heads/master
<repo_name>cnzhhi/fragment2<file_sep>/src/com/example/fragment2/fragment/HomeFragment.java package com.example.fragment2.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.fragment2.R; public class HomeFragment extends Fragment { // ����Fragment��View private View rootView; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if (rootView == null) { rootView = inflater.inflate(R.layout.fragment_home, container, false); } else { // �����rootView��Ҫ�ж��Ƿ��Ѿ����ӹ�parent // �����parent��Ҫ��parentɾ�� ViewGroup parent = (ViewGroup) rootView.getParent(); if (parent != null) { parent.removeView(rootView); } } return rootView; } }
a6d0ef57fe5b761fed92ce5ecdee99248c556031
[ "Java" ]
1
Java
cnzhhi/fragment2
834901b2834f2881e62181c9d42925c5d60cb50b
c7633c5f98d4f3c352d6c98b2af1f9b2e5f0a781
refs/heads/main
<repo_name>wissmedia/wiss-node<file_sep>/routes/qbankRouter.js const { Router } = require("express"); const qbankController = require("../controllers/qbankController"); const router = Router(); router.get("/add", qbankController.qbank_add_get); router.get("/", qbankController.qbank_index); router.post("/", qbankController.qbank_add_post); router.get("/:id", qbankController.qbank_detail); router.delete("/:id", qbankController.qbank_delete); module.exports = router; <file_sep>/controllers/settingController.js let appTitle = "Paperon"; const setting_index = (req, res) => { let menus = [ ] let navMenus = [ { link: '/admin', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, ]; res.render("setting/setting", { appTitle, navTitle: "Pengaturan", navMenus, }); }; module.exports = { setting_index }<file_sep>/controllers/quesionerController.js let appTitle = 'Paperon' const quesioner_index = (req, res) => { let navMenus = [ { link: '/admin', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, { link: '/admin/quesioner/add', icon: 'fas fa-plus-circle', label: 'Tambah' }, ]; res.render("quesioner/quesioner", { appTitle, navTitle: "Bank Kuesioner", navMenus, }); } const quesioner_detail = (req, res) => { let navMenus = [ { link: '/admin/quesioner', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, ]; res.render('quesioner/quesioner-detail', { appTitle, navTitle: "Detail Kuesioner", navMenus, }); } const quesioner_add_get = (req, res) => { let navMenus = [ { link: '/admin/quesioner', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, ]; res.render('quesioner/quesioner-add', { appTitle, navTitle: "Buat Kuesioner", navMenus, }); } const quesioner_add_post = (req, res) => {} const quesioner_delete = (req, res) => {} module.exports = { quesioner_index, quesioner_detail, quesioner_add_get, quesioner_add_post, quesioner_delete }<file_sep>/app.js // # import dependendcies const express = require('express') const path = require('path') const logger = require('morgan') const mongoose = require('mongoose') const cookieParser = require('cookie-parser') const createError = require('http-errors'); // # import required files const config = require('./config') const qbankRouter = require('./routes/qbankRouter') const authRouter = require('./routes/authRouter') const quesionerRouter = require('./routes/quesionerRouter') const resultRouter = require('./routes/resultRouter') // # set app const const app = express() const host = config.app.host const port = config.app.port const appTitle = 'Paperon' // # set db const const dbHost = config.db.host const dbPort = config.db.port const dbUser = config.db.user const dbPass = <PASSWORD>.db.pass const dbName = config.db.database // # dbString (full string) => 'mongodb://user:pass@host:port/database' // const dbURI = config.db.db_string // # dbString (partial) const dbURI = `mongodb://${dbUser}:${dbPass}@${dbHost}:${dbPort}/${dbName}` // # run express app (no db) app.listen(port, host, () => { console.log(`App listening at http://${host}:${port}`) }) // # run express app (with mongodb) /** * Change `Connected to DB at ${dbHost}:${dbPort}` * to * `Connected to DB at ${dbURI}` * if using dbURI full string */ // mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }) // .then(result => { // console.log(`Connected to DB at ${dbHost}:${dbPort}`) // app.listen(port, host, () => { // console.log(`App listening at http://${host}:${port}`) // }) // }) // .catch(err => { // console.log(err) // }) // view engine app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs') // middleware app.use(express.static(path.join(__dirname, 'public'))) app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cookieParser()) app.use(logger('dev')) // app routes app.get('/', (req, res) => { navMenus = [] res.render('index', { appTitle, navTitle: 'Beranda', navMenus }) }) app.get('/admin', (req, res) => { const navMenus = [ { link: '/admin/qbank', icon: 'fas fa-warehouse', label: 'Bank Pertanyaan' }, { link: '/admin/quesioner', icon: 'fas fa-newspaper', label: 'Kuesioner' }, { link: '/admin/result', icon: 'fas fa-poll', label: 'Hasil' }, { link: '/admin/setting', icon: 'fas fa-cogs', label: 'Pengaturan' }, ] res.render('admin/admin', { appTitle, navTitle: 'Admin Panel', navMenus }) }) // #Admin Route // auth route app.use(authRouter) // qbank route app.use('/admin/qbank', qbankRouter) // quesioner route app.use('/admin/quesioner', quesionerRouter) // result route app.use('/admin/result', resultRouter) //setting route app.get('/admin/setting', (req, res) => { const navMenus = [ { link: '/admin', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, ] res.render('setting/setting', { appTitle, navTitle: 'Pengaturan', navMenus }) }) // responden route app.get('/responden', (req, res) => { res.send('responden') }) // catch 404 and forward to error handler app.use(function (req, res, next) { next(createError(404)); }); // error handler app.use(function (err, req, res, next) { // set locals, only providing error in development res.locals.message = err.message; res.locals.error = req.app.get('env') === 'development' ? err : {}; // render the error page res.status(err.status || 500); res.render('error', { appTitle, navTitle: '404' }); });<file_sep>/routes/resultRouter.js const { Router } = require("express"); const resultController = require("../controllers/resultController"); const router = Router(); router.get("/", resultController.result_index); router.get("/:id", resultController.result_detail); module.exports = router; <file_sep>/routes/quesionerRouter.js const { Router } = require("express"); const quesionerController = require("../controllers/quesionerController"); const router = Router(); router.get("/add", quesionerController.quesioner_add_get); router.get("/", quesionerController.quesioner_index); router.post("/", quesionerController.quesioner_add_post); router.get("/:id", quesionerController.quesioner_detail); router.delete("/:id", quesionerController.quesioner_delete); module.exports = router<file_sep>/Dockerfile FROM node:14-slim WORKDIR /app COPY package.json . RUN npm install COPY . ./ ENV PORT=2021 EXPOSE 2021 CMD ["node", "app.js"]<file_sep>/controllers/qbankController.js let appTitle = "Paperon"; const qbank_index = (req, res) => { let navMenus = [ { link: '/admin', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, { link: '/admin/qbank/add', icon: 'fas fa-plus-circle', label: 'Tambah' }, ]; res.render("qbank/qbank", { appTitle, navTitle: "Bank Pertanyaan", navMenus, }); }; const qbank_detail = (req, res) => { let navMenus = [ { link: '/admin/qbank', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, ]; res.render('qbank/qbank-detail', { appTitle, navTitle: "Detail Pertanyaan", navMenus, }); }; const qbank_add_get = (req, res) => { let navMenus = [ { link: '/admin/qbank', icon: 'fas fa-chevron-circle-left', label: 'Kembali' }, ]; res.render('qbank/qbank-add', { appTitle, navTitle: "Tambah Pertanyaan", navMenus, }); }; const qbank_add_post = (req, res) => { let navTitle = []; let menus = []; let navMenus = []; res.send("qbank - add_post"); }; const qbank_delete = (req, res) => { let navTitle = []; let menus = []; let navMenus = []; res.send("qbank - delete"); }; module.exports = { qbank_index, qbank_detail, qbank_add_get, qbank_add_post, qbank_delete, }; <file_sep>/config.js require("dotenv").config(); const config = { app: { host: process.env.APP_HOST || "localhost", port: parseInt(process.env.APP_PORT) || 1234, }, db: { host: process.env.DB_HOST || "localhost", port: process.env.DB_PORT || 27017, user: process.env.DB_USERNAME || "admin", pass: process.env.DB_PASSWORD || "<PASSWORD>", database: process.env.DB_DATABASE || "db_test", db_string: process.env.DB_CONN_STRING, }, }; module.exports = config; <file_sep>/README.md # wiss-node Versi alternatif dari node-wiss
016dc76785a5443dfb296a43b92bea5d485a8427
[ "JavaScript", "Dockerfile", "Markdown" ]
10
JavaScript
wissmedia/wiss-node
b3b62950ab0700d56269eef900aab91037c3ea13
7fa7ae8d21f8204121d102ea21e450f144c865e1
refs/heads/main
<file_sep><h1> color grid system</h1> <pre> <h2> This is a website for the copy paste of haxa color. ✍</h2> => the "copy icon" , when u click it the color code will get copy. <h4> the view of website is given below 💙.</h4> </pre> ![Screenshot (131)](https://user-images.githubusercontent.com/69325431/121912437-35e0cc00-cd4e-11eb-8409-7e7dbab3d3ec.png) <file_sep> function myFunction() { var copyText = document.getElementById("myInput"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction1() { var copyText = document.getElementById("myInput1"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction2() { var copyText = document.getElementById("myInput2"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction3() { var copyText = document.getElementById("myInput3"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction4() { var copyText = document.getElementById("myInput4"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction5() { var copyText = document.getElementById("myInput5"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction6() { var copyText = document.getElementById("myInput6"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction7() { var copyText = document.getElementById("myInput7"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction8() { var copyText = document.getElementById("myInput8"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction9() { var copyText = document.getElementById("myInput9"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction10() { var copyText = document.getElementById("myInput10"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction11() { var copyText = document.getElementById("myInput11"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction12() { var copyText = document.getElementById("myInput12"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction13() { var copyText = document.getElementById("myInput13"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction14() { var copyText = document.getElementById("myInput14"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction15() { var copyText = document.getElementById("myInput15"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction16 () { var copyText = document.getElementById("myInput16"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction17() { var copyText = document.getElementById("myInput17"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction18() { var copyText = document.getElementById("myInput18"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction19() { var copyText = document.getElementById("myInput19"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction20() { var copyText = document.getElementById("myInput20"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction21() { var copyText = document.getElementById("myInput21"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction22() { var copyText = document.getElementById("myInput22"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction23() { var copyText = document.getElementById("myInput23"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction24() { var copyText = document.getElementById("myInput24"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction25() { var copyText = document.getElementById("myInput25"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction26() { var copyText = document.getElementById("myInput26"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction27() { var copyText = document.getElementById("myInput27"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction28() { var copyText = document.getElementById("myInput28"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction29() { var copyText = document.getElementById("myInput29"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction30() { var copyText = document.getElementById("myInput30"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction31() { var copyText = document.getElementById("myInput31"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction32() { var copyText = document.getElementById("myInput32"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction33() { var copyText = document.getElementById("myInput33"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction34() { var copyText = document.getElementById("myInput34"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction35() { var copyText = document.getElementById("myInput35"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction36() { var copyText = document.getElementById("myInput36"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction37() { var copyText = document.getElementById("myInput37"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction38() { var copyText = document.getElementById("myInput38"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction39() { var copyText = document.getElementById("myInput39"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction40() { var copyText = document.getElementById("myInput40"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction41() { var copyText = document.getElementById("myInput41"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction42() { var copyText = document.getElementById("myInput42"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction43() { var copyText = document.getElementById("myInput43"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction44() { var copyText = document.getElementById("myInput44"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction45() { var copyText = document.getElementById("myInput45"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction46() { var copyText = document.getElementById("myInput46"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction47() { var copyText = document.getElementById("myInput47"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction48() { var copyText = document.getElementById("myInput48"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction49() { var copyText = document.getElementById("myInput49"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); } function myFunction50() { var copyText = document.getElementById("myInput50"); copyText.select(); copyText.setSelectionRange(0, 99999); document.execCommand("copy"); alert("Copied the text: " + copyText.value); }
c5ed7c481de21957d432a3c751e0d82c81acf164
[ "Markdown", "JavaScript" ]
2
Markdown
thorved/color_grid_system
a9a4f81ed834a429d19db3342cacdd3ee7c7ef58
e7d51f8ccaf7e3248b9e73e135a23c7cd120d242
refs/heads/master
<file_sep>exports.index=function(req,res){ res.render('stripform', { title: 'stripform' }); }<file_sep>var crypto = require('crypto'); var mongoose = require('mongoose'); var reporterSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, unique: true, lowercase: true, required: true }, publication: { type: String, required: true }, url: { type: String, default: 'Not available :(' }, twitter: { type: String, unique: true, lowercase: true } }); reporterSchema.methods.gravatar = function(size) { if (!size) size = 200; if (!this.email) { return 'https://gravatar.com/avatar/?s=' + size + '&d=retro'; } var md5 = crypto.createHash('md5').update(this.email).digest('hex'); return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro'; }; module.exports = mongoose.model('Reporter', reporterSchema);<file_sep>var secrets = require('../config/secrets'); var stripe = require('stripe')(secrets.stripe.apiKey); var Reporter = require('../models/Reporter'); var mcapi = require('mailchimp-api/mailchimp'); var blog = require('wordpress'); var client = blog.createClient({ /**@MSS *remote wordpress installation link and access details **/ url: "http://blog.press.farm/b", username: "dev", password: <PASSWORD>!" }); /** * GET / * Home page. */ exports.index = function(req, res) { client.getPosts({ status: 'publish'}, function( error, posts ) { var counter = posts.length; if (posts.length > 4) { posts = posts.slice(0,4); } Reporter.count({}, function(err, count) { if (posts && !error) { res.render('home', { title: 'Find journalists to write about your startup.', count: count, posts:posts }); } else { res.render('home', { title: 'Find journalists to write about your startup.', count: count }); } },function(err) { console.log(err); if (err.name == 'Invalid_ApiKey') { res.locals.error_flash = "Invalid API key. Set it in app.js"; } else if (error.error) { res.locals.error_flash = error.code + ": " + error.error; } else { res.locals.error_flash = "An unknown error occurred"; } res.render('home', { title: 'Find journalists to write about your startup' ,count: count}); }); }); }; exports.charge = function(req, res) { var stripeToken = req.body.stripeToken; var charge = stripe.charges.create({ amount: 900, currency: 'usd', card: stripeToken }, function(err, charge) { if (err && err.type === 'StripeCardError') { req.flash('error', { msg: 'There was a problem charging your card. :( No charge has been made.' }); res.redirect('/account'); } else { var user = req.user; user.datePaid = new Date().getTime(); user.save(); req.flash('success', { msg: 'Thanks! You now have full access for 30 days. :)' }); res.redirect('/account'); } }); }; exports.coupn = function(req, res) { //stripe.coupons.list({ limit: 3 }, function(err, coupons) { console.log("coupons",coupons); }); stripe.coupons.retrieve(req.body.id, function(err, coupon) { if(err){ //alert(err); console.log("shintuerr",err) return res.send(err); } else{ // alert("sucess"); console.log("shintusuccess",coupon); return res.send(coupon); } }); }; exports.salecharge = function(req, res) { var stripeToken = req.body.stripeToken; var charge = stripe.charges.create({ amount: 400000, currency: 'usd', card: stripeToken }, function(err, charge) { if (err && err.type === 'StripeCardError') { req.flash('error', { msg: 'There was a problem charging your card. :( No charge has been made.' }); res.redirect('/'); } else { req.flash('success', { msg: 'Thanks! press farm is now yours.' }); res.redirect('/'); } }); }; exports.sale = function(req, res) { res.render('sale'); }; exports.subscribe = function(req, res){ mc.lists.subscribe({id:secrets.mailgunformid.key, email:{email:req.body.email}}, function(data) { req.flash('success', { msg: 'User subscribed successfully! Look for the confirmation email.' }); res.redirect('/'); }, function(error) { if (error.error) { console.log("error", error); req.flash('errors', { msg: error.code + ": " + error.error }); } else { req.flash('errors', { msg: 'There was an error subscribing that user' }); } res.redirect('/'); }); }; /* * GET home page. */ <file_sep>var User = require('../models/User'); var Reporter = require('../models/Reporter'); var json2csv = require('json2csv'); var fs = require('fs'); exports.newReporter = function(req, res) { if (!req.user.admin) res.status(404); res.render('reporters/new', { title: 'Add Reporter' }); }; exports.getReporters = function(req, res, next) { Reporter.find({}, null, { sort: 'publication' }, function (err, reporters) { if (!req.user.subscribed()) { req.flash('errors', { msg: 'You currently have a free account. $9 will let you see emails for 30 days.' }); } res.render('reporters/index', { title: 'Browse Reporters', reporters: reporters, subscribed: req.user.subscribed() }); }); }; exports.createReporter = function(req, res, next) { if (!req.user.admin) res.status(404); req.assert('name', 'Name is required').notEmpty(); req.assert('email', 'Valid email is required').isEmail(); req.assert('publication', 'Publication is required').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.render('reporters/new', { title: 'Add Reporter', name: req.body.name, email: req.body.email, publication: req.body.publication, url: req.body.url, twitter: req.body.twitter }); } var reporter = new Reporter({ name: req.body.name, email: req.body.email, publication: req.body.publication, url: req.body.url, twitter: req.body.twitter }); Reporter.findOne({ email: req.body.email }, function(err, existingReporter) { if (existingReporter) { req.flash('errors', { msg: 'Reporter with that email address already exists.' }); res.redirect('/reporters/new'); } reporter.save(function(err) { console.log(err); if (err) { req.flash('errors', { msg: err.err }); } else { req.flash('success', { msg: 'Reporter added!' }); } res.redirect('/reporters/new'); }); }); }; exports.Reportercsv = function(req, res) { Reporter.find({},function(err,reporters){ var date = Date('dd/mm/yy hh:mm:ss'); if (err) { console.log("error"); }else{ console.log(reporters); json2csv({data: reporters, fields: ['_id', 'name', 'email','publication','twitter','_v','url']}, function(err, csv) { if (err) console.log(err); fs.writeFile('csv/file:'+date+'.csv', csv, function(err) { if (err) throw err; console.log('file saved'); res.redirect('/reporters'); }); }); } }); }; <file_sep> var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs'); var crypto = require('crypto'); var nodemailer = require('nodemailer'); var Reporter = require('../models/Reporter'); var secrets = require('../config/secrets'); var fs = require('fs'); var collections = ["reporters"]; var validator = require('node-validator'); var validator = require('validator'); exports.index=function(req,res){ Reporter.find({}, null, { sort: 'publication' }, function (err, reporters) { res.render('import', { title: 'Import contacts', reporters: reporters, }); }); } exports.deletereporters=function(req,res){ console.log(req.body); var locks = req.body; var arr = Object.keys(locks); var deleted=0; console.log("arr",arr); arr.forEach(function(entry) { Reporter.remove({'_id':entry},function (err, resp) { if(err) { console.log('error',err) }else{ deleted=1; } }) }); Reporter.find({}, null, { sort: 'publication' }, function (err, reporters) { res.render('import', { title: 'Import contacts', reporters: reporters, }); }); req.flash('success', { msg: +arr.length+' Reporters deleted successfully' }); } exports.importer = function(req, res) { //var mongoose = require('mongoose'); console.log("in contacts importer"); console.log(req.files.contacts); var add1 = []; var success=0; var emailerr=0; var notfilled=0; if (req.files.contacts) { var lineList = fs.readFileSync('uploads/'+req.files.contacts.name).toString().split('\n'); var s=1; if (lineList.length){ for ( var j=0; j<s;j++) { var line = lineList.shift(); line.split(',').forEach(function (entry, i) { add1[i] = entry.replace(/"/g, ""); // console.log("field",add1[i]); }); // console.log("length ",add1.length); if (add1.length > 3 && add1[0] == "name" && add1[1] == "email" && add1[2] == "publication" && add1[3] == "twitter" && add1[4] == "url") { //lineList.shift(); // Shift the headings off the list of records. console.log(lineList); lineList.pop(); // Shift the headings off the list of records. var add = []; function createDocRecurse() { //console.log("inside loop"); //console.log(lineList.length); //console.log(lineList); var s=lineList.length; //console.log("lineList.length",lineList.length); if (lineList.length){ for ( var j=0; j<s;j++) { var line = lineList.shift(); line.split(',').forEach(function (entry, i) { add[i] = entry.replace(/"/g, ""); }); //console.log(add[0]); if (add[0] && add[1] && add[2] && add[3] && add[4]){ var registration = new Reporter({'name':add[0],'email':add[1], 'publication':add[2],'twitter':add[3],'url':add[4]}); //console.log("registration",registration); if (validator.isEmail(add[1])) { //console.log("valid email"); registration.save(function(err,res){ if(err) { //console.log("not saved",err); }else { //console.log("saved",res); } }); //mail(add[1]); success=success+1; } else{ emailerr=emailerr+1; }}else { notfilled=notfilled+1; } } } } // req.flash('success', { msg: 'Contacts Added Successfully to Pressman and a mail has been sent with Username and password to them' }); createDocRecurse(); if (success>0) { req.flash('success', { msg: +success+' Contact Added Successfully to Pressman and a mail has been sent with Username and password to them' }); } if (emailerr>0) { req.flash('errors', { msg: +emailerr+ ' Email incorrect.' }); } if(notfilled>0){ req.flash('errors', { msg: +notfilled+ 'rows not filled completely' }); } } else{ console.log("not inserted"); req.flash('errors', { msg: 'Csv file not in proper format according to database schema' }); } } createDocRecurse(); function mail(email){ //console.log(email); //console.log(pass); var smtpTransport = nodemailer.createTransport('SMTP', { service: 'Mailgun', auth: { user: secrets.mailgun.user, pass: <PASSWORD>.mailgun.<PASSWORD> } }); var mailOptions = { to: email, from: '<EMAIL>', subject: 'Successfully Registered', text: 'You are Successfully registered as reporters into pressfarm.\n'+ "Please Login to http://" + req.headers.host + "/reporters \n\n"+ 'Thanks for registering with us' }; smtpTransport.sendMail(mailOptions, function(error, info){ if(error){ console.log(error); }else{ console.log('Message sent: ' + info.response); } }); //req.flash('success', { msg: 'Contacts Added Successfully to Pressman and a mail has been sent with Username and password to them' }); } //req.flash('success', { msg: 'Contacts Added Successfully to Pressman and a mail has been sent with Username and password to them' }); res.render('import'); } } else{ console.log('no file'); req.flash('errors', { msg: 'Please select csv file.' }); res.render('import'); } }; <file_sep>var Option = require('../models/options'); var collections = ["options"]; exports.index = function(req, res){ res.render('options', { title: 'Add_options'}) }; exports.addoption = function(req, res){ name=req.body.name; value=req.body.value; var opt = new Option({'_id':name,'name':name,'value':value}); opt.save(function(err,res){ if(err) { console.log("not saved",err); }else { console.log("saved",res); } }); res.render('options', { title: 'Add_options'}) };<file_sep>/*** * Blank array to store subscribers */ var User = require('./models/User'); var Reporters = require('./models/Reporter'); var exportUser = function() { User.find(function(error, data){ var userSibscribers = [] if( !error && data ) { data.forEach(function(item) { userSibscribers.push({name:item.email, email: item.email}); }); console.log("userSibscribers",userSibscribers); } }); } var exportReporter = function() { Reporters.find(function(error, data){ var reporterSibscribers = [] if( !error && data ) { data.forEach(function(item) { reporterSibscribers.push({name:item.name,email:item.email}); }); console.log("reporterSibscribers",reporterSibscribers); } }); } exports.Reportercsv = function(req, res) { Reporter.find({},function(err,reporters){ if (err) { console.log("error"); }else{ console.log(reporters); json2csv({data: reporters, fields: ['_id', 'name', 'email','publication','twitter','_v','url']}, function(err, csv) { if (err) console.log(err); fs.writeFile('file.csv', csv, function(err) { if (err) throw err; console.log('file saved'); }); }); } }) };<file_sep>/** * Module dependencies. */ var express = require('express'); var cookieParser = require('cookie-parser'); var compress = require('compression'); var session = require('express-session'); var bodyParser = require('body-parser'); var logger = require('morgan'); var errorHandler = require('errorhandler'); var csrf = require('lusca').csrf(); var methodOverride = require('method-override'); var _ = require('lodash'); var MongoStore = require('connect-mongo')({ session: session }); var flash = require('express-flash'); var path = require('path'); var mongoose = require('mongoose'); var passport = require('passport'); var expressValidator = require('express-validator'); var connectAssets = require('connect-assets'); var multer = require('multer'); var done=false; var express = require('express'); var nodemailer = require('nodemailer'); var json2csv = require('json2csv'); var fs = require('fs'); /** * Controllers (route handlers). */ var homeController = require('./controllers/home'); var userController = require('./controllers/user'); var reporterController = require('./controllers/reporter'); var importController = require('./controllers/import'); var blogController= require('./controllers/blog'); var stripController= require('./controllers/stripform.js'); /** * API keys and Passport configuration. */ var secrets = require('./config/secrets'); var passportConf = require('./config/passport'); /** * Create Express server. */ var app = express(); /** * Connect to MongoDB. */ mongoose.connect(secrets.db); mongoose.connection.on('error', function() { console.error('MongoDB Connection Error. Make sure MongoDB is running.'); }); var hour = 3600000; var day = hour * 24; var week = day * 7; /** * CSRF whitelist. */ var csrfExclude = ['/charge', '/salecharge','/upload','/strippost','/coupn','/deletereporters']; /** * Express configuration. */ app.set('port', process.env.PORT || 9600); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compress()); app.use(connectAssets({ paths: ['public/css', 'public/js'], helperContext: app.locals })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(expressValidator()); app.use(methodOverride()); app.use(cookieParser()); app.use(session({ secret: secrets.sessionSecret, store: new MongoStore({ url: secrets.db, auto_reconnect: true }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.use('/public/js', express.static(path.join(__dirname, '/public/js'))); app.use('/public/css', express.static(path.join(__dirname, '/public/css'))); app.use(function(req, res, next) { // CSRF protection. if (_.contains(csrfExclude, req.path)) return next(); csrf(req, res, next); }); app.use(function(req, res, next) { // Make user object available in templates. res.locals.user = req.user; next(); }); app.use(function(req, res, next) { // Remember original destination before login. var path = req.path.split('/')[1]; if (/auth|login|logout|signup|fonts|favicon/i.test(path)) { return next(); } req.session.returnTo = req.path; next(); }); app.use(express.static(path.join(__dirname, 'public'), { maxAge: week })); //file upload app.use(multer({ dest: './uploads/', rename: function (fieldname, filename) { return filename+Date.now(); }, onFileUploadStart: function (file) { console.log(file.originalname + ' is starting ...') }, onFileUploadComplete: function (file) { console.log(file.fieldname + ' uploaded to ' + file.path) done=true; } })); /** * Redirect www to non-www */ app.get('/*', function(req, res, next) { if (req.headers.host.match(/^www/) !== null && process.env.ENV === 'production') { res.redirect('https://' + req.headers.host.replace(/^www\./, '') + req.url); } else { next(); } }); /** * Force SSL */ app.all('*', function(req, res, next) { if (req.headers['x-forwarded-proto'] !== 'https' && process.env.ENV === 'production') res.redirect('https://press.farm' + req.url); else next(); }); /** * Main routes. */ app.get('/', homeController.index); app.get('/login', userController.getLogin); app.post('/login', userController.postLogin); app.get('/logout', userController.logout); app.get('/import', passportConf.isAuthenticated,importController.index); app.post('/deletereporters', importController.deletereporters); app.post('/upload', importController.importer); app.get('/forgot', userController.getForgot); app.post('/forgot', userController.postForgot); app.get('/reset/:token', userController.getReset); app.post('/reset/:token', userController.postReset); app.get('/signup', userController.getSignup); app.post('/signup', userController.postSignup); app.get('/account', passportConf.isAuthenticated, userController.getAccount); app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile); app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword); app.get('/reporters',passportConf.isAuthenticated, reporterController.getReporters); app.get('/reporters/new',passportConf.isAuthenticated, reporterController.newReporter); app.get('/reporters/csv', reporterController.Reportercsv); app.post('/reporters', passportConf.isAuthenticated, reporterController.createReporter); app.post('/charge', passportConf.isAuthenticated, homeController.charge); app.post('/salecharge', homeController.salecharge); app.get('/sale', homeController.sale); app.get('/blog', blogController.index); app.get('/blog/post/:id', blogController.single); app.get('/stripform', stripController.index); app.post('/coupn', homeController.coupn); //s //strip app.post("/strippost", function(req, res) { var stripeToken = req.body.stripeToken; var charge = stripe.charges.create({ amount: 900, currency: 'usd', card: stripeToken }, function(err, charge) { if (err && err.type === 'StripeCardError') { req.flash('error', { msg: 'There was a problem charging your card. :( No charge has been made.' }); console.log("failure"); } else { var user = req.user; user.datePaid = new Date().getTime(); user.save(); req.flash('success', { msg: 'Thanks! You now have full access for 30 days. :)' }); console.log("success"); } }); }); /*** * Trigger email export to mail chimp after every minutes */ var cron = require('cron'); var MCapi = require('mailchimp-api'); var User = require('./models/User'); var Reporters = require('./models/Reporter'); /*** * Blank array to store subscribers */ User.find(function(error, data){ var userSibscribers = [] if( !error && data ) { data.forEach(function(item) { userSibscribers.push({name:item.email, email: item.email}); }); //console.log("userSibscribers",userSibscribers); } }); var cronJob = cron.job("0 */30 * * * *", function(){ // perform operation e.g. GET request http.get() etc. console.info('cron job completed'); MC = new MCapi.Mailchimp('86fc09c02e572d77ab079a95c34a0c1f-us9'); Reporters.find({},function(err,reporters){ if (err) { console.log("error"); }else{ console.log(reporters); json2csv({data: reporters, fields: ['_id', 'name', 'email','publication','twitter','_v','url']}, function(err, csv) { if (err) console.log(err); fs.writeFile('csv/file2.csv', csv, function(err) { fs.chmodSync('csv/file2.csv', 0777); if (err) throw err; console.log('file saved'); var smtpTransport = nodemailer.createTransport('SMTP', { service: 'Mailgun', auth: { user: secrets.mailgun.user, pass: <PASSWORD> } }); console.log('mailsend'); var mailOptions = { to: '<EMAIL>', from: '<EMAIL>', subject: 'Pressfarm Attachment', text: 'Please find attachment csv file.', attachments : [{'filename': 'csv/file2.csv','contents':csv}] }; smtpTransport.sendMail(mailOptions, function(error, info){ if(error){ console.log(error); }else{ console.log('Message sent: ' + info.response); } }); }); }); } }); }); cronJob.start(); /** * 500 Error Handler. */ app.use(errorHandler()); /** * Start Express server. */ app.listen(app.get('port'), function() { console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env')); }); module.exports = app; <file_sep>$(document).ready(function() { var amount=900; var coupncode=["Banana", "Orange", "Apple", "Mango"]; // Stripe if ($('#pay').length) { Stripe.setPublishableKey('<KEY>'); var handler = StripeCheckout.configure({ key: '<KEY>', image: '../img/logo.png', token: function(token) { $('<form method="post" action="/charge" id="stripe"></form>').appendTo('body'); $('<input type="hidden" name="stripeToken" />').val(token.id).appendTo('#stripe'); $('#stripe').submit(); } }); document.getElementById('pay').addEventListener('click', function(e) { $("#stripePayment").html('<li><div class="coupon_accept btn btn-success" style="display:none"/></div><div style="display:none" class="errorcoupn alert alert-danger"></div><input type="text" id="counid" name="discount" placeholder="Add coupon" class="form-control"/></li><li><input role="button" type="submit" class="btn btn-default btn-primary buy reporter-button upcase" value="Apply Coupon" id="coupncode"/><input type="submit" name="payment" class="btn btn-default btn-primary buy reporter-button upcase" value="Buy" id="subscription"/></li>').promise().done(function(){ $(this).removeClass('hide'); $('html').off('click.dropdown.data-api'); $('html').on('click.dropdown.data-api', function(e) { if(!$(e.target).parents().is('.dropdown-menu form')) { $('.dropdown').removeClass('open'); } }); }); e.preventDefault(); }); $('#stripePayment').click(function(e) { $('#stripePayment').addClass('open'); }); $('.page-header').click(function(e) { $('#stripePayment').removeClass('open'); }); $(document).on("click", "#coupncode", function(e){ var coupnid=$('#counid').val(); if(coupnid==''){ $('.errorcoupn').show().html('Enter coupon'); $('.errorcoupn').delay(1000).hide(2000) }else{ if(coupncode.indexOf(coupnid)!='-1'){ $('.errorcoupn').show().html('Already use coupon'); $('.errorcoupn').delay(1000).hide(2000) }else{ $.ajax({ type: "POST", url: "/coupn", data: {id : coupnid}, success: function(response) { result = response; if(result.message){ $('.errorcoupn').show().html(result.message); $('.errorcoupn').delay(1000).hide(2000) }else{ console.log("result",result.percent_off); var discount= amount*result.percent_off/100; amount=amount-discount; $('.coupon_accept').show().html(' Successful Coupon Add '+coupnid); $('.coupon_accept').delay(1000).hide(2000) coupncode.push(coupnid); } } }); } } e.preventDefault(); }); $(document).on("click", "#subscription", function(e){ handler.open({ name: 'pressfarm', description: '30 day full access', amount: amount }); e.preventDefault(); }); $('.pay').on('click', function(e) { handler.open({ name: 'pressfarm', description: '30 day full access', amount: amount }); $('#stripePayment').removeClass('open'); e.preventDefault(); }); } // Stripe for pressfarm sale if ($('#sale').length) { Stripe.setPublishableKey('<KEY>'); var handler = StripeCheckout.configure({ key: '<KEY>', image: '../img/logo.png', token: function(token) { $('<form method="post" action="/salecharge" id="stripe"></form>').appendTo('body'); $('<input type="hidden" name="stripeToken" />').val(token.id).appendTo('#stripe'); $('#stripe').submit(); } }); document.getElementById('sale').addEventListener('click', function(e) { handler.open({ name: 'pressfarm', description: 'Buy pressfarm', amount: 400000 }); e.preventDefault(); }); } // BG Scrolling function parallax() { var scrolled = $(window).scrollTop(); $('.bg').css('height', (jumboHeight-scrolled) + 'px'); } if ($('.bg').length) { var jumboHeight = $('.bg').outerHeight(); $(window).scroll(function(e){ parallax(); }); } // GA (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-53243302-1', 'auto'); ga('send', 'pageview'); }); <file_sep>var crypto = require('crypto'); var mongoose = require('mongoose'); /*** * Add mailchimp collection to store mailchimp subscribers */ var smailchimpSchema = new mongoose.Schema({ name: { type: String, required: true }, email: { type: String, unique: true, lowercase: true, required: true }, mailinglist: { type: String, required: true }, }); module.exports = mongoose.model('smailchimp', smailchimpSchema);
8d00be54614e0d8c959358b4bdc120fbc8d3583f
[ "JavaScript" ]
10
JavaScript
dream121/pressfarm_node
ef78af210998ccab185b2c0b69213c8f90c726a3
5a6d07d3a503d80994b0cde93b44df6ba4e69d13
refs/heads/master
<file_sep># ContainerCat Pack your node project into Docker Container! ### Install ``` npm install -g containercat ``` ### Usage ``` containercat ```<file_sep>#!/usr/bin/env node const inquirer = require('inquirer') const fs = require('fs') let cwd = process.cwd() let dockerfile = null // Dockerfile content const questions = [ { type: 'input', name: 'nodeversion', message: 'Enter the Node version of a project. (eg. 8.12.0)'}, { type: 'input', name: 'main', message: 'Enter the name of main file or NPM script (eg. "index.js" or "start")'}, { type: 'input', name: 'ports', message: 'Please enter the port that need to be exposed. (eg. "8080")'} ] const getMain = (userinput) => { // check for JS if (userinput.slice( userinput.length-3 ) == ".js") { return "node " + userinput } else { return "npm run " + userinput } } inquirer .prompt(questions) .then( (answers) => { dockerfile = "FROM node:"+ answers.nodeversion +" \nWORKDIR /app \nCOPY package.json /app \nRUN npm install \nCOPY . /app \nCMD " + getMain(answers.main) + "\nEXPOSE " + answers.ports fs.writeFile(cwd + "/Dockerfile", dockerfile, (err) => { if (err) throw err; }) fs.writeFile(cwd + "/.dockerignore", "node modules \n .git" , (err) => { if (err) throw err; }) })
87f9287a587d3e91ab8f5e861905ffbc0a7101c6
[ "Markdown", "JavaScript" ]
2
Markdown
Vista1nik/containercat
22b8618591f14701652a69a9c57194b4ed8d9169
a840a02c13a547a5aaa853e8b077928aafb4be60
refs/heads/master
<file_sep>package water.ustc.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * Created by leegend on 2017/12/26. */ public class Server extends Thread { private ServerSocket serverSocket; public Server(int port) { try { serverSocket = new ServerSocket(port); // serverSocket.setSoTimeout(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { while (true) { try { //简易Server,除接受信息外,暂无其他逻辑。。。。。。 System.out.println("Waiting for Connector......"); System.out.println(serverSocket.getLocalSocketAddress()); Socket socket = serverSocket.accept(); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); String input = inputStream.readUTF(); System.out.println(input); DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); outputStream.writeUTF("true"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) { Thread thread = new Server(2012); thread.start(); } } <file_sep>软体实验,随便写写,基于自编Java框架。预计一个下午完工~~
ad36a165ec8a28ddefd5c67619ae16f0c07b3edf
[ "Markdown", "Java" ]
2
Java
leegendlee/SoftwareArchitectureExpe
bced475d6bd165d414e805e6be115dd79adcb46f
89756cd9b43cc6cd940cc38d4a041be11dd2e3fd
refs/heads/master
<file_sep>package br.com.br.projeto<file_sep>import React, { Component } from 'react' import user from './user' class teste extends Component { render () { return ( <div> react componente <user name="tiago"></user> </div> ); } } export default teste; <file_sep>package br.com.projetowilson.factory; import java.sql.Connection; import java.sql.DriverManager; public class ConnectionFactory { //nome do usuario do mysql private static final String USERNAME = "root"; // Senha do mysql private static final String PASSWORD = "<PASSWORD>"; //dados de caminho, porta e nome da base de dados que vai ser feito private static final String DATABASE_URL = "jdbc:mysql://localhost:3636" /** * Cria uma conexão com o banco de dados MySQL utilizando o nome de usuário e senha fornecidos * * @param username * @param senha * @return uma conexão com o banco de dados * @throws Exception */ public static Connection createConnectionToMySQL() throws Exception Class.forName("com.mysql.jdbc.Driver"); // classe que cria a conexão com baco de dados Connection connection = DriverManager.getConnection(DATABASE_URL) return connection; } public static void main(String[] args) throws Exception { //recuperação de conexão. Connection con = createConnectionToMySQL(); //teste de conexão if (con ! = null){ System.out.println("Conexão obtida com sucesso!" + con); con.close(); } } }
358eb62e60aa7a61eee3090f3339b7d3d3d96c83
[ "JavaScript", "Java" ]
3
Java
tiago955/sistema-de-provas
adc44c0de6f35cbc53fbed21546821a1bb95166f
f1ebbe7c42c8f8058975201f56b81b276b8a96e6
refs/heads/master
<repo_name>tbrands13/Video_Preview<file_sep>/script.js var x = document.getElementById("video"); function playVideo() { x.play() } function pauseVideo() { x.pause() }
45188935739fddecab9fab2dbc30a712b2983791
[ "JavaScript" ]
1
JavaScript
tbrands13/Video_Preview
ca8ac04f8fd15cb765745d82e05eb230bb2414c7
63bbfa469e84f9960ce043dc150c58b5e322792a
refs/heads/master
<repo_name>AlexanderShutalyov/go_slice<file_sep>/digital.go package main import ( "fmt" "os" "strconv" "strings" ) var inputString = "4539 1488 0343 6467" func getArray(inputString string) bool { var numSlice []int var numTestValue int count := 0 readyString := strings.Replace(inputString, " ", "", -1) if len(string(readyString))%2 != 0 { fmt.Println("error: Unexpected length of the string") os.Exit(1) } for i, v := range readyString { if i%2 != 0 { if serv, err := strconv.Atoi(string(v)); err == nil { if numTestValue = serv * 2; numTestValue > 9 { numTestValue = numTestValue - 9 } numSlice = append(numSlice, numTestValue) count += numTestValue } else { fmt.Println("error: Unexpected char in the string") os.Exit(1) } } } fmt.Println(count) if count%10 == 0 { return true } return false } func main() { fmt.Println(getArray(inputString)) } <file_sep>/digital_extra.go package main import ( "fmt" "os" "strconv" "strings" ) var inputStr = "4539 1488 0343 6467" func checkToSlice(inputStr string) []int { var numTestValue int var numSlice []int readyString := strings.Replace(inputStr, " ", "", -1) if len(readyString) < 2 && len(readyString)%2 != 0 { fmt.Println("error: Unexpected length of the string") os.Exit(1) } for i, v := range readyString { if i%2 != 0 { if serv, err := strconv.Atoi(string(v)); err == nil { if numTestValue = serv * 2; numTestValue > 9 { numTestValue = numTestValue - 9 } numSlice = append(numSlice, numTestValue) } else { fmt.Println("error: Unexpected char in the string") os.Exit(1) } } } return numSlice } func checkExtSlice(inputStr string) bool { var sum = 0 for _, v := range checkToSlice(inputStr) { sum += v } if sum%10 == 0 { return true } else { return false } } func main() { fmt.Println(checkExtSlice(inputStr)) } <file_sep>/sliceTest.go package main import ( "golang.org/x/tour/pic" ) func Pic(dx, dy int) [][]uint8 { exte := make([][]uint8, dy) for j,_ := range exte { inte := make([]uint8, dx) for i,_ := range inte { inte[i] = uint8(i*j) } exte[j] = inte } return exte } func main() { pic.Show(Pic) }<file_sep>/mutation.go package main import ( "fmt" "strings" ) var dnkFirst = "GAGCCTACTAACGGGAT" var dnkSecond = "CATCGTAATGACGGCCT" func checkstr() bool{ if len(dnkFirst) != len (dnkSecond) { return false } return true } func main() { count:=0 if checkstr() { for i, v := range dnkFirst { if strings.EqualFold(string(v), string(dnkSecond[i])) { count++ } } fmt.Println("Both DNK have", count, "common runes") } else { fmt.Println("error in the input strings") } }
5120ae3bb8e60df2e10c865a0788036c9a72069e
[ "Go" ]
4
Go
AlexanderShutalyov/go_slice
2c8da9e41001d4a11e6a092a766546655e2f9abb
ed3ed736bd6fecbfc557ded0953956b0420e3f9b
refs/heads/master
<repo_name>tlambert03/otfsearch<file_sep>/register.py from otfsearch import matlabReg, pickRegFile, goodChannel import config if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Apply channel registration to multi-channel file', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('inputFile', help='The file to process', type=file) parser.add_argument('-f','--regfile', help='Registration File', default=None, metavar='FILE') parser.add_argument('-c','--refchannel', help='reference channel for channel registration', default=config.refChannel, type=goodChannel, metavar='WAVE') parser.add_argument('-x','--domax', help='perform max projection after registration', type=bool, default=False, metavar='T/F') args = vars(parser.parse_args()) if not args['regfile']: pickRegFile(args['inputFile'],config.regFileDir,filestring=None) registeredFile, maxProj = matlabReg(args['inputFile'].name,args['regfile'],args['refchannel'],args['domax']) # THIS IS NOT JUST FOR READOUT # these lines trigger the gui.py program to download the files # that are printed... # the "updateStatusBar" in the "sendRemoteCommand" function looks for the # 'Files Ready:' string in the response. print "" print "Files Ready:" if registeredFile: print "Registered: %s" % registeredFile if maxProj: print "maxProj: %s" % maxProj # this is important for the updateStatusBar function in gui.py print "Done" <file_sep>/__init__.py import otfsearch import helpers import Mrc import config import makeotf<file_sep>/makeotf.py import Mrc import os import config import subprocess from otfsearch import callPriism def splitAngles(infile, outdir=None): """divid image into nAngles components""" header = Mrc.open(infile).hdr numWaves = header.NumWaves numTimes = header.NumTimes imSize = header.Num nz = imSize[2]/(numTimes*numWaves) for ang in range(1,config.nAngles+1): if outdir: #outfile = os.path.join(outdir,("_a%d" % ang).join(os.path.splitext(os.path.basename(infile)))) outfile = os.path.join(outdir,os.path.basename(infile).replace('visit_', "a%d_00" % ang)) else: #outfile = ("_a%d" % ang).join(os.path.splitext(infile)) outfile = infile.replace('visit_', "a%d_00" % ang) callPriism([ 'CopyRegion', infile, outfile, '-z=%d:%d' % ((ang-1)*nz/3,ang*nz/3 - 1) ]) def batchmakeotf(directory): # create temp folder for reconstructions angleDirs = [] anglesDir=None # seperate angles for root, subdirs, files in os.walk(directory): #print root for F in files: if F.endswith('.dv') and not any([x in F for x in ['a1','a2','a3']]): fullpath=os.path.join(root,F) anglesDir = os.path.join(root,'angles') try: os.makedirs(anglesDir) except: pass print "seperating angles: %s" % F splitAngles(fullpath,anglesDir) if anglesDir: angleDirs.append(anglesDir) anglesDir=None # batch make otf for angdir in list(set(angleDirs)): for F in os.listdir(angdir): if (('a1' in F) or ('a2' in F) or ('a3' in F)) and not ('.otf' in F): outfile = F.replace('dv','otf') maxint = Mrc.open(os.path.join(angdir,F)).hdr.mmm1[1] if maxint < config.otfSigRange[1] and maxint > config.otfSigRange[0]: print "processing %s with maxint = %d" % (os.path.join(angdir,F),maxint) makeotf(os.path.join(angdir,F),os.path.join(angdir,outfile)) else: print "skipping %s with maxint = %d" % (os.path.join(angdir,F),maxint) os.remove(os.path.join(angdir,F)) # visitnumber # outfile #makeotf(F) def searchparams(file, angle=1): import matplotlib.pyplot as plt import Mrc import numpy as np otfs =[] krange=range(1,4) narange=np.linspace(1.52,1.52,1) for k in krange: for NA in narange: otf = M.makeotf('/Users/talley/Desktop/528_testotf.dv', outfile='/Users/talley/Desktop/otfs/otfs528_testotf'+str(int(NA*100))+"_"+str(k)+".otf", na=NA, nimm=1.52, angle=angle, leavekz=(8,9,k) ) otfs.append(otf) fig = plt.figure() for i in range(len(otfs)): indat = Mrc.bindFile(otfs[i]) amplitude = np.sqrt(np.power(indat.imag,2)+np.power(indat.real,2))[:,] gamcor = (amplitude / 1000535.)**(1/2.5) ax = fig.add_subplot(len(krange), len(narange), i+1) ax.imshow(gamcor[2]) ax.autoscale(True) ax.set_title(str(i)) #axarr[i/len(krange), i%len(narange)].imshow(gamcor[1]) #axarr[i/len(krange), i%len(narange)].set_title('NA %s, k2 %s' %(narange[i%len(narange)], krange[i/len(krange)] )) plt.show() def makeotf(infile, outfile=None, nimm=1.515, na=1.42, beaddiam=0.11, angle=None, fixorigin=(3,20), background=None, leavekz='auto'): if outfile is None: #outfile=os.path.splitext(infile)[0]+'.otf' outfile = infile.replace('.dv','.otf') header = Mrc.open(infile).hdr wave = header.wave[0] if not angle: angle = int(infile.split('_a')[1][0]) try: fileoil = infile.split('_')[2] except: pass #pull out stuff like oil from otf name here spacings = config.spacings angles = config.angles if leavekz == 'auto': leaveKZs = { 435 : [6, 7, 2], 528 : [7, 9, 2], 608 : [8, 10, 2], 683 : [8, 11, 2] } leavekz = leaveKZs[wave] callPriism() com = [config.makeOTFapp, infile, outfile, '-angle', str(angles[wave][angle-1]), '-ls', str(spacings[wave])] com.extend(['-na', str(na), '-nimm', str(nimm), '-beaddiam', str(beaddiam)]) com.extend(['-fixorigin', str(fixorigin[0]), str(fixorigin[1])]) if leavekz: com.append('-leavekz') com.extend([str(n) for n in leavekz]) if background: com.extend(['-background', str(background)]) #print " ".join(com) subprocess.call(com) return outfile if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Apply channel registration to multi-channel file', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('inputFile', help='The file to process') parser.add_argument('-o','--outputFile', help='Optional name of output file to process', default=None, metavar='FILE') parser.add_argument('-a','--angle', help='Angle of illumination', default=None, type=int) parser.add_argument('-i','--nimm', help='Refractive index of imersion oil', default=1.515, type=float) parser.add_argument('-n','--na', help='Numerical Aperture', default=1.42, type=float) parser.add_argument('-d','--beaddiam', help='Bead Diameter', type=float, default=0.11) parser.add_argument('-b','--background', help='background to subtract', type=int, default=None) parser.add_argument('-f','--fixorigin', help='the starting and end pixel for interpolation along kr axis', nargs="*", type=int, metavar='', default=None) parser.add_argument('-l','--leavekz', help='the pixels to be retained on kz axis', nargs=3, type=int, metavar=('kz1_1','kz1_2','kz2'), default=None) args = vars(parser.parse_args()) if args['leavekz']: lkz=args['leavekz'] else: lkz='auto' if args['fixorigin']: fo=args['fixorigin'] else: fo=(3,20) if os.path.isdir(args['inputFile']) : batchmakeotf(args['inputFile']) else: makeotf(args['inputFile'], outfile=args['outputFile'], nimm=args['nimm'], na=args['na'], beaddiam=args['beaddiam'], angle=args['angle'], background=args['background'], fixorigin=fo, leavekz=lkz) <file_sep>/optimalRecon.py import argparse import config from otfsearch import makeBestReconstruction, goodChannel, cropCheck def otfAssignment(string): if "=" in string and len(string.split('='))==2: k,v = string.split('=') if goodChannel(k) and goodChannel(v): return [k,v] msg = "OTF force %r is not of the form CHANNEL=OTF (each in wavelengths)" % string raise argparse.ArgumentTypeError(msg) if __name__ == '__main__': parser = argparse.ArgumentParser(description='OTF matching program', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('inputFile', help='The file to process', type=file) parser.add_argument('-a','--age', help='max age of OTF file in days', default=None, type=int) parser.add_argument('-n','--num', help='max number of OTF files used', default=config.maxNum, type=int) parser.add_argument('-l','--oilmin', help='min oil refractive index to search', default=config.oilMin, type=int, choices=config.valid['oilMin'], metavar='1510-1530') parser.add_argument('-m','--oilmax', help='max oil refractive index to search', default=config.oilMax, type=int, choices=config.valid['oilMax'], metavar='1510-1530') parser.add_argument('-w','--wiener', help='Wiener constant', default=None, type=float) parser.add_argument('-f', '--force', help='Force OTF wave for specific channel in form: <CHAN>=<OTF>', metavar='<CHAN>=<OTF>', nargs=1, action='append',type=otfAssignment, default=[]) #parser.add_argument('-t','--time', help='number of timepoints to use', default=config.maxNum) parser.add_argument('-p','--crop', help='ROI crop size to use for testing', default=config.cropsize, type=cropCheck) parser.add_argument('-c','--channels', help='channels to process (sep by spaces)', default=None, nargs="*", type=goodChannel, metavar='CHAN') #parser.add_argument('-f','--forceotf', help='force wavelength to use specified OTF wavelength. provided as space-seperated list of comma-seperated pairs: e.g. 528,528', nargs="*") parser.add_argument('--otfdir', help='OTF directory', default=config.OTFdir, metavar='') parser.add_argument('--regfile', help='Registration File', default=None, metavar='') parser.add_argument('--regdir', help='Directory with Reg Files', default=config.regFileDir, metavar='') parser.add_argument('-r','--refchannel', help='reference channel for channel registration', default=config.refChannel, type=goodChannel) parser.add_argument('-x','--domax', help='perform max projection after registration', type=bool, default=config.doMax) parser.add_argument('-g','--doreg', help='perform channel registration', default=config.doReg) parser.add_argument('-s','--writefile', help='write score results to csv file', default=config.writeCSV, action='store_true') parser.add_argument('-q','--quiet', help='suppress feedback during reconstructions', default=False, action='store_true') parser.add_argument('--optout', help='dont store scores in master CSV file', default=True, action='store_false') parser.add_argument('--version', action='version', version='%(prog)s 0.1') args = vars(parser.parse_args()) forceOTFdict = {} for item in args['force']: forceOTFdict[int(item[0][0])]=int(item[0][1]) bestOTFs, reconstructed, logFile, registeredFile, maxProj, scoreFile = makeBestReconstruction(args['inputFile'].name, wiener=args['wiener'], cropsize=args['crop'], oilMin=args['oilmin'], oilMax=args['oilmax'], maxAge=args['age'], maxNum=args['num'], OTFdir=args['otfdir'], reconWaves=args['channels'], forceChannels=forceOTFdict, regFile=args['regfile'], regdir=args['regdir'], refChannel=args['refchannel'], doMax=int(args['domax']), doReg=int(args['doreg']), writeCSV=args['writefile'], appendtomaster=args['optout'], cleanup=True, verbose=True,) # THIS IS NOT JUST FOR READOUT # these lines trigger the gui.py program set the specific OTF window # with the OTFS if bestOTFs: print "" print "Best OTFs:" print bestOTFs # THIS IS NOT JUST FOR READOUT # these lines trigger the gui.py program to download the files # that are printed... # the "updateStatusBar" in the "sendRemoteCommand" function looks for the # 'Files Ready:' string in the response. print "" print "Files Ready:" if reconstructed: print "FILE READY - Reconstruction: %s" % reconstructed if logFile: print "FILE READY - LogFile: %s" % logFile if registeredFile: print "FILE READY - Registered: %s" % registeredFile if maxProj: print "FILE READY - maxProj: %s" % maxProj if scoreFile: print "FILE READY - ScoreCSV: %s" % scoreFile # this is important for the updateStatusBar function in gui.py print "Done" <file_sep>/calculateMatlabTform.py from otfsearch import goodChannel import config import subprocess def calcMatlabTform(inputFile,outpath=None, refChannels=None, iterations=None, dims=None, bestplane=None, TformType=None, interpType=None): matlabString = "%s('%s'" % (config.MatlabTformCalc,inputFile) if outpath: matlabString += ",'outpath','%s'" % outpath if refChannels : matlabString += ",'referenceChannels', %s " % str(refChannels) if iterations : matlabString += ",'iterations', %d " % iterations if dims : matlabString += ",'dims', %d " % dims if bestplane : matlabString += ",'bestplane', '%s' " % bestplane if TformType : matlabString += ",'type', '%s' " % TformType if interpType : matlabString += ",'interp', '%s' " % interpType matlabString += "); exit;" print matlabString subprocess.call(['matlab', '-nosplash', '-nodesktop', '-nodisplay', '-r', matlabString]) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser(description='Calcultate transformation matrices for Matlab image registration', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('inputFile', help='The file to process', type=file) parser.add_argument('-o','--outpath', help='Destination directory for the registration file', default=None, type=str) parser.add_argument('-r','--refs', help='calculate matrices for only these reference channels', default=None, nargs="*", type=goodChannel, metavar='WAVE') parser.add_argument('-n','--iter', help='Number of iterations', default=None, type=int) parser.add_argument('-d','--dims', help='measure 2D+1 or 3D transformations', default=None, choices=[2,3]) parser.add_argument('-p','--plane', help='Method to pick plane for 2D Tform calculation', default=None, choices=['focus','max']) parser.add_argument('-t','--type', help='Transformation type', default=None, choices=['translation','rigid','similarity','affine']) parser.add_argument('-i','--interp', help='Interpolation type', default=None, choices=['linear','nearest','cubic','bicubic']) args = vars(parser.parse_args()) calcMatlabTform(args['inputFile'].name,outpath=args['outpath'], refChannels=args['refs'], iterations=args['iter'], dims=args['dims'], bestplane=args['plane'], TformType=args['type'], interpType=args['interp'])<file_sep>/config.py """Configuration File.""" # CONNECTION TO REMOTE SERVER # this program assumes the use of private keys for authentication # https://help.github.com/articles/generating-an-ssh-key/ server = 'cbmf-latwork' username = 'cbmf' priismpath = '/usr/local/priism' masterScoreCSV = '/ssd/data0/SIMrecon/scores_master.csv' # DIRECTORIES ON THE RECONSTRUCTION SERVER # temp folder where files will get uploaded to remotepath = '/ssd/data0/remote/' # script to trigger optimized reconstruction remoteOptScript = '/ssd/data0/SIMrecon/otfsearch/optimalRecon.py' # script to trigger single recon with specific OTFs remoteSpecificScript = '/ssd/data0/SIMrecon/otfsearch/singleRecon.py' # script to trigger single registration with specific OTFs remoteRegScript = '/ssd/data0/SIMrecon/otfsearch/register.py' # script to trigger channel registration calibration remoteRegCalibration = '/ssd/data0/SIMrecon/otfsearch/calculateMatlabTform.py' # directory with all the OTFs OTFdir = '/ssd/data0/SIMrecon/OTFs' # directory with default OTFs # (this could probably be eliminated in favor of filename conventions) defaultOTFdir = '/ssd/data0/SIMrecon/OTFs/defaultOTFs' # string that determines formatting of the OTF filename OTFtemplate = 'wavelength_date_oil_medium_angle_beadnum' # delimiter for parsing OTFtemplate OTFdelim = '_' # extension of otf files OTFextension = '.otf' # app to generate OTF makeOTFapp = '/Users/talley/Dropbox/Documents/Python/otfsearch/makeotf' # directory with config files for CUDA-SIMrecon reconstruction SIconfigDir = '/ssd/data0/SIMrecon/SIconfig' # path to CUDA-SIMrecon reconstruction app reconApp = '/usr/local/bin/sir' # otfSigRange=[16000,31500] # OPTMIIZED RECONSTRUCTION PARAMETERS # all files will be cropped to this size before reconstruction cropsize = 256 # max age (in days) of OTFs to use in search process maxAge = None # max number of OTFs to use in search process maxNum = None # minimum OTF oil RI to use in search oilMin = 1512 # maximum OTF oil RI to use in seach oilMax = 1520 # whether to save the CSV file after scoring all the OTFS writeCSV = True wiener = 0.001 background = 90 # REGISTRATION AND POST-RECONSTRUCTION PROCESSING # perform channel registration by default doReg = False # perform max projection by default doMax = False # perform pseudo WF by default doWF = False # name of matlab registration function (must be on MATLAB path) MatlabRegScript = 'omxreg' # default reference channel for registration refChannel = 528 # default matlab regisration file to use regFile = '/ssd/data0/regfiles/OMXreg_160616_waves435-528-608-683_grid.mat' # directory containing registration files (and where they will be saved to by default) regFileDir = '/ssd/data0/regfiles/' # name of matlab registration calibration function (must be on MATLAB path) MatlabTformCalc = 'omxregcal' # default number of iterations for calibration for GUI CalibrationIter = 2000 # VALIDATION DICTIONARY # these are valid choices for the respective settings valid = { 'waves': [435, 477, 528, 541, 608, 683], 'cropsize': [36, 64, 128, 256, 512, 1024], 'oilMin': range(1510, 1530), 'oilMax': range(1510, 1530) } spacings = { 435 : 0.1920, 528 : 0.2035, 608 : 0.2075, 683 : 0.2200, 477 : 0.2290, 541 : 0.2400, } nAngles=3 nPhases=5 angles = { 435 : [-0.831000,-1.884600,0.213000], 528 : [-0.804300,-1.855500,0.238800], 608 : [-0.775600,-1.826500,0.270100], 683 : [-0.768500,-1.823400,0.276100], 477 : [-0.803400,-1.856900,0.238900], 541 : [-0.798300,-1.849100,0.244700] } em2ex = { 435 : 405, 477 : 445, 528 : 488, 541 : 514, 608 : 568, 683 : 642 }<file_sep>/CUDAsirecon.py import os import subprocess def cudaSIrecon(inputFile, otfFile, outputFile=None, app='/usr/local/bin/sir', **kwargs): ''' python interface for Lin's CUDAsirecon command line app ''' if not outputFile: namesplit = os.path.splitext(inputFile) outputFile = namesplit[0]+"_PROC"+namesplit[1] commandArray=[app,inputFile,outputFile,otfFile] for k,v in kwargs.items(): if isinstance(v,bool): commandArray.extend(["--%s" % k, str(int(v))]) elif v: print commandArray.extend(["--%s" % k, str(v)]) #print " ".join(commandArray) try: process = subprocess.Popen(commandArray, stdout=subprocess.PIPE) output = process.communicate()[0] return output except OSError as e: print "error calling CUDA_SIMrecon: %s" % e print "App may not be located at: %s " % app return 0 if __name__=="__main__": import argparse parser = argparse.ArgumentParser(description='Single SIM file reconstruction', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('input-file', help='input file (or data folder in TIFF mode)', type=file) parser.add_argument('otf-file', help='OTF file', type=file) parser.add_argument('--output-file', help='output file (or filename pattern in TIFF mode)', default=None) parser.add_argument('-w','--wiener', help='Wiener constant', type=float) parser.add_argument('-b','--background', help='number of output orders; must be <= norders', type=int) parser.add_argument('--usecorr', help='use the flat-field correction file provided', type=file) parser.add_argument('-c','--config', help='name of a file of a configuration.', type=file) # CCD correction file is a .dv file with two 2D floating-point images. # The x-y dimension of the images has to match the SIM raw data you are # processing. The first contains the dark-field image of the camera, # usually obtained by averaging hundreds or thousands of camera exposures # with no light. The second is sort of what you call the per-pixel gain # image, except that it needs to be the inverse of that gain. You first # obtain the gains for each pixel by whatever means, then divide all gains # by the median of all gains, and finally take the inversion of the # normalized gains. This image should have value distributed around 1.0. parser.add_argument('--ndirs', help='number of directions', type=int) parser.add_argument('--nphases', help='number of phases per direction', type=int) parser.add_argument('--nordersout', help='number of output orders; must be <= norders', type=int) parser.add_argument('--angle0', help='angle of the first direction in radians', type=float) parser.add_argument('--ls', help='number of phases per direction', type=float) parser.add_argument('--na', help='Detection numerical aperture', type=float) parser.add_argument('--nimm', help='refractive index of immersion medium', type=float) parser.add_argument('--zoomfact', help='lateral zoom factor', type=float) parser.add_argument('--zzoom', help='axial zoom factor', type=float) parser.add_argument('--explodefact', help='artificially exploding the reciprocal-space distance between orders by this factor', type=float) parser.add_argument('--nofilteroverlaps', help='do not filter the overlaping region between bands (usually used in trouble shooting)', type=bool) parser.add_argument('--forcemodamp', help='modamps forced to these values') parser.add_argument('--k0angles', help='user given pattern vector k0 angles for all directions') parser.add_argument('--otfRA', help='using rotationally averaged OTF', type=bool) parser.add_argument('--fastSI', help='SIM data is organized in Z->Angle->Phase order, default being Angle->Z->Phase', type=bool) parser.add_argument('--k0searchAll', help='search for k0 at all time points', type=bool) parser.add_argument('--equalizez', help='bleach correcting for z', type=bool) parser.add_argument('--equalizet', help='bleach correcting for time', type=bool) parser.add_argument('-d','--dampenOrder0', help='dampen order-0 in final assembly', type=bool) # It sort of apply a high pass filter (an inverted Gaussian centering around the origin) # to the order 0 component (i.e., what conventional wide-field microscope would get normally) # to suppress the all low-resolution information, not just the singularity at the origin # as what suppress_singularities does. The "haloing" stuff comes mostly from incorrect # enhancing or subduing of the low-resolution stuff, so it makes sense you see less of # that after dampenOrder0 is applied. parser.add_argument('--nosuppress', help='do not suppress DC singularity in final assembly (good idea for 2D/TIRF data)', type=bool) parser.add_argument('--nokz0', help='do not use kz=0 plane of the 0th order in the final assembly', type=bool) parser.add_argument('--gammaApo', help='output apodization gamma; 1.0 means triangular apo', type=bool) parser.add_argument('--saveprefiltered', help='save separated bands (half Fourier space) into a file and exit', type=bool) parser.add_argument('--savealignedraw', help='save drift-fixed raw data (half Fourier space) into a file and exit', type=bool) parser.add_argument('--saveoverlaps', help='save overlap0 and overlap1 (real-space complex data) into a file and exit', type=bool) parser.add_argument('--2lenses', help='I5S data', type=bool) args = vars(parser.parse_args()) inputFile = args.pop('input-file').name otfFile = args.pop('otf-file').name if 'output_file' in args: outputFile = args.pop('output_file') else: outputFile = None cudaSIrecon(inputFile,otfFile,outputFile,**args) <file_sep>/singleRecon.py import sys import os import argparse import config from otfsearch import reconstructMulti, goodChannel, croptime, isRawSIMfile, query_yes_no, matlabReg, pickRegFile, maxprj import Mrc def otfAssignment(string): if "=" in string and len(string.split('='))==2: k,v = string.split('=') if goodChannel(k): if not v.endswith('.otf'): msg = "%r is not an OTF file ending in '.otf'" % v raise argparse.ArgumentTypeError(msg) else: return {k:v} msg = "OTF assignment %r is not of the form <WAVE>=<FILE>" % string raise argparse.ArgumentTypeError(msg) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Single SIM file reconstruction', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('inputFile', help='The file to process', type=file) parser.add_argument('--outputFile', help='Optional name of output file to process', default=None, metavar='FILE') parser.add_argument('-o', '--otf', help='OTF assignment in the form: <WAVE>=<FILE>', metavar='<WAVE>=<FILE>', nargs=1, action='append',type=otfAssignment, default=[]) parser.add_argument('-c','--channels', help='channels to process (sep by spaces)', default=None, nargs="*", type=goodChannel, metavar='WAVE') parser.add_argument('--configDir', help='Director with config files', default=config.SIconfigDir, metavar='DIR') parser.add_argument('-b','--background', help='Background to subtract', default=None, type=int) parser.add_argument('-w','--wiener', help='Wiener constant', default=None, type=float) parser.add_argument('-t','--time', help='Cut to first N timepoints', default=None, type=int) parser.add_argument('--regfile', help='Registration File', default=None, metavar='FILE') parser.add_argument('--regdir', help='Directory with Reg files', default=config.regFile, metavar='FILE') parser.add_argument('-r','--refchannel', help='reference channel for channel registration', default=config.refChannel, type=goodChannel) parser.add_argument('-x','--domax', help='perform max projection after registration', default=False, action='store_true') parser.add_argument('-g','--doreg', help='perform channel registration', default=False, action='store_true') parser.add_argument('-q','--quiet', help='suppress feedback during reconstructions', default=False, action='store_true') parser.add_argument('--version', action='version', version='%(prog)s 0.1') args = vars(parser.parse_args()) # build OTF dict from input, prepending OTFdir from config file otfDict = {} for item in args['otf']: otfDict.update(item[0]) for k,v, in otfDict.items(): otfDict[k]=os.path.join(config.OTFdir,v) # get parameters of input file fname = args['inputFile'].name header = Mrc.open(fname).hdr numWaves = header.NumWaves waves = [i for i in header.wave if i != 0] numTimes = header.NumTimes # check whether input file is a valid raw SIM file if not isRawSIMfile(fname): if not query_yes_no("File doesn't appear to be a raw SIM file... continue?"): sys.exit("Quitting...") # crop to the first N timepoints if requested and appropriate if args['time'] and args['time']>0 and numTimes > 1: inputFile = croptime(fname, end=args['time']) timecropped = 1 else: inputFile = fname timecropped = 0 # validate the channel list that the user provided if args['channels']: for c in args['channels']: if c not in waves: print "Channel %d requested, but not in file... skipping" % c reconWaves=sorted([c for c in args['channels'] if c in waves]) else: reconWaves=None # perform reconstruction reconstructed,logFile = reconstructMulti(inputFile, OTFdict=otfDict, reconWaves=reconWaves, wiener=args['wiener'], background=args['background'], outFile=args['outputFile'], configDir=args['configDir']) registeredFile=None maxProj=None # TODO: add check for len(reconwaves>1) here as well if args['doreg'] and numWaves>1: # perform channel registration #print "perfoming channel registration in matlab..." regFile = args['regfile'] if not regFile: regFile = pickRegFile(fname,args['regdir']) registeredFile, maxProj = matlabReg(reconstructed,regFile, args['refchannel'],args['domax']) # will be a list elif args['domax']: maxProj = maxprj(reconstructed) # cleanup the file that was made if timecropped: os.remove(inputFile) # THIS IS NOT JUST FOR READOUT # these lines trigger the gui.py program to download the files # that are printed... # the "updateStatusBar" in the "sendRemoteCommand" function looks for the # 'Files Ready:' string in the response. print "" print "Files Ready:" if reconstructed: print "FILE READY - Reconstruction: %s" % reconstructed if logFile: print "FILE READY - LogFile: %s" % logFile if registeredFile: print "FILE READY - Registered: %s" % registeredFile if maxProj: print "FILE READY - maxProj: %s" % maxProj # this is important for the updateStatusBar function in gui.py print "Done"<file_sep>/readme.md installation requirements: anaconda CUDA_SIMrecon install priism add priism to bashrc install matlab git matlab repo #example usage import Mrc import numpy as np import matplotlib.pyplot as plt indat=Mrc.bindFile('/Users/talley/Dropbox/OMX/data/SIRreconTEST/testA_1516_PROC.dv') xPixelSize=indat.Mrc.hdr.d[0] imwidth = indat.shape[-1] spacing=0.414635 # from the log file angle = -0.80385 # the angle in radians of the illumination coords = getIllumCoords(xPixelSize, imwidth, spacing, angle) bp = indat[bestplane(indat)] F,amp = getFFT(bp, shifted=True, log=True) Fstack,ampstack = getFFT(indat, shifted=True, log=True) #line = linecut(amp,p1=coords[0],p2=coords[1], width=3, show=True) [x,y]=[int(i) for i in coords[0]] cropsize=70 cropped=amp[x-cropsize:x+cropsize,y-cropsize:y+cropsize] showPlane(cropped) m = croparound(ampstack[19],coords[1],15) from scipy.ndimage import gaussian_filter sigma = 5 # I have no idea what a reasonable value is here smoothed = gaussian_filter(croparound(ampstack[18],coords[1],100), sigma) plt.imshow(smoothed) plt.show()<file_sep>/guilocal.py #!/usr/bin/env python2.7 """Tkinter-based GUI for OTF-searching workflow.""" import Tkinter as Tk import tkFileDialog import tkMessageBox from ScrolledText import ScrolledText from ttk import Notebook, Style import sys import config as C import os from otfsearch import isRawSIMfile, isAlreadyProcessed, isaReconstruction, pseudoWF import threading from functools import partial from ast import literal_eval try: import Mrc except ImportError as e: print 'This program requires the Mrc.py class file for reading .dv files' sys.exit() ############################# ### FUNCTIONS ### ############################# def send_command(remotefile, mode): """Send one of the commands above to the server.""" Server['busy'] = True Server['status'] = 'processing' if mode == 'registerCal': command = ['python', C.remoteRegCalibration, remotefile, '--outpath', C.regFileDir] if calibrationIterations.get(): command.extend(['--iter', calibrationIterations.get()]) if RegCalRef.get() != 'all': command.extend(['--refs', RegCalRef.get()]) elif mode == 'register': command = ['python', C.remoteRegScript, remotefile, '-c', RefChannel.get()] if RegFile.get().strip(): command.extend(['--regfile', RegFile.get()]) elif mode == 'single': command = ['python', C.remoteSpecificScript, remotefile] if RegFile.get().strip(): command.extend(['--regfile', RegFile.get(), '-r', RefChannel.get()]) if wienerspec.get().strip(): command.extend(['-w', wienerspec.get()]) if background.get().strip(): command.extend(['-b', background.get()]) if timepoints.get().strip(): command.extend(['-t', timepoints.get()]) selected_channels = [key for key, val in channelSelectVars.items() if val.get() == 1] command.extend(['-c', " ".join([str(n) for n in sorted(selected_channels)])]) for c in selected_channels: command.extend(['-o', "=".join([str(c), channelOTFPaths[c].get()])]) if doMax.get(): command.append('-x') if doReg.get(): command.append('-g') elif mode == 'optimal': command = ['python', C.remoteOptScript, remotefile, '-l', OilMin.get(), '-m', OilMax.get(), '-p', cropsize.get(), '--otfdir', OTFdir.get(), '-x', doMax.get(), '-g', doReg.get()] if RegFile.get().strip(): command.extend(['--regfile', RegFile.get(), '-r', RefChannel.get()]) if maxOTFage.get().strip(): command.extend(['-a', maxOTFage.get()]) if maxOTFnum.get().strip(): command.extend(['-n', maxOTFnum.get()]) if wieneropt.get().strip(): command.extend(['-w', wieneropt.get()]) selected_channels = [key for key, val in channelSelectVars.items() if val.get() == 1] if selected_channels: command.extend(['-c', " ".join([str(n) for n in sorted(selected_channels)])]) # if not all([k==v.get() for k,v in forceChannels.items() if k in selected_channels]): # if any of the channel:otf pairings have been changed for c in selected_channels: # build the "force channels" commands if not c == forceChannels[c].get(): command.extend(['-f', "=".join([str(c), str(forceChannels[c].get())])]) if optOut.get(): command.append('--optout') else: raise ValueError('Uknown command mode: %s' % mode) statusTxt.set("Starting command...") # send the command to the server print " ".join([str(s) for s in command]) + '\n' junkresponses = ['[?1h=','[?1h=','[?1l>','[?1l>', 'To get started, type one of these: helpwin, helpdesk, or demo.', 'For product information, visit www.mathworks.com.', ' Academic License','Priism 4.4.0 set up; type Priism to run it', ' * Documentation: https://help.ubuntu.com/', ' Copyright 1984-2016 The MathWorks, Inc.'] def receive_command_response(ssh): if Server['status'] == 'canceled': statusTxt.set("Process canceled...") return 0 elif Server['status'] == 'processing': if channel.recv_ready(): # if there's something waiting in the queue, read it response = channel.recv(2048) if response != '': statusTxt.set("Receiving feedback from server ... see text area above for details.") r = [r for r in response.splitlines() if r and r != ''] #r = filter(lambda a: a not in junkresponses, r) for i in r: if i not in junkresponses: if 'WARNING' in i: pass else: textArea.insert(Tk.END, i + "\n") #textArea.insert(Tk.END, "\n") textArea.yview(Tk.END) if 'Best OTFs:' in r: otfdict = r[r.index('Best OTFs:') + 1] if not isinstance(otfdict, dict): otfdict = literal_eval(otfdict) if isinstance(otfdict, dict): for k, v in otfdict.items(): channelOTFPaths[int(k)].set(v) print "Best OTF for %s: %s" %(k,v) statusTxt.set("Best OTFs added to 'Specific OTFs' tab") # this will not work if the server doesn't send all of the text in a single receive # increasing loop time might help... but doesn't fix the fundamental problem if 'Files Ready:' in r: i = r.index('Files Ready:') + 1 filelist = [] while not r[i].startswith('Done'): filelist.append(r[i].split(": ")[1]) i += 1 if len(filelist): download(filelist) # this is where this loop ends... return if response.endswith(':~$ '): if 'OTFs' not in statusTxt.get(): statusTxt.set("Server finished command.") elif response.endswith("File doesn't appear to be a raw SIM file... continue?"): statusTxt.set("Remote server didn't recognize file as raw SIM file and quit") else: # response was empty... root.after(500, receive_command_response, ssh) else: # if there's nothing ready to receive, wait another while root.after(500, receive_command_response, ssh) else: print('Unexpected server status: %s' % Server['status']) #raise ValueError('Unexpected server status: %s' % Server['status']) #root.after(500, receive_command_response) def activateWaves(waves): for w in waves: channelSelectBoxes[w].config(state='normal') channelSelectVars[w].set(1) def deactivateWaves(waves): for w in waves: channelSelectVars[w].set(0) channelSelectBoxes[w].config(state='disabled') def getRawFile(): filename = tkFileDialog.askopenfilename(filetypes=[('DeltaVision Files', '.dv'), ('MRC Files', '.mrc')], initialdir=lastdir) setRawFile(filename) def setRawFile(filename): global lastdir lastdir=os.path.dirname(filename) # so that the filechoice opens in the same place next time if filename: rawFilePath.set( filename ) try: header = Mrc.open(filename).hdr waves = [i for i in header.wave if i != 0] deactivateWaves(allwaves) activateWaves(waves) statusTxt.set('Valid .dv file') except ValueError: statusTxt.set('Unable to read file... is it a .dv file?') def entriesValid(silent=False, mode=None): errors=[] if maxOTFnum.get(): if not maxOTFnum.get().isdigit(): errors.append(["Optimized Reconstruction Input Error","Max number of OTFs must be a positive integer (or blank)"]) if maxOTFage.get(): if not maxOTFage.get().isdigit(): errors.append(["Optimized Reconstruction Input Error","Max OTF age must be a positive integer (or blank)"]) if not OilMin.get().isdigit() or not int(OilMin.get()) in C.valid['oilMin']: errors.append(["Optimized Reconstruction Input Error","Oil min must be an integer between 1510 and 1530"]) if not OilMax.get().isdigit() or not int(OilMax.get()) in C.valid['oilMax']: errors.append(["Optimized Reconstruction Input Error","Oil max must be an integer between 1510 and 1530"]) if not cropsize.get().isdigit() or not int(cropsize.get()) in C.valid['cropsize']: errors.append(["Optimized Reconstruction Input Error","Cropsize must be a power of 2 <= 512"]) if wienerspec.get().strip(): if float(wienerspec.get())>0.2 or float(wienerspec.get()) < 0: errors.append(["Wiener Constant Error","Wiener constant (Specified OTF tab) must be between 0-0.2"]) if wieneropt.get().strip(): if float(wieneropt.get())>0.2 or float(wieneropt.get()) < 0: errors.append(["Wiener Constant Error","Wiener constant (Optimized tab) must be between 0-0.2"]) if doReg.get() or mode=='register': waves = [i for i in Mrc.open(rawFilePath.get()).hdr.wave if i != 0] if not int(RefChannel.get()) in waves: errors.append(["Registration Settings Error","Reference channel not in input file. Must be one of the following:" + " ".join([str(w) for w in waves])]) if not RegFile.get().strip(): errors.append(["Registration File Error","Please select a registration file in the registration tab"]) else: try: regwaves = os.path.basename(RegFile.get()).split('waves')[1].split('_')[0].split('-') # could potentially try to read the matlab file directly with something like: # import scipy.io # mat = scipy.io.loadmat(RegFile.get()) # regwaves = mat.get('R')[0][0][6][0][0][0][0] if not str(RefChannel.get()) in regwaves: errors.append(["Registration File Error","The selected reference channel (%s) does not exist in the registration file (%s). Please either change the registration file or the reference channel" % (RefChannel.get(),", ".join(regwaves))]) except: errors.append(["Registration File Error","Cannot parse registration file name... for now, the filename must include 'waves_'... etc"]) selectedchannels = [key for key, val in channelSelectVars.items() if val.get() == 1] if len(selectedchannels) == 0 and not mode=='register': errors.append(["Input Error","You must select at least one channel to reconstruct:"]) if len(errors): if not silent: [tkMessageBox.showinfo(*error) for error in errors] return 0,errors else: return 1,errors def getOTFdir(): filename = tkFileDialog.askdirectory() if filename: OTFdir.set(filename) def getSIRconfigDir(): filename = tkFileDialog.askdirectory() if filename: SIRconfigDir.set(filename) def getbatchDir(): filename = tkFileDialog.askdirectory() if filename: batchDir.set(filename) def getregCalImage(): filename = tkFileDialog.askopenfilename(filetypes=[('DV file', '.dv')]) if filename: regCalImage.set(filename ) def getRegFile(): reglist = sorted([item for item in os.listdir(C.regFileDir) if item.endswith('.mat')]) top = Tk.Toplevel() top.title('Choose registration file') scrollbar = Tk.Scrollbar(top) scrollbar.grid(row=0, column=3, sticky='ns') lb = Tk.Listbox(top, yscrollcommand=scrollbar.set, height=18, width=45) for item in reglist: lb.insert(Tk.END, os.path.basename(item)) lb.grid(row=0, column=0, columnspan=3) scrollbar.config(command=lb.yview) def Select(): items = lb.curselection() item = [reglist[int(item)] for item in items][0] if item: RegFile.set(os.path.join(C.regFileDir, item)) top.destroy() selectButton = Tk.Button(top, text="Select", command=Select, pady=6, padx=10) selectButton.grid(row=1, column=0) cancelButton = Tk.Button(top, text="Cancel", command=lambda: top.destroy(), pady=6, padx=10) cancelButton.grid(row=1, column=1) top.update_idletasks() w = top.winfo_screenwidth() h = top.winfo_screenheight() size = tuple(int(_) for _ in top.geometry().split('+')[0].split('x')) x = w / 2 - size[0] / 2 y = h / 2 - size[1] / 1.3 top.geometry("%dx%d+%d+%d" % (size + (x, y))) top.resizable(0, 0) def getChannelOTF(var): otflist = sorted([item for item in os.listdir(OTFdir.get()) if item.endswith('.otf')]) selectedlist = [item for item in otflist if item.startswith(str(var))] fullist=0 top = Tk.Toplevel() top.title('Choose OTF for %d' % var) scrollbar = Tk.Scrollbar(top) scrollbar.grid(row=0, column=3, sticky='ns') lb = Tk.Listbox(top, yscrollcommand=scrollbar.set, height=18, width=28) for item in selectedlist: lb.insert(Tk.END, os.path.basename(item)) lb.grid(row=0, column=0, columnspan=3) scrollbar.config(command=lb.yview) def Select(): items = lb.curselection() if fullist: item = [otflist[int(item)] for item in items][0] else: item = [selectedlist[int(item)] for item in items][0] if item: channelOTFPaths[var].set(OTFdir.get() + '/' + item) top.destroy() def ShowAll(): lb.delete(0, 'end') for item in otflist: lb.insert(Tk.END, os.path.basename(item)) global fullist fullist = 1 def cancelOTF(): top.destroy() selectButton = Tk.Button(top, text="Select",command=Select, pady=6, padx=10) selectButton.grid(row=1, column=0) cancelButton = Tk.Button(top, text="ShowAll",command=ShowAll, pady=6, padx=10) cancelButton.grid(row=1, column=2) cancelButton = Tk.Button(top, text="Cancel",command=cancelOTF, pady=6, padx=10) cancelButton.grid(row=1, column=1) top.update_idletasks() w = top.winfo_screenwidth() h = top.winfo_screenheight() size = tuple(int(_) for _ in top.geometry().split('+')[0].split('x')) x = w/2 - size[0]/2 y = h/2 - size[1]/1.3 top.geometry("%dx%d+%d+%d" % (size + (x, y))) top.resizable(0,0) def quit(): """Quit the program.""" root.destroy() def cancel(): """Cancel the current activity.""" print("Cancel button pressed.") global Server if Server['status'] and Server['status'] != 'canceled': statusTxt.set("Process canceled!") textArea.insert(Tk.END, "Process canceled...\n\n") Server['status'] = 'canceled' Server['busy'] = False # could be more agressiver here and close ssh def processFile(mode): """ where mode = 'optimal', 'single', 'register', or 'registerCal' """ inputfile = rawFilePath.get() if not os.path.exists(inputfile): tkMessageBox.showinfo("Input file Error", "Input file does not exist") return 0 if not mode=='register' and not isRawSIMfile(inputfile): response = tkMessageBox.askquestion("Input file Error", "Input file doesn't appear to be a raw SIM file... Do it anyway?") if response == "no": return 0 V = entriesValid(mode) if V[0]: send_command(inputfile, mode) if doWF.get() and (mode=='optimal' or mode=='single'): thr = threading.Thread(target=pseudoWF, args=(inputfile,)) thr.start() else: textArea.insert(Tk.END, "Invalid settings!\n") [textArea.insert(Tk.END, ": ".join(e) + "\n" ) for e in V[1]] textArea.insert(Tk.END, "\n") return 0 def sendRegCal(): inputfile = regCalImage.get() if not os.path.exists(inputfile): tkMessageBox.showinfo("Input file Error", "Registration calibration image doesn't exist") return 0 upload(inputfile, C.remotepath, 'registerCal') def dobatch(mode): """Start batch job. mode can be one of 'optimal', 'single', or 'register' and will perform the corresponding task on the provided batch folder """ global Server if Server['status'] == 'canceled': Server['status'] = None # this is here in case the last button pressed was cancel batchlist = [] directory = batchDir.get() if not directory: tkMessageBox.showinfo('No batch directory!', 'Please chose a directory for batch reconstruction') return 0 for R, S, F in os.walk(directory): for file in F: fullpath = os.path.join(R, file) if mode=='register': if isaReconstruction(fullpath): header = Mrc.open(fullpath).hdr numWaves = header.NumWaves if numWaves > 1: batchlist.append(fullpath) else: print("Skipping single-channel file: %s" % fullpath) else: if isRawSIMfile(fullpath): if skipalreadyprocessed.get() and isAlreadyProcessed(fullpath): pass else: batchlist.append(fullpath) def callback(mode): if Server['busy']: root.after(700, callback, mode) else: if Server['status'] == 'canceled': statusTxt.set("Batch job canceled... closing server connection") return 0 elif Server['status'] == None or Server['status']=='getDone': if len(batchlist) == 0: print("Batch reconstruction finished") statusTxt.set("Batch reconstruction finished") else: item = batchlist.pop(0) setRawFile(item) V = entriesValid(silent=True) if V[0]: if onlyoptimizefirst.get() and Server['batchround']>1 and not mode=='register': mode='single' print("Current File: %s" % item) processFile(mode) Server['batchround']+=1 else: print("Invalid settings on file: %s" % item) textArea.insert(Tk.END, "Batch job skipping file: %s\n" % item) [textArea.insert(Tk.END, ": ".join(e) + "\n" ) for e in V[1]] textArea.insert(Tk.END, "\n") root.after(600, callback, mode) else: print("Unexpected server status in batch job: %s" % Server['status']) root.after(600, callback, mode) if len(batchlist): print("Starting batch on: %s" % directory) Server['batchround']=1 callback(mode) else: if mode=='register': statusTxt.set('No (multi-channel) PROC files in directory!') else: statusTxt.set('No raw SIM files in directory!') def naccheck(entry, var): # function for linking enabled state of entry # to a checkbox, for example if var.get() == 0: entry.configure(state='disabled') else: entry.configure(state='normal') def get_git_revision_short_hash(): import subprocess os.chdir(os.path.dirname(os.path.realpath(__file__))) return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD']) class ToolTip: def __init__(self, master, text='Your text here', delay=1500, **opts): self.master = master self._opts = {'anchor':'center', 'bd':1, 'bg':'lightyellow', 'delay':delay, 'fg':'black',\ 'follow_mouse':0, 'font':None, 'justify':'left', 'padx':4, 'pady':2,\ 'relief':'solid', 'state':'normal', 'text':text, 'textvariable':None,\ 'width':0, 'wraplength':150} self.configure(**opts) self._tipwindow = None self._id = None self._id1 = self.master.bind("<Enter>", self.enter, '+') self._id2 = self.master.bind("<Leave>", self.leave, '+') self._id3 = self.master.bind("<ButtonPress>", self.leave, '+') self._follow_mouse = 0 if self._opts['follow_mouse']: self._id4 = self.master.bind("<Motion>", self.motion, '+') self._follow_mouse = 1 def configure(self, **opts): for key in opts: if self._opts.has_key(key): self._opts[key] = opts[key] else: KeyError = 'KeyError: Unknown option: "%s"' %key raise KeyError ##----these methods handle the callbacks on "<Enter>", "<Leave>" and "<Motion>"---------------## ##----events on the parent widget; override them if you want to change the widget's behavior--## def enter(self, event=None): self._schedule() def leave(self, event=None): self._unschedule() self._hide() def motion(self, event=None): if self._tipwindow and self._follow_mouse: x, y = self.coords() self._tipwindow.wm_geometry("+%d+%d" % (x, y)) ##------the methods that do the work:---------------------------------------------------------## def _schedule(self): self._unschedule() if self._opts['state'] == 'disabled': return self._id = self.master.after(self._opts['delay'], self._show) def _unschedule(self): id = self._id self._id = None if id: self.master.after_cancel(id) def _show(self): if self._opts['state'] == 'disabled': self._unschedule() return if not self._tipwindow: self._tipwindow = tw = Tk.Toplevel(self.master) # hide the window until we know the geometry tw.withdraw() tw.wm_overrideredirect(1) if tw.tk.call("tk", "windowingsystem") == 'aqua': tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "none") self.create_contents() tw.update_idletasks() x, y = self.coords() tw.wm_geometry("+%d+%d" % (x, y)) tw.deiconify() def _hide(self): tw = self._tipwindow self._tipwindow = None if tw: tw.destroy() ##----these methods might be overridden in derived classes:----------------------------------## def coords(self): # The tip window must be completely outside the master widget; # otherwise when the mouse enters the tip window we get # a leave event and it disappears, and then we get an enter # event and it reappears, and so on forever :-( # or we take care that the mouse pointer is always outside the tipwindow :-) tw = self._tipwindow twx, twy = tw.winfo_reqwidth(), tw.winfo_reqheight() w, h = tw.winfo_screenwidth(), tw.winfo_screenheight() # calculate the y coordinate: if self._follow_mouse: y = tw.winfo_pointery() + 20 # make sure the tipwindow is never outside the screen: if y + twy > h: y = y - twy - 30 else: y = self.master.winfo_rooty() + self.master.winfo_height() + 3 if y + twy > h: y = self.master.winfo_rooty() - twy - 3 # we can use the same x coord in both cases: x = tw.winfo_pointerx() - twx / 2 if x < 0: x = 0 elif x + twx > w: x = w - twx return x, y def create_contents(self): opts = self._opts.copy() for opt in ('delay', 'follow_mouse', 'state'): del opts[opt] label = Tk.Label(self._tipwindow, **opts) label.pack() def get_recent_regfile(): reglist = sorted([item for item in os.listdir(C.regFileDir) if item.endswith('.mat') and "refs" not in item]) RegFile.set(os.path.join(C.regFileDir, reglist[-1])) ####################################################################################### ################################ START PROCEDURAL CODE ################################ ####################################################################################### Server = { 'busy' : False, 'connected' : False, 'currentFile' : None, 'progress' : (0,0), 'status' : None, # transferring, putDone, getDone, processing, canceled } lastdir='' ### SETUP MAIN WINDOW ### root = Tk.Tk() root.title('CBMF SIM Reconstruction Tool v.%s' % get_git_revision_short_hash()) Style().theme_use('clam') top_frame = Tk.Frame(root) # input file frame Nb = Notebook(root) # Tabs container textAreaFrame = Tk.Frame(root, bg='gray', bd=2) # Text Area (output) Frame statusFrame = Tk.Frame(root) # Statusbar Frame # add individual tab frames otfsearchFrame = Tk.Frame(Nb, padx=5, pady=8) singleReconFrame = Tk.Frame(Nb, padx=5, pady=8) settingsFrame = Tk.Frame(Nb, padx=5, pady=8) batchFrame = Tk.Frame(Nb, padx=5, pady=8) registrationFrame = Tk.Frame(Nb, padx=5, pady=8) helpFrame = Tk.Frame(Nb, padx=5, pady=8) Nb.add(otfsearchFrame, text='Optimized Reconstruction') Nb.add(singleReconFrame, text='Specify OTFs') Nb.add(batchFrame, text='Batch') Nb.add(registrationFrame, text='Channel Registration') Nb.add(settingsFrame, text='Settings') Nb.add(helpFrame, text='Help') # pack the main frames into the top window top_frame.pack(side="top", fill="both", padx=15, pady=5) Nb.pack(side="top", fill="both", padx=15, pady=5) textAreaFrame.pack(side="top", fill="both", padx=15, pady=5) statusFrame.pack(side="top", fill="both") ##### TOP AREA FOR INPUT FILE #### # variables rawFilePath = Tk.StringVar() RefChannel = Tk.IntVar() RefChannel.set(C.refChannel) channelSelectVars={} doReg = Tk.IntVar() doReg.set(C.doReg) doMax = Tk.IntVar() doMax.set(C.doMax) doWF = Tk.IntVar() doWF.set(C.doWF) Tk.Label(top_frame, text='Input File:').grid(row=0, sticky='e') Tk.Entry(top_frame, textvariable=rawFilePath, width=48).grid(row=0, column=1, columnspan=6, sticky='W') Tk.Label(top_frame, text='Use Channels:').grid(row=1, sticky='e') allwaves=C.valid['waves'] channelSelectBoxes={} for i in range(len(allwaves)): channelSelectVars[allwaves[i]]=Tk.IntVar() channelSelectVars[allwaves[i]].set(0) channelSelectBoxes[allwaves[i]]=Tk.Checkbutton(top_frame) channelSelectBoxes[allwaves[i]].config(variable=channelSelectVars[allwaves[i]], text=str(allwaves[i]), state='disabled') channelSelectBoxes[allwaves[i]].grid(row=1, column=i+1, sticky='W') Tk.Label(top_frame, text='Ref Channel:').grid(row=2, sticky='e') RefChannelEntry = Tk.OptionMenu(top_frame, RefChannel, *allwaves) if not C.doReg: RefChannelEntry.config(state='disabled') RefChannelEntry.grid(row=2, column=1, sticky='W') Tk.Checkbutton(top_frame, variable=doReg, text='Do registration', command=lambda e=RefChannelEntry, v=doReg: naccheck(e,v)).grid( row=2, column=2, columnspan=2, sticky='W') Tk.Checkbutton(top_frame, variable=doMax, text='Do max').grid( row=2, column=4, sticky='W') Tk.Checkbutton(top_frame, variable=doWF, text='Do pseudoWF').grid( row=2, column=5, columnspan=2, sticky='W') Tk.Button(top_frame, text ="Choose File", command=getRawFile).grid( row=0, column=7, ipady=3, ipadx=7, sticky='ew') Tk.Button(top_frame, text="Quit", command=quit).grid( row=1, column=7, ipady=3, ipadx=7, sticky='ew') Tk.Button(top_frame, text="Cancel", command=cancel).grid( row=2, column=7, ipady=3, ipadx=7, sticky='ew') # OPTIMIZED RECONSTRUCTION # variables maxOTFage = Tk.StringVar() maxOTFage.set(C.maxAge if C.maxAge is not None else '') maxOTFnum = Tk.StringVar() maxOTFnum.set(C.maxNum if C.maxNum is not None else '') cropsize = Tk.StringVar() cropsize.set(C.cropsize) OilMin = Tk.StringVar() OilMin.set(C.oilMin) OilMax = Tk.StringVar() OilMax.set(C.oilMax) forceChannels = {} forceChannelsMenus = {} wieneropt = Tk.StringVar() wieneropt.set(C.wiener) #left side Tk.Label(otfsearchFrame, text="Limit OTFs used in search", font=('Helvetica', 12, 'bold')).grid(row=0, column=0, columnspan=2, sticky='w') leftLabels = ['Max OTF age (days):', 'Max number OTFs:', 'Crop Size (pix):', 'Min Oil RI:', 'Max Oil RI:', 'Wiener:'] for i in range(len(leftLabels)): Tk.Label(otfsearchFrame, text=leftLabels[i]).grid(row=i+1, sticky='E') Tk.Entry(otfsearchFrame, textvariable=maxOTFage).grid(row=1, column=1) Tk.Entry(otfsearchFrame, textvariable=maxOTFnum).grid(row=2, column=1) Tk.Entry(otfsearchFrame, textvariable=cropsize).grid(row=3, column=1) Tk.Entry(otfsearchFrame, textvariable=OilMin).grid(row=4, column=1) Tk.Entry(otfsearchFrame, textvariable=OilMax).grid(row=5, column=1) Tk.Entry(otfsearchFrame, textvariable=wieneropt).grid(row=6, column=1) #right side Tk.Label(otfsearchFrame, text="Force specific images channel:OTF pairings", font=('Helvetica', 12, 'bold')).grid(row=0, column=2, columnspan=2, sticky='w', padx=(20, 0)) for i in range(len(allwaves)): Tk.Label(otfsearchFrame, text="OTF to use for channel %s:" % allwaves[i]).grid(row=i + 1, column=2, sticky='E', padx=(40, 0)) forceChannels[allwaves[i]] = Tk.IntVar() forceChannels[allwaves[i]].set(allwaves[i]) forceChannelsMenus[allwaves[i]] = Tk.OptionMenu(otfsearchFrame, forceChannels[allwaves[i]], *allwaves) forceChannelsMenus[allwaves[i]].grid(row=i + 1, column=3, sticky='w') Tk.Button(otfsearchFrame, text="Run OTF Search", command=partial(processFile, 'optimal')).grid(row=7, column=0, columnspan=4, ipady=8, ipadx=8, pady=35) # SINGLE RECON TAB #variables wienerspec = Tk.StringVar() wienerspec.set(C.wiener) background = Tk.StringVar() background.set(C.background) timepoints = Tk.StringVar() timepoints.set('') allwaves=C.valid['waves'] channelOTFPaths={} channelOTFEntries={} channelOTFButtons={} Tk.Label(singleReconFrame, text="Use this tab to quickly reconstruct the input file with the OTFs and settings specified in this tab", font=('Helvetica', 12, 'bold')).grid(row=0, column=0, columnspan=7, sticky='w') Tk.Label(singleReconFrame, text='Wiener:').grid(row=1, column=0, sticky='E') wfe = Tk.Entry(singleReconFrame, textvariable=wienerspec, width=9) wfe.grid(row=1, column=1) ToolTip(wfe, text='Wiener Filter',delay=200) Tk.Label(singleReconFrame, text='Background:').grid(row=1, column=2, sticky='e') Tk.Entry(singleReconFrame, textvariable=background, width=9).grid(row=1, column=3) Tk.Label(singleReconFrame, text='Timepoints:').grid(row=1, column=4, sticky='e') Tk.Entry(singleReconFrame, textvariable=timepoints, width=9).grid(row=1, column=5) for i in range(len(allwaves)): Tk.Label(singleReconFrame, text=str(allwaves[i]) + "nm OTF: ").grid(row=i+2, column=0, sticky='E') for i in range(len(allwaves)): channelOTFPaths[allwaves[i]] = Tk.StringVar() channelOTFPaths[allwaves[i]].set("/".join([C.defaultOTFdir,str(allwaves[i])+'.otf'])) channelOTFEntries[allwaves[i]] = Tk.Entry(singleReconFrame, textvariable=channelOTFPaths[allwaves[i]]) channelOTFEntries[allwaves[i]].grid(row=i+2, column=1, columnspan=5, sticky='EW') channelOTFButtons[allwaves[i]] = Tk.Button(singleReconFrame, text ="Select OTF", command=partial(getChannelOTF, allwaves[i])) channelOTFButtons[allwaves[i]].grid(row=i+2, column=6, ipady=3, ipadx=10) Tk.Button(singleReconFrame, text ="Reconstruct", command = partial(processFile, 'single')).grid(row=8, column=0, columnspan=7, ipady=8, ipadx=8, pady=8) # REGISTRATION TAB # variables RegFile = Tk.StringVar() #RegFile.set( C.regFile ) regCalImage = Tk.StringVar() calibrationIterations = Tk.IntVar() calibrationIterations.set(C.CalibrationIter) RegCalRef = Tk.StringVar() RegCalRef.set('all') Tk.Label(registrationFrame, text='Apply registration to current image file', font=('Helvetica', 13, 'bold')).grid(row=0, column=0, columnspan=5, sticky='w') Tk.Label(registrationFrame, text='Registration File:').grid(row=1, column=0, sticky='E') RegFileEntry = Tk.Entry(registrationFrame, textvariable=RegFile).grid(row=1, column=1, columnspan=3, sticky='EW') Tk.Button(registrationFrame, text ="Choose File", command = getRegFile).grid(row=1, column=4, ipady=3, ipadx=10, sticky='ew') singleRegButton = Tk.Button(registrationFrame, text ="Register Input File", command = partial(processFile, 'register')).grid(row=2, column=1,ipady=3, ipadx=10,sticky='w') Tk.Label(registrationFrame, text='Ref Channel:').grid(row=2, column=2, sticky='e') RefChannelEntry = Tk.OptionMenu(registrationFrame, RefChannel, *allwaves) RefChannelEntry.grid(row=2, column=3, sticky='W') Tk.Label(registrationFrame, text='Use calibration image (e.g. dot grid, or tetraspeck) to calculate registration matrices', font=('Helvetica', 13, 'bold')).grid(row=3, columnspan=5, sticky='w',pady=(20,0)) Tk.Label(registrationFrame, text='Calibration Image:').grid(row=4, column=0, sticky='e') regCalImageEntry = Tk.Entry(registrationFrame, textvariable=regCalImage).grid(row=4, column=1, columnspan=3, sticky='EW') Tk.Button(registrationFrame, text ="Choose Image", command = getregCalImage).grid(row=4, column=4, ipady=3, ipadx=10, sticky='ew') Tk.Label(registrationFrame, text='Iterations:').grid(row=5, column=0, sticky='e') calibrationIterationsEntry = Tk.Entry(registrationFrame, textvariable=calibrationIterations, width=15).grid(row=5, column=1, columnspan=1, sticky='W') Tk.Label(registrationFrame, text='Reference to:').grid(row=5, column=2, sticky='ew') o=['all'] o.extend(allwaves) Tk.OptionMenu(registrationFrame, RegCalRef, *o).grid(row=5, column=3, sticky='W') Tk.Button(registrationFrame, text ="Calibrate", command = sendRegCal).grid(row=5, column=4, ipady=3, ipadx=10, sticky='ew') # CONFIG TAB # variables OTFdir = Tk.StringVar() OTFdir.set(C.OTFdir ) SIRconfigDir = Tk.StringVar() SIRconfigDir.set(C.SIconfigDir) server = Tk.StringVar() server.set(C.server) username = Tk.StringVar() username.set(C.username) Tk.Label(settingsFrame, text='Server Settings:', font=('Helvetica', 13, 'bold')).grid(row=0, column=0, columnspan=5, sticky='w') Tk.Label(settingsFrame, text='OTF Directory:').grid(row=1, sticky='e') Tk.Entry(settingsFrame, textvariable=OTFdir, width=48).grid(row=1, column=1, columnspan=6, sticky='W') Tk.Label(settingsFrame, text='SIR config Dir:').grid(row=2, sticky='e') Tk.Entry(settingsFrame, textvariable=SIRconfigDir, width=48).grid(row=2, column=1, columnspan=6, sticky='W') Tk.Label(settingsFrame, text='Server Address:').grid(row=3, sticky='e') Tk.Entry(settingsFrame, textvariable=server, width=48).grid(row=3, column=1, columnspan=6, sticky='W') Tk.Label(settingsFrame, text='Username:').grid(row=4, sticky='e') Tk.Entry(settingsFrame, textvariable=username, width=48).grid(row=4, column=1, columnspan=6, sticky='W') #Tk.Button(settingsFrame, text="Test Connection", command=test_connect, # width=12).grid(row=5, column=1, columnspan=2, ipady=6, ipadx=6, sticky='w') Tk.Label(settingsFrame, text='Misc Settings:', font=('Helvetica', 13, 'bold')).grid(row=6, column=0, columnspan=5, sticky='w', pady=(10,0)) overwrite = Tk.IntVar() overwrite.set(1) Tk.Checkbutton(settingsFrame, variable=overwrite, text='Overwrite local files when downloading (increment name if unchecked)').grid( row=7, column=0, columnspan=4, sticky='W') optOut = Tk.IntVar() optOut.set(0) Tk.Checkbutton(settingsFrame, variable=optOut, text='Opt out of reconstruction score collection (no images are saved in score collection)').grid( row=8, column=0, columnspan=4, sticky='W') # BATCH TAB batchDir = Tk.StringVar() onlyoptimizefirst = Tk.IntVar() onlyoptimizefirst.set(0) skipalreadyprocessed = Tk.IntVar() skipalreadyprocessed.set(1) Tk.Label(batchFrame, text='Batch process a directory of files.', font=('Helvetica', 13, 'bold')).grid(row=0, columnspan=5, sticky='w') Tk.Label(batchFrame, text='Directory:').grid(row=1, sticky='e') Tk.Entry(batchFrame, textvariable=batchDir).grid( row=1, column=1, columnspan=2, pady=8, sticky='eW') Tk.Button(batchFrame, text ="Choose Dir", command = getbatchDir).grid( row=1, column=3, ipady=3, ipadx=10, padx=2, sticky='w') Tk.Button(batchFrame, text="Batch Optimized Reconstruction", command=partial(dobatch, 'optimal'), ).grid(row=2, column=1, ipady=6, sticky='ew') Tk.Button(batchFrame, text="Batch Specified Reconstruction", command=partial(dobatch, 'single'), ).grid(row=2, column=2, ipady=6, sticky='ew') Tk.Label(batchFrame, text='(Settings on the respective tabs will be used for batch reconstructions)').grid( row=4, column=1, columnspan=3, pady=8, sticky='w') Tk.Checkbutton(batchFrame, variable=onlyoptimizefirst, text='Only perform optimized reconstruction on first file (then use OTFs)').grid( row=5, column=1, columnspan=3, sticky='W') Tk.Checkbutton(batchFrame, variable=skipalreadyprocessed, text='Skip files that have already been reconstructed').grid( row=6, column=1, columnspan=3, sticky='W') Tk.Button(batchFrame, text="Batch register processed files", command=partial(dobatch, 'register'), ).grid(row=7, column=1, ipady=6, sticky='ew') # HELP TAB helpText = ScrolledText(helpFrame, wrap='word') helpText.pack(fill='both') helpText.tag_configure("heading", font=('Helvetica', 12, 'bold')) helpText.tag_configure("paragraph", font=('Helvetica', 10, 'normal')) helpText.tag_configure("code", font=('Monaco', 10, 'bold')) helpText.tag_configure("italics", font=('Helvetica', 12, 'italic')) helpText.insert('insert', 'Input File\n', 'heading') helpText.insert('insert', 'Select a raw SIM .dv file to process and choose the ', 'paragraph') helpText.insert('insert', 'Channels ', 'code') helpText.insert('insert', 'that you would like to include in the reconstructions. ', 'paragraph') helpText.insert('insert', 'When you open a new file, the channels will be automatically populated based on the available channels in the image. \n', 'paragraph') helpText.insert('insert', '\n') helpText.insert('insert', 'Optimized Reconstruction \n', 'heading') helpText.insert('insert', 'Use this tab to search the folder of OTFs specified on the server tab for the optimal OTF for each channel. ', 'paragraph') helpText.insert('insert', 'Adjust the OTF search parameters in the optimized reconstruction tab and hit the ', 'paragraph') helpText.insert('insert', 'Run OTF Search ', 'code') helpText.insert('insert', 'button. \n', 'paragraph') helpText.insert('insert', '\n') helpText.insert('insert', 'Specify OTFs\n', 'heading') helpText.insert('insert', 'This tab can be used to specifiy OTFs for each channel present in the file, then perform a single reconstruction. \n ', 'paragraph') helpText.insert('insert', '\n') helpText.insert('insert', 'Server\n', 'heading') helpText.insert('insert', 'The Server tab specifies important folders on the server used in the reconstructions. \n ', 'paragraph') helpText.insert('insert', '\n') helpText.insert('insert', "If you are getting bugs or unexpected results, don't hesistate to ask for help!\n", 'italics') helpText.insert('insert', '\n') helpText.insert('insert', "Created by <NAME>, (c) 2016", 'paragraph') helpText.config(height=17, state='disabled') # TEXT AREA textArea = ScrolledText(textAreaFrame) textArea.config(height=14) textArea.pack(side='bottom', fill='both') Tk.Button(textAreaFrame, text="Clear", command=lambda: textArea.delete(1.0, 'end'), relief='flat', padx=7, pady=4).place( relx=1.0, rely=1.0, x=-23, y=-5, anchor="se") # STATUS BAR statusTxt = Tk.StringVar() statusBar = Tk.Label(statusFrame, textvariable=statusTxt, bd=1, relief='sunken', anchor='w', background='gray') statusBar.pack(side='bottom', fill='x') # UPDATE WINDOW GEOMETRY AND CENTER ON SCREEN root.update_idletasks() w = root.winfo_screenwidth() h = root.winfo_screenheight() size = tuple(int(_) for _ in root.geometry().split('+')[0].split('x')) x = w/2 - size[0]/2 y = h/2 - size[1]/1.3 root.geometry("%dx%d+%d+%d" % (size + (x, y))) root.resizable(0,0) # grab most recent regfile from server (this may also cause failure if no connection) try: get_recent_regfile() except AttributeError as e: print 'ERROR: Could not retrieve the most recent registration file!' except IOError as e: print 'ERROR: could not find a good registration file!' statusTxt.set('ERROR: could not find a good registration file!') except: pass #START PROGRAM root.mainloop()<file_sep>/otfsearch.py import sys import os from datetime import datetime import subprocess import Mrc import numpy as np from scipy import stats import config # OTF handling functions def makeOTFdict(dir,template=config.OTFtemplate,delim=config.OTFdelim,ext=config.OTFextension): allOTFs = [otf for otf in os.listdir(dir) if otf.endswith(ext)] O = [otf.split(ext)[0].split(delim) for otf in allOTFs] D=[dict(zip(template.split(delim),o)) for o in O] for n in range(len(D)): D[n]['path']=os.path.join(dir,allOTFs[n]) D[n]['ctime']=os.stat(os.path.join(dir,allOTFs[n])).st_ctime D[n]['code']=getOTFcode(os.path.join(dir,allOTFs[n])) return D def getMatchingOTFs(otfdict, wave, oilMin, oilMax, maxAge=None, maxNum=None): import time OTFlist=[O for O in otfdict if O['wavelength']==str(wave) and int(O['oil'])>=oilMin and int(O['oil'])<=oilMax] if maxAge is not None: oldestDate=time.time()-maxAge*24*60*60 OTFlist=[O for O in OTFlist if O['ctime']>=oldestDate] OTFlist.sort(key=lambda x: x['ctime'], reverse=True) OTFlist=OTFlist[0:maxNum] return [O for O in sorted(OTFlist, key=lambda x: x['oil'])] def getOTFcode(fname,template=config.OTFtemplate,delim=config.OTFdelim): splits = os.path.basename(fname).split('.otf')[0].split(delim) T=template.split(delim) code = "w" + splits[T.index('wavelength')] + "d" + splits[T.index('date')] + "o" + splits[T.index('oil')] + splits[T.index('angle')] + "b" + splits[T.index('beadnum')] return code def decodeOTFcode(code,template=config.OTFtemplate,delim=config.OTFdelim): pass def goodChannel(string): import argparse goodChannels=config.valid['waves'] value = int(string) if value not in goodChannels: msg = "%r is not one of the acceptable channel names: %s" % (string, ', '.join(str(x) for x in goodChannels)) raise argparse.ArgumentTypeError(msg) return value def cropCheck(string): import argparse value = int(string) if not (value != 0 and ((value & (value - 1)) == 0)): msg = "%r is not a power of two" % string raise argparse.ArgumentTypeError(msg) if value > 1024 or value < 32: msg = "Cropsize must be between 32 and 1024" raise argparse.ArgumentTypeError(msg) return value # image file manipulation def callPriism(command=None): # must figure out way to add this to path if not os.environ.has_key('IVE_BASE') and os.path.exists(config.priismpath): P = os.environ['PATH'].split(":") P.insert(0,os.path.join(config.priismpath,'Darwin64','BIN')) os.environ['PATH'] = ":".join(P) dyld_fallback = [ os.path.join(config.priismpath,'Darwin64','LIB'), os.path.join(config.priismpath,'Darwin','LIB'), os.path.join(os.path.expanduser('~'),'lib'), '/usr/local/lib', '/lib', '/usr/lib'] os.environ['DYLD_FALLBACK_LIBRARY_PATH'] = ":".join(dyld_fallback) os.environ['IVE_WORKING_SET']='24000' os.environ['IVE_BASE']=config.priismpath os.environ['LIBQUICKTIME_PLUGIN_DIR']=os.path.join(config.priismpath,'libquicktime','Darwin','lib','libquicktime') os.environ['IVE_PGTHRESH']='1024' os.environ['IVE_SIZE']='27000' os.environ['IVE_WORKING_UNIT']='128' # IVE_ENV_SETUP={ test -r '/Users/talley/Dropbox/NIC/software/priism-4.4.1/Priism_setup.sh' && . '/Users/talley/Dropbox/NIC/software/priism-4.4.1/Priism_setup.sh' ; } || exit 1 if command: try: subprocess.call(command) except EOFError: msg = "Priism may not be setup correctly...\n" msg += "Source the priism installation and try again" raise EOFError(msg) def splitchannels(fname, waves=None): reader = Mrc.open(fname) imWaves = [i for i in reader.hdr.wave if i != 0] if waves is None: waves = imWaves namesplit = os.path.splitext(fname) files = [] for w in waves: if w in imWaves: print "Extracting channel %d..." % w out=namesplit[0]+"-"+str(w)+namesplit[1] callPriism(['CopyRegion', fname, out, "-w="+str(w)]) files.append(out) return files def mergeChannels(fileList, outFile=None): if outFile is None: namesplit = os.path.splitext(fileList[0]) outFile=namesplit[0]+"_MRG"+namesplit[1] command = ['mergemrc', '-append_waves', outFile] command.extend(fileList) callPriism(command) return outFile def maxprj(fname, outFile=None): if outFile is None: namesplit = os.path.splitext(fname) outFile=namesplit[0]+"_MAX"+namesplit[1] header = Mrc.open(fname).hdr numWaves = header.NumWaves numTimes = header.NumTimes imSize = header.Num numplanes = imSize[2]/(numTimes*numWaves) callPriism([ 'RunProj', fname, outFile, '-z_step=%d'%numplanes, '-z_group=%d'%numplanes, '-max_z' ]) return outFile def pseudoWF(fileIn, nangles=3, nphases=5, extract=None, outFile=None): """Generate pseudo-widefield image from raw SIM stack by averaging phases together""" img = Mrc.bindFile(fileIn) nt = img.Mrc.hdr.NumTimes nw = img.Mrc.hdr.NumWaves nx = img.Mrc.hdr.Num[0] ny = img.Mrc.hdr.Num[1] nz = float(img.Mrc.hdr.Num[2]) / (nphases * nangles * nw * nt) # try to identify OTF files with nangles =1 if not nz%1==0: print "Guessing nangles = 1 ..." nangles=1 nz = img.Mrc.hdr.Num[2] / (nphases * nangles * nw * nt) imseq = img.Mrc.hdr.ImgSequence # 0 = ZTW # 1 = WZT # 2 = ZWT # reshape array to separate phases and angles from Z # and transpose to bring all ImgSeq types to type WZT if imseq==0: ordered = np.reshape(img,(nw,nt,nangles,nz,nphases,ny,nx)) ordered = np.transpose(ordered,(1,2,3,4,0,5,6)) elif imseq==1: ordered = np.reshape(img,(nt,nangles,nz,nphases,nw,ny,nx)) elif imseq==2: ordered = np.reshape(img,(nt,nw,nangles,nz,nphases,ny,nx)) ordered = np.transpose(ordered,(0,2,3,4,1,5,6)) else: raise ValueError('Uknown image sequence in input file') # average phases imgavg = np.mean(ordered, 3) imgavg = imgavg.astype(img.dtype) # now order is (nt, na, nz, nw, ny, nx) if extract: if not extract in range(1,nangles+1): print('extracted angle must be between 1 and %d' % nangles) print('chosing angle 1') extract=1 imgavg = imgavg[:,extract-1,:,:,:,:] else: #further average over all angles imgavg = np.mean(imgavg, 1, img.dtype) imgavg = np.squeeze(imgavg) if imgavg.ndim>4: raise ValueError('ERROR: pseudo widefield function cannot accept 5d images!') hdr = Mrc.makeHdrArray() Mrc.initHdrArrayFrom(hdr, img.Mrc.hdr) hdr.ImgSequence=1 if outFile is None: namesplit = os.path.splitext(fileIn) outFile=namesplit[0]+"_WF"+namesplit[1] if not (outFile is fileIn): try: Mrc.save(imgavg, outFile, hdr = hdr, ifExists='overwrite') except ValueError as e: print e #return outFile def stackmath(fileIn, operator='max', axis='z', outFile=None): """Generate pseudo-widefield image from raw SIM stack by averaging phases together""" img = Mrc.bindFile(fileIn) nt = img.Mrc.hdr.NumTimes nw = img.Mrc.hdr.NumWaves nx = img.Mrc.hdr.Num[0] ny = img.Mrc.hdr.Num[1] nz = img.Mrc.hdr.Num[2] / (nw * nt) imseq = img.Mrc.hdr.ImgSequence # 0 = ZTW # 1 = WZT # 2 = ZWT # reshape array to separate phases and angles from Z # and transpose to bring all ImgSeq types to type WZT if imseq==0: ordered = np.reshape(img,(nw,nt,nz,ny,nx)) ordered = np.transpose(ordered,(1,2,0,3,4)) elif imseq==1: ordered = np.reshape(img,(nt,nz,nw,ny,nx)) elif imseq==2: ordered = np.reshape(img,(nt,nw,nz,ny,nx)) ordered = np.transpose(ordered,(0,2,1,3,4)) else: raise ValueError('Uknown image sequence in input file') axtoindex={'t': 0, 'z': 1, 'w': 2, 'c': 2} if operator=='max' or operator=='maximum': proj = np.max(ordered, axtoindex[axis]) elif operator=='sum': proj = np.sum(ordered, axtoindex[axis]) elif operator=='std' or operator=='stdev': proj = np.std(ordered, axtoindex[axis]) elif operator=='med' or operator=='median': proj = np.std(ordered, axtoindex[axis]) elif operator=='avg' or operator=='average': proj = np.average(ordered, axtoindex[axis]) else: raise ValueError('operator must be: max, sum, std, med, or avg') proj = np.squeeze(proj) if proj.ndim>4: raise ValueError('Mrc.py cannot write 5D .dv images') hdr = Mrc.makeHdrArray() Mrc.initHdrArrayFrom(hdr, img.Mrc.hdr) hdr.ImgSequence=1 if outFile is None: namesplit = os.path.splitext(fileIn) outFile=namesplit[0]+"_"+operator.upper()+namesplit[1] if not (outFile is fileIn): try: Mrc.save(proj, outFile, hdr = hdr, ifExists='overwrite') except ValueError as e: print e def croptime(fileIn, fileOut=None, start=1, end=1, step=1): if fileOut is None: namesplit = os.path.splitext(fileIn) fileOut=namesplit[0]+"_T"+str(end)+namesplit[1] callPriism(['CopyRegion', fileIn, fileOut, "-t="+str(start)+":"+str(end)+":"+str(step)]) return fileOut def crop(fileIn, cropsize, fileOut=None): reader = Mrc.open(fileIn) imSize = reader.hdr.Num reader = Mrc.open(fileIn) cropstartX=(imSize[0]/2)-(cropsize/2); cropendX=cropstartX+cropsize-1 cropstartY=(imSize[1]/2)-(cropsize/2); cropendY=cropstartY+cropsize-1 if fileOut is None: namesplit = os.path.splitext(fileIn) fileOut=namesplit[0]+"_cropped"+namesplit[1] callPriism(['CopyRegion', fileIn, fileOut, "-x="+str(cropstartX)+":"+str(cropendX), "-y="+str(cropstartY)+":"+str(cropendY)]) return fileOut # helpers def isRawSIMfile(fname): if os.path.splitext(fname)[1] != ".dv": return 0 #exclude known processed files for q in ['_SIR','_PROC','_WF']: if q in os.path.basename(fname): return 0 try: header = Mrc.open(fname).hdr numWaves = header.NumWaves numTimes = header.NumTimes imSize = header.Num numplanes = imSize[2]/(numTimes*numWaves) if numplanes%15: return 0 return 1 except Exception as e: print "Error reading header in: %s" % fname return 0 # this is a more stringent check for raw SIM files... but will fail # if the log file doesn't exist def logIsTypeSI(file): '''For a given file, look for a .log file with the same name if it exists, and the experiment type is "SI", then return 1 ''' logfile=os.path.splitext(file)[0] + '.log' if not os.path.exists(logfile): return 0 for line in open(logfile, 'r'): if 'type:' in line: if line.split()[1]=='SI': return 1 else: return 0 break else: continue def isAlreadyProcessed(filename): '''simple check to see if a _PROC or _SIR file already exists for a given file ''' if filename.endswith('.dv'): if os.path.exists(filename.replace('.dv','_PROC.dv')): return 1 elif os.path.exists(filename.replace('.dv','_SIR.dv')): return 1 return 0 def isaReconstruction(filename): '''simple check to see whether a file is a SIM reconstruction (probably more elegant ways) ''' if filename.endswith('PROC.dv'): return 1 elif filename.endswith('PROC_MAX.dv'): return 1 return 0 def query_yes_no(question): """Ask a yes/no question via raw_input() and return their answer. "question" is a string that is presented to the user. The "answer" return value is True for "yes" or False for "no". """ valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} while True: sys.stdout.write(question) choice = raw_input().lower() if choice in valid: return valid[choice] else: sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n") # reconstruction def reconstruct(inFile, otfFile, outFile=None, configFile=None, wiener=None, background=None, configDir=None): wave = Mrc.open(inFile).hdr.wave[0] if outFile is None: namesplit = os.path.splitext(inFile) outFile=namesplit[0]+"_PROC"+namesplit[1] if configFile is None: if configDir is not None: configFile = os.path.join(configDir,str(wave)+'config') else: configFile = os.path.join(config.SIconfigDir,str(wave)+'config') if not os.path.exists(configFile): raise OSError(2, 'Cannot find SIrecon config file: %s' % configFile) commandArray=[config.reconApp,inFile,outFile,otfFile,'-c',configFile] if wiener: commandArray.extend(['--wiener',str(wiener)]) if background: commandArray.extend(['--background',str(background)]) process = subprocess.Popen(commandArray, stdout=subprocess.PIPE) output = process.communicate()[0] if 'CUFFT failed to allocate GPU or CPU memory' in output: raise MemoryError('CUFFT failed to allocate GPU or CPU memory: File size too large??') elif 'done' in output.split('\n')[-2]: return output def reconstructMulti(inFile, OTFdict={}, reconWaves=None, outFile=None, wiener=None, background=None,configDir=None, writeLog=True, logFile=None): """Splits multi-channel file into individual channels then reconstructs each channel and merges the results provide OTFdict as { '528' : '/path/to/528/otf', '608' : 'path/to/608/otf'} """ if outFile is None: namesplit = os.path.splitext(inFile) outFile=namesplit[0]+"_PROC"+namesplit[1] header = Mrc.open(inFile).hdr numWaves = header.NumWaves #waves = [i for i in header.wave if i != 0] # split multi-channel files into component parts if numWaves > 1: splitfiles = splitchannels(inFile, reconWaves) else: splitfiles = [inFile] filesToMerge = [] reconLogs=[] for file in splitfiles: wave = Mrc.open(file).hdr.wave[0] print "Reconstructing channel %d ..." % wave if OTFdict.has_key(str(wave)): otf = OTFdict[str(wave)] elif os.path.exists(os.path.join(config.defaultOTFdir,str(wave)+".otf")): otf = os.path.join(config.defaultOTFdir,str(wave)+'.otf') else: print "cannot find OTF for %s, channel %d... skipping" % (file,wave) continue namesplit = os.path.splitext(file) procFile=namesplit[0]+"_PROC"+namesplit[1] filesToMerge.append(procFile) try: reconLogs.append({ 'log' : reconstruct(file, otf, procFile, wiener=wiener, background=background, configDir=configDir), 'wave' : wave, 'otf' : otf, 'file' : file, 'procFile' : procFile }) except Exception as e: print "Cannot reconstruct file %s due to error %s" % (inFile,e) #cleanup files for f in splitfiles: if not f == inFile: os.remove(f) for f in filesToMerge: os.remove(f) return 0 if writeLog: if not logFile: namesplit=os.path.splitext(outFile) logFile=namesplit[0]+"_LOG.txt" with open(logFile, 'w') as the_file: the_file.write("INPUT FILE: %s \n" % inFile) the_file.write("\n") for D in reconLogs: the_file.write("#"*80+'\n') the_file.write("\n") the_file.write("WAVELENGTH: %d \n" % D['wave']) the_file.write("FILE: %s \n" % D['file']) the_file.write("OTF: %s \n" % D['otf']) indat = Mrc.bindFile(D['procFile']) try: imRIH = getRIH(indat) # workaround when RIH fails except: imRIH = 0.1 the_file.write("RECONSTRUCTION SCORE (MMR): %0.2f \n" % imRIH) the_file.write("\n") the_file.write("RECONSTRUCTION LOG: \n") the_file.write(D['log']) the_file.write("\n") if len(filesToMerge) > 1: print "Merging multi-channel reconstructions..." mergeChannels(filesToMerge, outFile) #cleanup files for f in splitfiles: os.remove(f) for f in filesToMerge: os.remove(f) else: outFile=filesToMerge[0] return (outFile,logFile) # SCORING FUNCTIONS def calcPosNegRatio(pc, bg, histMin, histMax, hist, nPixels): #find hist step (bin size) histStep = (histMax - histMin) / len(hist) # for negative histogram extreme, add until percentile reached negPc = 0.0 negTotal = 0.0 bin = 0 binValue = float(histMin) while (negPc < pc and binValue <= bg and bin < len(hist)): negPc += float(hist[bin]) / nPixels negTotal += (binValue - bg) * hist[bin] # make mode 0 bin += 1 binValue += histStep pc = negPc # for positive histogram extreme, add until percentile reached posPc = 0.0 posTotal = 0.0 bin = len(hist) - 1 binValue = float(histMax) while (posPc < pc and bin >=0): posPc += float(hist[bin]) / nPixels posTotal += (binValue - bg) * hist[bin] # make mode 0 bin -= 1 binValue -= histStep #uncomment to check actual histogram bins used (pc and pixels) #nNegPixels = int(negPc * nPixels) #nPosPixels = int(posPc * nPixels) #since negTotal may or may not be negative... posNegRatio = float(abs(posTotal / negTotal)) return posNegRatio def getRIH1(im): percentile = 0.0001 # use 0-100% of histogram extrema minPixels = 100.0 # minimum pixels at histogram extrema to use #modeTol = 0.25 # mode should be within modeTol*stdev of 0 #nNegPixels = 0 #nPosPixels = 0 flat = np.ndarray.flatten(im) histMin = flat.min() histMax = flat.max() hist = np.histogram(flat,bins=1024) background = hist[1][np.argmax(hist[0])] # find the rough mode if (histMin == 0): print "Image has no neg values!" if histMin <= background: # ensure we consider a bare minimum of pixels totalPixels = len(flat) if totalPixels * percentile / 100 < minPixels: percentile = minPixels * 100 / totalPixels # caluclate +ve / -ve ratio if histogram has negatives posNegRatio = calcPosNegRatio(percentile / 100, background, histMin, histMax, hist[0], totalPixels) return posNegRatio else: print "! histogram minimum above background. unable to calculate +ve/-ve intensity ratio" return 0.0 def getRIH(im): if im.Mrc.hdr.NumWaves > 1: scores = []; for i in im: scores.append((getRIH1(i))) else: scores = getRIH1(im) return scores def getSAM(im): from skimage import filters #hist=np.histogram(im,bins=1024); #stackMode = hist[1][np.argmax(hist[0])] #threshold = filters.threshold_otsu(im) sliceMinima = [np.min(i) for i in im] sliceMeans = [np.average(plane[np.where(plane > filters.threshold_otsu(plane))]) for plane in im] avgmean = np.nanmean(sliceMeans) minStd = np.std(sliceMinima) return minStd/avgmean def CIP(im): phases = 5 # phases nz = im.shape[-3] # shape gives (c, t, z, y, x) angles = 3 #angles nz = nz / (phases * angles) # take phase & angle out of Z npz = nz * phases zwin = 9 #### TIV ######## sliceMeans = list(reversed(np.mean(im.reshape(im.shape[-3],-1), axis=1)[::-1])) centralWindow=[] # TIV for a in range(angles): zFirst = (a*npz) + npz/2 -(zwin*phases/2) zLast = zFirst+zwin*phases centralWindow.append(sliceMeans[zFirst:zLast]) intensMin = np.min(centralWindow) intensMax = np.max(centralWindow) TIV = round(100 * (intensMax - intensMin) / intensMax,2) # per-channel intensity decay xSlice = range(len(sliceMeans)) # estimate % decay over each angle via simple straight line fit angleDecays = [] angleMeans = [] for a in range(angles): nzp = nz * phases xa = xSlice[a*nzp:(a+1)*nzp] ya = sliceMeans[a*nzp:(a+1)*nzp] angleMeans.append(np.mean(ya)) fitParams = stats.linregress(xa,ya) angleDecays.append((fitParams[0] * nzp * -100.0) / fitParams[1]) channelDecay = np.mean(angleDecays) # negative bleaching does not make sense, so report 0 if channelDecay < 0: channelDecay = 0 channelDecay = round(channelDecay,2) angleMax = np.max(angleMeans) angleMin = np.min(angleMeans) largestDiff = abs(angleMax - angleMin) angleDiffs = round(100 * largestDiff / angleMax,2) return (TIV, channelDecay, angleDiffs) def printFormattedScores(scoreList): ''' prints a nicely formatted version of the output from scoreOTFs ''' print "{:<8} {:<10} {:^23} {:<8} {:<8} {:<7}".format("Channel", "Bleaching", "OTF", "OTFoil", "Modamp", "RIH") for i in scoreList: print "{:<8} {:<10} {:<23} {:<8} {:<05.3} {:<04.3}".format(i['wavelength'], i['channelDecay'], i['OTFcode'], i['OTFoil'], np.average(i['modamp2']), i['RIH']) def scoreOTFs(inputFile, cropsize=256, OTFdir=config.OTFdir, reconWaves=None, forceChannels=None, oilMin=1510, oilMax=1524, maxAge=None, maxNum=None, verbose=True, cleanup=True): ''' Takes an input file and reconstructs it by all of the OTFs that match certain criteria ''' import shutil # check if it exists if not os.path.isfile(inputFile): sys.exit(inputFile + " not found... quitting") # create temp folder for reconstructions tmpDir = os.path.splitext(inputFile)[0]+"_tmp" if os.path.exists(tmpDir): shutil.rmtree(tmpDir) os.makedirs(tmpDir) # create symlink of original file in tmp fname=os.path.join(tmpDir,os.path.basename(inputFile)) os.symlink(inputFile, fname) # get file info header = Mrc.open(fname).hdr numWaves = header.NumWaves waves = [i for i in header.wave if i != 0] numTimes = header.NumTimes imSize = header.Num # cut timelapse to the first timepoint if numTimes>1: print("Timelapse detected, clipping to the first timepoint") fname=croptime(fname) # crop to a central region to speed things up if imSize[0]>cropsize or imSize[1]>cropsize: print "Cropping to the center %d pixels..." % cropsize fname=crop(fname, cropsize) if reconWaves is not None: if isinstance(reconWaves,list): for W in reconWaves: if not W in waves: reconWaves.remove(W) if verbose: print "channel %d does not exist in the input file..." % W elif isinstance(reconWaves,int): reconWaves = [reconWaves] else: if verbose: print "Channel input format not recognized: %s" % reconWaves print "Channels must be integer or list of integers. Quitting..." sys.exit(1) else: # reconstruct all channels reconWaves = waves # split multi-channel files into component parts if numWaves > 1: splitfiles = splitchannels(fname, reconWaves) else: splitfiles = [fname] # generate searchable dict of OTFs in a directory otfDict = makeOTFdict(OTFdir) allScores=[] # reconstruct each channel file by all matching OTFs for file in splitfiles: namesplit = os.path.splitext(file) imChannel = Mrc.open(file).hdr.wave[0] if verbose: print "%s - Channel: %s" % (os.path.basename(file), imChannel) # raw data/bleaching test indat=Mrc.bindFile(file) im=np.asarray(indat) TIV,channelDecay,angleDiffs = CIP(im) if verbose: print print "Bleaching rate: %.2f%%" % channelDecay print "Angle Illumination variance: %.2f%%" % angleDiffs print "Total intensity variation: %.2f%%" % TIV if channelDecay > 30: print "WARNING: Image: %s, Channel: %s, Bleaching: %.2f%%" % (os.path.basename(file),imChannel,channelDecay) if angleDiffs > 20: print "WARNING: Image: %s, Channel: %s, AngleDiff: %.2f%%" % (os.path.basename(file),imChannel,angleDiffs) fileDict={ "input" : inputFile, "input-ctime" : datetime.fromtimestamp(os.path.getctime(inputFile)), "TIV" : TIV, "channelDecay" : channelDecay, "angleDiffs" : angleDiffs, "imChannel" : imChannel } # this line allows the user to match certain image channels to certain OTF channels if forceChannels: otfWave = forceChannels[imChannel] if forceChannels.has_key(imChannel) else imChannel else: otfWave = imChannel OTFlist = getMatchingOTFs(otfDict,otfWave,oilMin,oilMax, maxAge=maxAge, maxNum=maxNum) for otf in OTFlist: # this is where we parse the reconstruction log and mine for import data procFile=namesplit[0] + "_" + otf['code'] + "_PROC" + namesplit[1] reconLog = reconstruct(file, otf['path'], procFile) combinedModamps = [float(line.split('amp=')[1].split(',')[0]) for line in reconLog.split('\n') if 'Combined modamp' in line] correlationCoeffs = [float(line.split(": ")[1]) for line in reconLog.split('\n') if 'Correlation coefficient' in line] spacings = [float(line.split(" ")[0]) for line in reconLog.split('spacing=')[1:]] angles = [float(line.split(",")[0]) for line in reconLog.split('Optimum k0 angle=')[1:]] lengths = [float(line.split(",")[0]) for line in reconLog.split('length=')[1:]] fitDeltas = [float(line.split(" ")[0]) for line in reconLog.split('best fit for k0 is ')[1:]] warnings = [line for line in reconLog.split('\n') if 'WARNING' in line] indat = Mrc.bindFile(procFile) try: imRIH = getRIH(indat) # workaround when RIH fails except: imRIH = 0.1 try: imSAM = getSAM(indat) except: imSAM = 0.1 scoreDict={ "OTFcode" : otf['code'], "OTFoil" : otf['oil'], "OTFangle": otf['angle'][1:], "OTFbead" : otf['beadnum'], "OTFdate" : otf['date'], "OTFwave" : otf['wavelength'], "OTFpath" : otf['path'], "RIH" : round(imRIH,3), "SAM" : round(imSAM,3), "warnings": warnings, "correl2" : correlationCoeffs[0:6:2], "correl1" : correlationCoeffs[1:6:2], "avgcorrel" : np.average(correlationCoeffs), "avgcorrel1" : np.average(correlationCoeffs[1:6:2]), "avgcorrel2" : np.average(correlationCoeffs[0:6:2]), "modamp2" : combinedModamps[0:6:2], "modamp1" : combinedModamps[1:6:2], "avgmodamp" : np.average(combinedModamps), "avgmodamp1" : np.average(combinedModamps[1:6:2]), "avgmodamp2" : np.average(combinedModamps[0:6:2]), "wiener" : reconLog.split('wiener=')[1][:5], "spacings" : spacings, "angles" : angles, "lengths" : lengths, "fitDeltas" : fitDeltas } scoreDict['score'] = scoreDict['RIH'] * scoreDict['avgmodamp2'] scoreDict.update(fileDict) allScores.append(scoreDict) if verbose: print "%s: %0.3f %.2f" % (otf['code'], np.average(combinedModamps[0:6:2]), imRIH) if verbose: print "" if cleanup: shutil.rmtree(tmpDir) return allScores def getBestOTFs(scoreDict,channels=None, report=10, verbose=True): results={} if channels is None: channels = list(set([s['imChannel'] for s in scoreDict])) for c in channels: sortedList = sorted([s for s in scoreDict if s['imChannel']==c], key=lambda x: x['score'], reverse=True) results[str(c)] = sortedList[0]['OTFpath'] if verbose: print "Channel %s:" % c q=[(s['OTFcode'], s['score'], s['RIH'], s['avgmodamp2']) for s in sortedList][:report] print "{:<23} {:<6} {:<5} {:<7}".format('OTFcode','Score','RIH','modamp') for i in q: print "{:<23} {:<05.3} {:<04.3} {:<05.3}".format(*i) return results def matlabReg(fname,regFile,refChannel,doMax,form='dv'): maxbool = 'true' if doMax else 'false' matlabString = "%s('%s','%s', %d,'DoMax', %s, 'format', '%s');exit" % (config.MatlabRegScript,fname,regFile,refChannel,maxbool,form) subprocess.call(['matlab', '-nosplash', '-nodesktop', '-nodisplay', '-r', matlabString]) registeredFile = os.path.splitext(fname)[0]+"-REGto"+str(refChannel)+"."+form if doMax: maxProj = os.path.splitext(fname)[0]+"-REGto"+str(refChannel)+"-MAX."+form else: maxProj = None return (registeredFile, maxProj) def pickRegFile(fname,directory,filestring=None): filelist = sorted(os.listdir(directory), key=lambda x: x.split("_")[1], reverse=True) reader = Mrc.open(fname) imWaves = [i for i in reader.hdr.wave if i != 0] for f in filelist: fileWaves = [int(w) for w in f.split('waves')[1].split('_')[0].split('-')] if set(imWaves).issubset(set(fileWaves)): if filestring: if filestring in f: return f else: return f # should add another bit to check whether the .mat file has that channel as # a reference channel... # if the regile has "refs" in the filename, it means that not all wavelengths # are referenced to all other wavelengths (otherwise, that can be assumed) return 0 def makeBestReconstruction(fname, cropsize=256, oilMin=1510, oilMax=1524, maxAge=config.maxAge, wiener=None, maxNum=config.maxNum, writeCSV=config.writeCSV, appendtomaster=True, OTFdir=config.OTFdir, reconWaves=None, forceChannels=None, regFile=None, regdir=config.regFileDir, refChannel=config.refChannel, doMax=None, doReg=None, cleanup=True, verbose=True): # check if it appears to be a raw SIM file if not isRawSIMfile(fname): if not query_yes_no("File doesn't appear to be a raw SIM file... continue?"): sys.exit("Quitting...") allScores = scoreOTFs(fname, cropsize=cropsize, OTFdir=config.OTFdir, reconWaves=reconWaves, forceChannels=forceChannels, oilMin=oilMin, oilMax=oilMax, maxAge=maxAge, maxNum=maxNum, verbose=verbose, cleanup=cleanup) bestOTFs = getBestOTFs(allScores, verbose=verbose) if verbose: print "reconstructing final file..." reconstructed,logFile = reconstructMulti(fname, OTFdict=bestOTFs, reconWaves=reconWaves, wiener=wiener) numWaves = Mrc.open(reconstructed).hdr.NumWaves registeredFile = None maxProj = None if doReg and numWaves>1: # perform channel registration if verbose: print "perfoming channel registration in matlab..." if not regFile: regFile = pickRegFile(fname,regdir) registeredFile, maxProj = matlabReg(reconstructed,regFile,refChannel,doMax) # will be a list elif doMax: maxProj = maxprj(reconstructed) scoreFile=None if writeCSV: # write the file to csv import pandas as pd scoreDF = pd.DataFrame(allScores) scoreFile = os.path.splitext(fname)[0]+"_scores.csv" scoreDF.to_csv(scoreFile) if appendtomaster: # write the file to master csv file with all the scores if not os.path.isfile(config.masterScoreCSV): scoreDF.to_csv(config.masterScoreCSV, mode='a', index=False) elif len(scoreDF.columns) != len(pd.read_csv(config.masterScoreCSV, nrows=1).columns): raise Exception("Columns do not match!! new scores have " + str(len(scoreDF.columns)) + " columns. CSV file has " + str(len(pd.read_csv(config.masterScoreCSV, nrows=1).columns)) + " columns.") elif not (scoreDF.columns == pd.read_csv(config.masterScoreCSV, nrows=1).columns).all(): raise Exception("Columns and column order of dataframe and csv file do not match!!") else: scoreDF.to_csv(config.masterScoreCSV, mode='a', index=False, header=False) cleanupDupes(config.masterScoreCSV) return (bestOTFs, reconstructed, logFile, registeredFile, maxProj, scoreFile) def cleanupDupes(csvFile=config.masterScoreCSV): import pandas as pd df = pd.DataFrame.from_csv(csvFile) df.drop_duplicates().to_csv(csvFile) def batchRecon(directory, mode, **kwargs): for root, subdirs, files in os.walk(directory): for file in files: fullpath=os.path.join(root,file) if isRawSIMfile(fullpath): if mode=='optimal': print "Doing optimal reconstruction on file: %s" % file try: makeBestReconstruction(fullpath, **kwargs) except Exception as e: print 'Skipping file %s due to error %s' % (fullpath,e) elif mode=='single': print "Doing single reconstruction on file: %s" % file try: reconstructMulti(fullpath, **kwargs) except Exception as e: print 'Skipping file %s due to error %s' % (fullpath,e) else: raise ValueError('Mode %s in batchRecon function was not understood' % mode) return 0 return 1 <file_sep>/helpers.py import numpy as np import matplotlib.pyplot as plt def bestplane( array ): scores=[] for plane in range(array.shape[0]): im = array[plane] M,N = im.shape # M and N are dimensions of plane DH = np.zeros((M,N)) # pre allocate DH and DV of the same size as plane DV = np.zeros((M,N)) DV[:-2,:] = im[2:,:]-im[:-2,:] # all rows but the first two - all rows but the last two DH[:,:-2] = im[:,2:]-im[:,:-2] # all cols but the first two - all cols but the last two FM = np.maximum(DH, DV); # get the larger of each respective pixel from DV and DH scores.append(np.mean(np.power(FM,2))); #take the mean of the whole array return scores.index(np.max(scores)) # SIMcheck options # public boolean autoCutoff = true; // no noise cut-off? # public boolean manualCutoff = false; // manual noise cut-off? # public boolean applyWinFunc = false; // apply window function? # public boolean gammaMinMax = false; // show 32-bit gamma 0.2, min-max? # public boolean logDisplay = false; // show 8-bit log(Amp^2)? # public boolean autoScale = false; // re-scale FFT to mode->max? # // N.B. autoScale now *always*/only happens for log(Amp^2): TODO, tidy! # public boolean blurAndLUT = false; // blur & apply false color LUT? # public boolean showAxial = false; // show axial FFT? def getFFT(array, window=True, log=False, shifted=True): """Get FFT of array (2D or 3D), with optional hanning window.""" if window: han1=np.hanning(array.shape[-2]) han2=np.hanning(array.shape[-1]) F = np.fft.fft2(array*np.outer(han1,han2)) else: F = np.fft.fft2(array) if shifted: F = np.fft.fftshift(F) amp = np.log(np.power(np.abs(F),2)) if log else np.abs(F) phase = np.angle(shifted) return F, amp def showPlane(array, scale=(0,1), interp='nearest', cmap='gray'): """ Show a single image plan with autoscaling. optional scale tuple lets you set min/max scaling as a percentage of the min/max value in the image """ if len(array.shape)==2: ma = np.max(array) * scale[1] mi = np.min(array) * scale[0] plt.imshow(array, vmin = mi, vmax = ma, interpolation=interp, cmap=cmap) elif len(array.shape)==3: bp = bestplane(array) ma = np.max(array[bp]) * scale[1] mi = np.min(array[bp]) * scale[0] plt.imshow(array[bp], vmin = mi, vmax = ma, interpolation=interp, cmap=cmap) plt.show() def radial_profile(data, center=None): """Radial average plot, cenetered around image center, or provided center tuple.""" y, x = np.indices((data.shape)) if not center: center = tuple(np.floor(np.array(data.shape)/2)) r = np.sqrt((x - center[0])**2 + (y - center[1])**2) r = r.astype(np.int) tbin = np.bincount(r.ravel(), data.ravel()) nr = np.bincount(r.ravel()) radialprofile = tbin / nr return radialprofile def linecut(arr,p1=None,p2=None, width=1, show=False): """ Create linescan/linecut from point1 to point2 in an image. width affects the size of the line, and pixels across the width of the line will be averaged together """ if not p1: p1 = np.array(amp.shape)/2 # center spot if not p2: p2 = np.array(arr.shape)-1 # bottom right corner x0, y0 = p1 x1, y1 = p2 length = int(np.hypot(x1-x0, y1-y0)) Z=np.zeros((width,length)) for i in range(width): if i%2==0: x0i = x0 + i/2 y0i = y0 - i/2 x1i = x1 + i/2 y1i = y1 - i/2 else: x0i = x0 - (i+1)/2 y0i = y0 + (i+1)/2 x1i = x1 - (i+1)/2 y1i = y1 + (i+1)/2 x, y = np.linspace(x0i, x1i, length), np.linspace(y0i, y1i, length) for n in range(length): try: Z[i][n] = arr[int(x[n]), int(y[n])] if (x[n]>=0 and y[n]>=0) else np.nan except: Z[i][n] = np.nan zi = np.average(Z,0) if show: fig, axes = plt.subplots(nrows=2) axes[0].imshow(arr) axes[0].plot([x0, x1], [y0, y1], 'ro-', lw=width) axes[0].axis('image') axes[1].plot(zi) plt.show() return zi def makeRadial(vector): ''' take a list or 1-dimensional array and make a radial plot ''' size = np.array(vector).size x, y = np.meshgrid(np.arange(-size,size),np.arange(-size,size)) radialMap = 0.0 * x # easy way to get shape right, 0.0 necessary to make it floats r=np.arange(size) #this represents radial distance from origin r2 = r**2 # hypotenuse of x,y,r triangle ... x**2 + y**2 = r**2 xy2 = x**2 + y**2 # pythagorean theorem: distance of any (x,y) pixel from origin for ii in range(r.size): # for each pixel # lookup the frequency by distance from center radialMap[np.where(xy2 >= r2[ii])] = vector[ii] return radialMap # better way: def getIllumCoords(pixelSize, imwidth, spacing, angle, extend=1): ''' get the pixel coordinates in fourier space corresponding to a given line-spacing and illumination angle. (For evaluating artifact in a SIM reconstruction) use 'extend' to get coordinates farther from orign by a certain factor ''' # frequency as a function of distance from origin frequencies = np.fft.fftfreq(imwidth)[:imwidth/2] # this is the distance in pixels from the origin to the pixel that # represents the frequency of the spacing in the image kSpacing = np.searchsorted(frequencies/xPixelSize,2/spacing) # center coords x0=imwidth/2 y0=imwidth/2 xOff = kSpacing * np.cos(angle) * extend yOff = kSpacing * np.sin(angle) * extend artCoord1=(x0+xOff,y0+yOff) artCoord2=(x0-xOff,y0-yOff) return artCoord1,artCoord2 def croparound(arr, coord=None, cropsize=15): if not coord: [x,y]=np.array(arr.shape[-2:])/2 else: [x,y]=[int(i) for i in coord] if len(arr.shape)==2: cropped=arr[x-cropsize:x+cropsize+1,y-cropsize:y+cropsize+1] elif len(arr.shape)==3: cropped=arr[:, x-cropsize:x+cropsize+1,y-cropsize:y+cropsize+1] elif len(arr.shape)==4: cropped=arr[:,:, x-cropsize:x+cropsize+1,y-cropsize:y+cropsize+1] return cropped def twoD_Gaussian((x, y), amplitude, xo, yo, sigma_x, sigma_y, theta, offset): xo = float(xo) yo = float(yo) a = (np.cos(theta)**2)/(2*sigma_x**2) + (np.sin(theta)**2)/(2*sigma_y**2) b = -(np.sin(2*theta))/(4*sigma_x**2) + (np.sin(2*theta))/(4*sigma_y**2) c = (np.sin(theta)**2)/(2*sigma_x**2) + (np.cos(theta)**2)/(2*sigma_y**2) g = offset + amplitude*np.exp( - (a*((x-xo)**2) + 2*b*(x-xo)*(y-yo) + c*((y-yo)**2))) return g.ravel() def calcartifact(file, spacing=0.414635, angle=-0.80385, cropsize = 15): indat=Mrc.bindFile(file) dims=indat.shape xPixelSize=indat.Mrc.hdr.d[0] imwidth = dims[-1] Fstack,ampstack = getFFT(indat, shifted=True, log=True) coords = getIllumCoords(xPixelSize, imwidth, spacing, angle) cropped = croparound(ampstack,coords[1],cropsize) x = np.linspace(-cropsize, cropsize, 2*cropsize+1) y = np.linspace(-cropsize, cropsize, 2*cropsize+1) x, y = np.meshgrid(x, y) initial_guess = (1,0,0,10,10,0,20) if len(dims)==2: popt, pcov = opt.curve_fit(twoD_Gaussian, (x, y), cropped.ravel(), p0=initial_guess) return popt, pcov, cropped elif len(dims)==3: popts = [] pcovs = [] i=1 for n in cropped: try: popt, pcov = opt.curve_fit(twoD_Gaussian, (x, y), n.ravel(), p0=initial_guess) popts.append(popt) pcovs.append(pcov) except: popts.append([]) pcovs.append([]) return popts, pcovs, cropped #MATLAB CODE # def frc(in1,in2): # # take fft # ft1 = ft(in1); # ft2 = ft(in2); # # Compute fourier ring correlation curve # frc_num = real(radialsum(in1.*conj(in2))); # Numerator # in1 = abs(in1).^2; # in2 = abs(in2).^2; # frc_denom = sqrt(abs(radialsum(in1).*radialsum(in2))); # Denominator # frc_out = double(frc_num)./double(frc_denom); # FRC # frc_out(isnan(frc_out)) = 0; # Remove NaNs <file_sep>/todo.md <!-- features to add --> work on cleaning up and formatting response from update_status allow to create batch job for just image registration (tricky to decide which images) allow batch process for max projection only make regfile optional in gui (by selecting best one automatically) add option for "forced" channel registration (assuming similar intensity distribution in two channels) add options to channel registration calibration command make timepoints a string that can accept start:stop:step <!-- nice but low priority --> calculate more things for score dict... add more raw data indices to score, such as snr? max/min/mean? give more feedback on raw data to the user saturation check snr check bleaching check PSF check?? change cropsize box in gui to option box? -> make it a class OTF names in specific OTF tab might not need full path add fourier ring correlation when timelapse data available? * redo whole thing as Classes * rethink where stuff goes on configuration tab and others add more help consider using a smart regisatration file choice create dictionary of regisration files that knows waves, daves, et... add ability to subsection Z-divs auto background subtraction? <!-- bugs --> make it so that you don't have to hit cancel button after server fail prevent registration when only a single channel is selected in a multichannel file invalid switch for -nimm in makeotf when nimm!=1.515...
7ee15edc8f5c89463ceec8326e41c6d94fbb1b7f
[ "Markdown", "Python" ]
13
Python
tlambert03/otfsearch
ae4052ffb0a2e75eec03b3cfb4022a99839364ae
ed643455c26e772516d47a722e4427d2ab90fbf9
refs/heads/main
<repo_name>StrongerMyself/shop-wear<file_sep>/src/features/catalog/epics.ts import { RootEpic } from 'root-types' import { isActionOf } from 'typesafe-actions' import { from, of } from 'rxjs' import { catchError, filter, map, switchMap } from 'rxjs/operators' import { fetchCatalog } from './actions' export const fetchCatalogEpic: RootEpic = (action$, state$, { api }) => action$.pipe( filter(isActionOf(fetchCatalog.request)), switchMap(() => from(api.products.fetchList()) .pipe( map(fetchCatalog.success), catchError((message: string) => of(fetchCatalog.failure(message))) ) ) ) <file_sep>/src/features/catalog/actions.ts import { Product } from 'entity-types' import { createAsyncAction } from 'typesafe-actions' export const fetchCatalog = createAsyncAction( 'FETCH_CATALOG_REQUEST', 'FETCH_CATALOG_SUCCESS', 'FETCH_CATALOG_FAILTURE', )<void, Product[], string>(); <file_sep>/src/store/root-reducer.ts import { combineReducers } from 'redux' import catalog from '../features/catalog/reducer' export default combineReducers({ catalog, }) <file_sep>/src/store/root-action.ts import * as catalog from '../features/catalog/actions'; export default { catalog, };<file_sep>/src/store/store.ts import { createStore, applyMiddleware } from 'redux' import { createEpicMiddleware } from 'redux-observable' import { RootAction, RootState, RootService } from 'root-types' import { composeEnhancers } from './utils' import rootReducer from './root-reducer' import rootEpic from './root-epic' import services from '../services'; export const epicMiddleware = createEpicMiddleware< RootAction, RootAction, RootState, RootService >({ dependencies: services, }) const middlewares = [epicMiddleware] const enhancer = composeEnhancers(applyMiddleware(...middlewares)) const initialState = {} const store = createStore(rootReducer, initialState, enhancer) epicMiddleware.run(rootEpic) export default store <file_sep>/src/store/root-epic.ts import { combineEpics } from 'redux-observable' import * as catalogEpics from '../features/catalog/epics' export default combineEpics( ...Object.values(catalogEpics) ) <file_sep>/src/services/types.d.ts declare module 'root-types' { export type RootService = typeof import('./index').default; } declare module 'entity-types' { export interface Category { id: 1 title: string decription: string } export interface Product { id: 1 title: string price: number caregoryId: number decription: string } } <file_sep>/src/features/catalog/reducer.ts import { combineReducers } from 'redux' import { createReducer } from 'typesafe-actions' import { fetchCatalog } from './actions' const isLoading = createReducer(false as boolean) .handleAction([fetchCatalog.request], () => true) .handleAction( [fetchCatalog.success, fetchCatalog.failure], () => false ); const list = createReducer([]) .handleAction(fetchCatalog.success, (state, action) => action.payload) export default combineReducers({ isLoading, list, }) <file_sep>/docs/styleguide.md # Стиль разработки проекта - Название компонентов и их файлов именуются PascalCase, остальные файлы kebab-case ### Файловая структура - src - исходники приложения - src/components - общие простые компоненты - src/features - функциоанальность(фича) имеющая бизнес-логику - src/features/components - компоненты определенной функциональности - src/features/actions.ts - экшены хранилища от фичи - src/features/epics.ts - эпики (redux-observable) от фичи - src/features/reducer.ts - редьюсер хранилища от фичи - src/features/selector.ts - выборки данных из хранилища для фичи - src/routes - страницы - src/services/... - сервисы, запросы по сети - src/services/types.d.ts - конструктор сервисов в типы - src/store - хранилище приложения - src/store/root-action.ts - регистрация всех экшенов - src/store/root-epic.ts - регистрация всех эпиков - src/store/root-reducer.ts - регистрация всех редьюсеров - src/store/store - конструктор хранилища - src/store/types.d.ts - конструктор хранилища в типы - App.tsx - конструктор приложения - index.tsx - точка входа для бразера - index.sass - сброс общих стилей<file_sep>/src/features/catalog/selector.ts import { RootState } from 'root-types' export const getCatalog = (state: RootState) => state.catalog <file_sep>/README.md # Demo app: shop-wear ## Scripts - ```yarn``` install dependency - ```yarn dev``` run dev mode<file_sep>/src/store/types.d.ts import { Epic } from 'redux-observable'; import { StateType, ActionType } from 'typesafe-actions'; declare module 'typesafe-actions' { interface Types { RootAction: ActionType<typeof import('./root-action').default>; } } declare module 'root-types' { export type RootStore = StateType<typeof import('./store').default>; export type RootState = StateType<typeof import('./root-reducer').default>; export type RootAction = ActionType<typeof import('./root-action').default>; export type RootEpic = Epic<RootAction, RootAction, RootState> }
cdf2f3bee509285a37af1cad4e3b96c0fa116de5
[ "Markdown", "TypeScript" ]
12
TypeScript
StrongerMyself/shop-wear
026e43d3f3e78c1335f36e7afd360695005ef596
e5afdc1225ddd5c4a95cb0eb7d1343c5f4bf1a2d
refs/heads/master
<repo_name>sheepp91/HideAndSeek<file_sep>/HideAndSeekCaptureTheFlag_Take2/Assets/Scripts/ThirdPersonMovement.cs using UnityEngine; public class ThirdPersonMovement : MonoBehaviour { private const float STAND_SCALE = 1.0f; private const float CROUCH_SCALE = 0.5f; public CharacterController controller; public Transform cam; public float walkSpeed = 10; public float sprintSpeed = 15; public Transform playerModel; public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; public float gravity = -9.81f; private Vector3 velocity; bool isGrounded; public float jumpHeight = 3f; public float turnSmoothTime = 0.1f; private float turnSmoothVelocity; void Update() { CheckGrounded(); Move(); Jump(); Crouch(); } private void CheckGrounded() { isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if (isGrounded && velocity.y < 0) { velocity.y = -2f; } } private void Move() { float horizontal = Input.GetAxisRaw("Horizontal"); float vertical = Input.GetAxisRaw("Vertical"); Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized; if (direction.magnitude >= 0.1f) { float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y; float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime); transform.rotation = Quaternion.Euler(0f, angle, 0f); Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward; bool isSprinting = Input.GetKey(KeyCode.LeftShift) || Input.GetAxis("Sprint") > 0.5; float speed = isSprinting ? sprintSpeed : walkSpeed; controller.Move(moveDir.normalized * speed * Time.deltaTime); } } private void Jump() { if (Input.GetButtonDown("Jump") && isGrounded) { velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity); } velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); } private void Crouch() { bool isCrouching = Input.GetKey(KeyCode.LeftControl) || Input.GetButton("Crouch"); if (isCrouching) { Vector3 scale = playerModel.localScale; scale.y = CROUCH_SCALE; playerModel.localScale = scale; } else { Vector3 scale = playerModel.localScale; scale.y = STAND_SCALE; playerModel.localScale = scale; } } } <file_sep>/HideAndSeekCaptureTheFlag_Take2/Assets/Scripts/PlayerMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public Transform player; public Transform playerBase; public LayerMask Ignore; private MeshRenderer[] playerChildMeshes; void Start() { playerChildMeshes = GetComponentsInChildren<MeshRenderer>(); } void Update() { GameObject[] lightSources = GameObject.FindGameObjectsWithTag("MainLightSource"); CheckInvisible(lightSources); lightSources = GameObject.FindGameObjectsWithTag("LightSource"); CheckInvisible(lightSources); } private void CheckInvisible(GameObject[] lightSources) { RaycastHit hit; foreach (GameObject light in lightSources) { Vector3 directionToLight = light.transform.forward * -1; if (Physics.Raycast(playerBase.position, directionToLight, out hit, Mathf.Infinity, ~Ignore))//, 9)) { MakeVisible(false); } else { MakeVisible(true); } } } private void MakeVisible(bool shouldBeVisble) { foreach (MeshRenderer mr in playerChildMeshes) { mr.enabled = shouldBeVisble; } } }
ad0b2cc36cb8a02270b6d444fd46f9d8ee8169a0
[ "C#" ]
2
C#
sheepp91/HideAndSeek
4309efee1f0659b42561bcb6ee04fde2d7d2b7de
04e2a13b73b9ff684103625ab165f58bec38f8a1
refs/heads/master
<file_sep># -*- coding:utf-8 -*- from pymongo import MongoClient def insertData2Table(collectname,num,test_name,content): '''insert one data to collection''' connect=MongoClient() db = connect['LeetCode'] data = db[collectname] try: datum = { 'num' : num, 'test_name':test_name, 'content' :content } data.insert_one(datum) except: print u'数据存储失败,请检查数据格式' def queryMatrix(collectname,value): '''根据变量矩阵查询表''' try: connect=MongoClient() db = connect['LeetCode'] data = db[collectname] query_result = data.find_one({'test_name':value}) except: return return query_result<file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月27日 下午9:52:43 @author: yzw ''' import json import docx from LeetCode_test2 import reconfigurl from LeetCode_test2 import reconfig_solution from LeetCode_test2 import reconfig_pythonsulu from LeetCode_test2 import get_content import sys reload(sys) sys.setdefaultencoding('utf8') from database_leetcode import insertData2Table,queryMatrix with open('name_all.json','r') as f: data = json.load(f) f.close() name_list = [] doc = docx.Document() for x in data['stat_status_pairs']: s = x['stat']['question__title'] name_list.append(s) for i,l in enumerate(name_list[::-1]): ls =l.replace(' ','-') ls =ls.replace('(','') ls =ls.replace(')','') ls =ls.replace(',','') ls =ls.replace(' ','') ls = ls.replace("'",'') ls = ls.replace('`','') ls = ls.replace('---','-') judge = queryMatrix('LeetCode_solu1',l) if not judge : try: url = reconfig_solution(ls) tem_con =reconfig_pythonsulu(url) cont = tem_con[0] best_solu = tem_con[1] if cont!=0 : python_solution =get_content(cont) best_solution = get_content(best_solu) title = python_solution[0] code = python_solution[1] best_title = best_solution[0] best_code = best_solution[1] con1 ='Python_solution:'+'\n'+title.decode('UTF-8')+'\n'+code.decode('UTF-8')+'\n'+'Best_solution:'+'\n'+best_title.decode('UTF-8')+'\n'+ best_code.decode('UTF-8')+'\n' insertData2Table('LeetCode_solu1',i+1,l,con1) else: print('is 0') best_solution = get_content(best_solu) best_title = best_solution[0] best_code = best_solution[1] con2 = 'Best_solution:'+'\n'+best_title.decode('UTF-8')+'\n'+ best_code.decode('UTF-8')+'\n' insertData2Table('LeetCode_solu1',i+1,l,con2) except IndexError: print(ls,l) insertData2Table('LeetCode_solu1',i+1,l,0) print(i+1) <file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月27日 下午8:21:08 @author: yzw ''' a =u'class Solution:\u000D\u000A def twoSum(self, nums, target):\u000D\u000A \u0022\u0022\u0022\u000D\u000A :type nums: List[int]\u000D\u000A :type target: int\u000D\u000A :rtype: List[int]\u000D\u000A \u0022\u0022\u0022\u000D\u000A ' c =a.encode("UTF-8") '''with open('test.txt','w') as f: f.write(c) f.close()''' #print(c) a ='()1' a =a.replace('(', '') a =a.replace(')', '') #print(a) a = [2,4,8,3,2,3,1,8] a = reversed(a) for x in a: print(x) a ='Powx,-n' if ',' in a: print('dd') a = ('r`q') def main(): """ """ for atrr in [0,1,4,5,7]: print "attribute %d ------------------------------" % atrr for fore in [30,31,32,33,34,35,36,37]: for back in [40,41,42,43,44,45,46,47]: color = "\x1B[%d;%d;%dm" % (atrr,fore,back) print "%s %d-%d-%d\x1B[0m" % (color,atrr,fore,back), print "" if __name__ == "__main__": """ """ main() a = [1,0,3] a.pop(0) print(a)<file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月27日 下午9:52:43 @author: yzw ''' import json import docx from LeetCode_test2 import reconfigurl from LeetCode_test2 import reconfig_solution from LeetCode_test2 import reconfig_pythonsulu # encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8') with open('name_all.json','r') as f: data = json.load(f) f.close() name_list = [] doc = docx.Document() for x in data['stat_status_pairs']: s = x['stat']['question__title'] name_list.append(s) with open('leetcodeans.txt','w') as f: for i,l in enumerate(name_list[::-1]): ls =l.replace(' ','-') ls =ls.replace('(','') ls =ls.replace(')','') ls =ls.replace(',','') ls =ls.replace(' ','') ls = ls.replace("'",'') try: url = reconfig_solution(ls) tem_con =reconfig_pythonsulu(url) cont = tem_con[0] best_solu = tem_con[1] if cont[0]!=0 : con = str(i+1)+','+l+':\n'+'Python_solution:'+'\n'+cont[1].decode('UTF-8')+'\n'+cont[2].decode('UTF-8')+'\n' f.write(con) if cont[0]==0 and best_solu[0]!=0: con = str(i+1)+','+l+':\n'+'Best_solution:'+'\n'+best_solu[0].decode('UTF-8')+'\n'+best_solu[1].decode('UTF-8')+'\n' f.write(con) except IndexError: pass print(i+1) f.close() #doc.save('demo.docx') <file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月27日 下午9:52:43 @author: yzw ''' import json import docx import sys reload(sys) sys.setdefaultencoding('utf-8') doc = docx.Document() f=open('leetcode_solu1111.txt','r') for line in f.readlines(): data =unicode(line,'utf-8') try: if data.startswith('***'): #print'uu' con =data p=doc.add_paragraph() p.add_run(con).italic = True if data.startswith('Python_solution') or data.startswith('Best_solution'): con = data p=doc.add_paragraph() p.add_run(con).bold = True elif len(data)!=0 and not data.startswith('***'): #print(data) con = data doc.add_paragraph(con) except ValueError as e: print(data) f.close() doc.save('solu3.docx') <file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月28日 下午11:40:37 @author: yzw ''' from pymongo import MongoClient connect=MongoClient() collectname = 'LeetCode_solu1' db = connect['LeetCode'] data = db[collectname] import sys reload(sys) sys.setdefaultencoding('utf8') i = 0 with open('leetcode_solu1111.txt','w') as f: for x in data.find().sort("num"): if x['content'] !=0: con = '***'+str(x['num'])+','+x['test_name']+':\n'+x['content'].decode('utf-8')+'\n' f.write(con) i+=1 print(i) f.close()<file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月27日 下午9:52:43 @author: yzw ''' import json import docx from LeetCode_test2 import reconfigurl # encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8') from database_leetcode import insertData2Table,queryMatrix with open('name_all.json','r') as f: data = json.load(f) f.close() name_list = [] doc = docx.Document() for x in data['stat_status_pairs']: s = x['stat']['question__title'] name_list.append(s) for i,l in enumerate(name_list[::-1]): ls =l.replace(' ','-') ls =ls.replace('(','') ls =ls.replace(')','') ls =ls.replace(',','') ls =ls.replace(' ','') ls = ls.replace("'",'') ls = ls.replace("`",'') judge = queryMatrix('LeetCode_exe',l) if not judge: con = reconfigurl(ls).decode('UTF_8') if not con.startswith('Level up your'): insertData2Table('LeetCode_exe',i+1,l,con) else: print(i+1,l) print(i+1) <file_sep># -*- coding:utf-8 -*- ''' Created on 2016年10月9日 下午9:15:00 @author: yzw ''' from bs4 import BeautifulSoup from urlparse import urljoin import requests def reconfigurl(name): url = 'https://leetcode.com/problems/{}/#/description'.format(name) response = requests.get(url) html = BeautifulSoup(response.text) c = html.find('meta',attrs={'name':'description'}) c =str(c) d = replace_html(c) return d def reconfig_solution(name): url1 = 'https://leetcode.com/problems/{}/#/solutions'.format(name) response = requests.get(url1) html = BeautifulSoup(response.text) html = str(html) c1 = html.rfind('data-forumurl') c2 = html.rfind('data-notebbcid') d= html[c1:c2] d =d.split('=') d = d[1][1:-2] d2 ='{}/{}'.format(d,name) return d2 def reconfig_pythonsulu(url1): response = requests.get(url1) html = BeautifulSoup(response.text,"html.parser") d_temp = html.find_all('a', class_="permalink") python_url = [] total_url =[] for i,x in enumerate(d_temp): temp_url =d_temp[i]['href'] index_url = temp_url.rfind('/') temp_url = temp_url[:index_url] total_url.append(temp_url) if 'python' in temp_url: python_url.append(temp_url) try: url_python = 'https://discuss.leetcode.com{}'.format(python_url[0]) except: url_python = 0 best_url = 'https://discuss.leetcode.com{}'.format(total_url[0]) return url_python,best_url def get_content(part_url): response = requests.get(part_url) html = BeautifulSoup(response.text) title = html.title.string title = title.split('|')[0] try: code = html.code.string except AttributeError: code = 'None' return title,code def replace_html(s): s = s.replace('&quot;','"') s = s.replace('&amp;','&') s = s.replace('&lt;','<') s = s.replace('&gt;','>') s = s.replace('&nbsp;',' ') s = s.replace('&#8594;','→') s = s.replace(' - 361way.com','') s = s.replace('<meta content="','') s = s.replace("<meta content='" ,'') s = s.replace('" name="description"/>','') s = s.replace(' name="description"/>','') s = s.replace(' name="description"/>','') return s '''a =reconfig_solution('two-sum') parturl= reconfig_pythonsulu(a)[0] c =get_content(parturl) print(c)''' <file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月27日 下午9:52:43 @author: yzw ''' import json import docx import sys reload(sys) sys.setdefaultencoding('utf-8') doc = docx.Document() f=open('leetcode_database.txt','r') for line in f.readlines(): data=line.strip() data =unicode(data,'utf-8') try: if data == "'": data ='' if data.endswith('***:'): con =data doc.add_heading(con, level=1) doc.add_paragraph() if data.startswith('Example') or data.startswith('Note'): con = data p=doc.add_paragraph() p.add_run(con).bold = True elif len(data)!=0 and not data.endswith('***:'): con = data doc.add_paragraph(con) except ValueError as e: print(data) f.close() doc.save('exe.docx') <file_sep># -*- coding:utf-8 -*- ''' Created on 2017年6月27日 下午9:52:43 @author: yzw ''' import json import docx from LeetCode_test2 import reconfigurl # encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8') with open('name_all.json','r') as f: data = json.load(f) f.close() name_list = [] doc = docx.Document() for x in data['stat_status_pairs']: s = x['stat']['question__title'] name_list.append(s) with open('leetcode1.txt','w') as f: for i,l in enumerate(name_list[::-1]): ls =l.replace(' ','-') ls =ls.replace('(','') ls =ls.replace(')','') ls =ls.replace(',','') ls =ls.replace(' ','') ls = ls.replace("'",'') temp_con = reconfigurl(ls) if not temp_con.startwith('Level up your'): con = str(i+1)+','+l+':\n\n'+temp_con.decode('UTF-8')+'\n' f.write(con) print(i+1) f.close() #doc.save('demo.docx')
4dd4092acf3d1201e79414d5911380624ab641ed
[ "Python" ]
10
Python
hustpython/leetcodecrawler
67602bd68f250eb9e813d2f61b031464bf5cbd3a
c5ac30eb45775ed117b6555f3dbe149a598175a4
refs/heads/master
<repo_name>juancaser/hamradioph<file_sep>/_posts/2019-03-02-cignus-uv-85-hp-a-year-after-review.md --- title: "Cignus UV-85+ HP — A year after review" description: >- This was my EDC radio for three years because it is very portable and uses the same accessories which i already have. date: '2019-03-02T04:01:01.006Z' categories: "Reviews" thumbnail: https://cdn-images-1.medium.com/max/800/1*A_xXDd2W0LBAJVToCXGeEA.jpeg --- This is the first radio that I bought upon recommendation from a ham friend, I got this radio from a local Cignus dealer for a 2,500 pesos, I also bought a Cignus RH-771 dual band whip antenna. This was my EDC radio for three years because it is very portable and uses the same accessories which i already have. ![](https://cdn-images-1.medium.com/max/800/1*doPOoge0M1TZ4DGH5zHR7Q.png) ### First impression ![](https://cdn-images-1.medium.com/max/800/1*SODUGDiGASZQT2x-TYOFww.jpeg) Cignus UV-85 series They say first impression last, well it did in some way. This little radio closely resembles [Baofeng FF-12P (UV-5X)](https://hamgear.wordpress.com/2015/03/17/review-baofeng-ff-12p-uv-5x/), I’m not surprise since Cignus UV-82 is basically a rebranded OEM of famous Baofeng UV-5R. ![](https://cdn-images-1.medium.com/max/800/1*7XFX8ksDFitOefmEEJHCHA.jpeg) This particular version is HP means High Power, it claimed that it can transmit up to maximum of 8 watts. ### Specifications **Frequency range:** _\[TX\] 136–174MHz, 400–520MHz, \[RX\] 136–174MHz, 400–520MHz, 68–108MHz (FM Broadcast)_ **Channel Capacity:** _128 Channels_ **Channel Spacing:** _25KHz (wide band)12.5KHz (narrow band)_ **Sensitivity:** _≤0.25μV (wide band) ≤0.35μV (narrow band)_ **Operation Voltage:** _7.4V DC ±20%_ **Battery:** _1500mAh_ **Frequency step:** _2.5, 5, 6.25, 10, 12.5, 20, 25, 30 and 50KHz_ **Antenna:** _Antenna Connector: SMA-Female / Antenna Impedance: 50Ω_ **Accessory Connector:** _Kenwood 2 Pin Standard_ **Stability:** _±2.5ppm_ **Output power:** _8W / 5W / 1W_ **Audio Power Output:** _700mW/10%_ ### Accessories ![](https://cdn-images-1.medium.com/max/800/1*_uiIK3kWGBtoqg514scBlw.jpeg) Finding accessories for this one is quite easy since it is compatible with most accessories for UV-5 series except for battery. From speaker mic to antenna you can easily interchange them with other Chinese made radio this type. ### Performance Performance in transmit is good for its price, those extra transmit power is quite useful when propagation is not really good in your current location, though using high power would have drained your batter fast. However, the receiver of this radio is mediocre like most Chinese radio. UV-85+ can easily be over-modulated (bingi) if you connect it to an external antenna or you are located on an high RF traffic area. This is due to the design made by the manufacturer, they use [Direct Conversion receiver](/blogs/superheterodyne-vs-direct-conversion.html) in their system on chip (SoC). This drastically lowers the manufacturing cost since it doesn't need those bulky and expensive IF filter most branded expensive radio has. Battery life is also good, mine last for 4 days with casual use. However, I notice that the longer you use the radio in transmitting, the battery charger terminal gets warm to the point that you can actually feel that your hands are burning. ### Pros and Cons #### Pros * Cheap, value for money * Uses same accessories compatible with other Chinese radio * High Power, quite handy when you need more power to transmit * Good battery life * Support and warranty #### Cons * Uses direct conversion receiver, the means it can get easily over-modulated * Battery charger terminal gets how with prolong transmit * It says it can transmit 8w, well it doesn't on all frequency, but still it transmits above 5 watts ### Verdict Will I recommend this? if you’re looking for a starter radio I would certainly recommend this than Baofeng UV-5R or UV-82. Because those service warranty is quite handy one day. Apart from that I wouldn't recommend this for daily driver. You’ll better off getting those budget Yaesu radio which is technically same with most Chinese radio except they added some software based IF filter, may not as good as the hardware base but it’s an improvement. ![](https://cdn-images-1.medium.com/max/800/1*A_xXDd2W0LBAJVToCXGeEA.jpeg)<file_sep>/_posts/2019-02-23-wln-kd-c1-year-after-review.md --- title: WLN KD-C1 — Year after Review description: >- I have this little radio for more than a year now and I could certainly say it became my favorite that it is now my EDC radio. date: '2019-02-23T04:01:00.829Z' categories: 'Reviews' thumbnail: https://cdn-images-1.medium.com/max/800/1*hELxrCuo8VE8CoA4zoVa5w.png --- When this little thing came everybody is talking about it, it is small, compact and very loud. Nope its not the [Baofeng UV-3R+](https://medium.com/@hamph/baofeng-uv-3r-a-year-after-review-3aa0f99e3881), its WLN KD-C1. I have this little radio for more than a year now and I could certainly say it became my favorite that it is now my EDC radio. ![](https://cdn-images-1.medium.com/max/800/1*hELxrCuo8VE8CoA4zoVa5w.png) ### Specs ![](https://cdn-images-1.medium.com/max/800/1*aHlC3yjqeskv9Ty0GfnHaw.png) ### Experience ### Price Its dirt cheap really cheap. Nothing more to say but cheap! #### Battery life Impressive, mine last for 3 days without being turned off. The good is i can charge it using PC USB port, a feature that i wish other radio should have as well. ![](https://cdn-images-1.medium.com/max/800/1*xYSnoYk-urqisujvbQjv5g.jpeg) _This battery reminds me of the Nokia BL-5C which looks them same even the specs are almost the same, even the name :)._ #### Portability Portability is one of its selling point, the non-removable antenna is actually advantageous for portability since you don’t have to worry about breaking the antenna port. KD-C1 fits perfectly on my pocket. #### TX/RX Performance Transmit is mediocre cant say its good but i cant say its bad either. Truth is i rarely used it to transmit since we don’t have UHF repeater in my area. But i do use it for simplex with my family which really works but only on limited range like inside a building. Since this is a UHF radio if works well in built up areas. Receive audio is loud.. really loud, i’m not surprised since it uses a 1 watt speaker. For a radio this size its packs a punch and i guess thats one of the selling point. #### Pros and Cons Pros:  \- Small and portable \- Fixed antenna \- Good battery life \- Loud audio \- Cheap price \- You can use programming cable from Baofeng **Cons:** \- UHF (well you can actually put VHF but that would be limited by the antenna) \- Non field programmable, requires computer to program \- Audio is loud that sometimes its already annoying \- Brittle belt-clip ### Verdict Will i recommend this? certainly.<file_sep>/reviews.html --- layout: archive title: "Reviews" permalink: "/reviews" category: "Reviews" header: true description: >- Collection amateur radio tech reviews made by Ham Philippines or by other hams. ---<file_sep>/assets/js/scripts.js (function($){ $(document).ready(function(){ $('.post-content').find('img').each(function(){ var src = $(this).attr('src'); var title = $(this).attr('alt'); $(this).wrap('<a data-fancybox="gallery" class="post-content-image shadow" href="' + src + '" data-caption="' + title + '" title="' + title + '"></a>'); var box = $(this).parent('.post-content-image'); box.wrap('<figure></figure>') box.parent('figure').append('<figcaption>' + title + '</figcaption>'); if($(this).width() > $('.post-content').width()){ $(this).css('width','95%'); } }); }); })(jQuery); window.onscroll = function () { var rect = document.getElementById('comments').getBoundingClientRect(); if (rect.top < window.innerHeight) { var js = document.createElement('script'); js.src = '//connect.facebook.net/en_US/sdk.js#xfbml=1&appId=822714894740746&version=v3.2&autoLogAppEvents=1'; document.body.appendChild(js); window.onscroll = null; } }<file_sep>/_posts/2019-02-12-swr-for-dummies.md --- title: SWR for Dummies description: >- Once you have setup your external antenna, you are most likely heard about antenna tuning and SWR. date: '2019-02-12T07:01:00.886Z' categories: 'Blogs' thumbnail: https://cdn-images-1.medium.com/max/800/1*AXq63Q6Yx5SNc3sB1VUsbw.jpeg --- ![](https://cdn-images-1.medium.com/max/800/1*AXq63Q6Yx5SNc3sB1VUsbw.jpeg) Once you have setup your external antenna, you are most likely heard about antenna tuning and SWR. SWR stands for _Standing Wave Ratio_, its the ratio of how much output power reaches the antenna against what is reflected back. When the output power is impeded the waves is called **standing**, it means they are not radiated the way it supposed to. A low SWR reading means your antenna is transmitting a proper amount of RF power instead of sending the excess power it back into your transmitter. The idea of SWR reading is making sure your antenna will have lower SWR reading to avoid damaging your transmitters. When you have high SWR reading that means your antenna has low RF power and the rest is sent back through the feed line and back into the radio. This will results into your signals being weak and distorted. Or worst all those excess power return to your radio will damage the transmitter. ### Interpreting SWR reading Tuning your antenna to an acceptable SWR is very crucial for good performance and safety of your transmitter. Below are some guidelines to give you and idea about it. ### 1.0–1.5 This is the ideal range, if your SWR is < 1.5 that means you antenna is properly tuned. However if you are ≥ 1.5 you may want to drop it down a little bit more. Tuning antenna may differ from case to case. Sometimes cutting the antenna elements may solve this, or adding a coil to the feed line. Dropping from 1.5 to 1.0 may not have any noticeable difference but it would surely make sure you transmitter is happy. Not as noticeable as going from 2.0 to 1.5. ### 1.5–1.9 At this range should still be able to provide adequate performance. If you get this reading try moving you antenna position. Sometimes adding some coil to the feed line may solve improve the reading. ### 2.0–2.4 This is not really an ideal reading, while it will not likely damaged your radio for casual use, for regular rag chewing it will. ### 3.0+ Performance at this level is severely affected and most like you radio is damaged. **NOTE:** The damage to your radio will only happen if you transmit from an antenna with high SWR readings.<file_sep>/_includes/sidebar.html {% if page.is_post %} {% include sidebar/related-posts.html %} {% endif %} {% include sidebar/categories.html %} {% include sidebar/about.html %} {% include sidebar/social.html %}<file_sep>/_posts/2019-02-16-baofeng-uv-3r-a-year-after-review.md --- title: Baofeng UV-3R+ — a Year after Review description: >- Small ultra portable dual band radio that is cheap and it works. date: '2019-02-16T04:01:00.858Z' categories: 'Reviews' thumbnail: https://cdn-images-1.medium.com/max/800/1*WKLYJOc7ID36Aq1qttfvoQ.jpeg --- ![](https://cdn-images-1.medium.com/max/800/1*WKLYJOc7ID36Aq1qttfvoQ.jpeg) Way back December 2016 on our club Christmas party, one of the price is a small radio. I was so curious since it is very small and portable. After searching for couple days i stumble upon Baofeng UV-3R. Thats where i started digging into this portable radio more. Baofeng UV-3R is a copy of Yaesu VX-3R. After a year they released UV-3R Mk II with little changes to the original one. ![](https://cdn-images-1.medium.com/max/800/1*5RQAhZoyUcvLjIM1BpCgDw.png) Baofeng UV-3R MK I and Yaesu VX-3R Soon after the release of Mk II they released the latest and probably the last iteration of the UV-3R series, the UV-3R+ ![](https://cdn-images-1.medium.com/max/800/1*Q6wmb0HzNmMbG0omHD-Z2A.jpeg) Baofeng UV-3R series. Left to Right, MK I, II and Plus ### Specs ![](https://cdn-images-1.medium.com/max/800/1*LkYcioU8q7NkoISjKdnflQ.png) Baofeng UV-3R+ is a complete redesign of its aesthetics, it doesnt resemble VX-3R anymore. It also uses a more updated firmware than the one from Mk I and II. Size and portability is the selling point of the UV-3R series, but due to its small there are some compromise on its features _(I know there are more but this are the ones that i experienced personally)_: * It doesn't support channel naming * It doesn't have a keypad to typed the frequency, you need to do it from the single VFO/Volume/Control knob which is sometimes it is fiddly. * Changing the frequency could be hassle sometimes if not all the time. * You are limited to 4 buttons to operate. * Audio is still loud even if the volume is already set low. * Hard to find battery replacement But with its cons comes its pros as well: * Portability, perfect for EDC. * Commonality with other Baofeng parts like antenna, programming cable and speaker mic. * You can actually used Sony digital camera battery as alternative, but may require some modification. * Good TX even if it only transmit less than 2W. ### Experience #### Price Its quite cheap actually, got mine for one thousand three hundred pesos (Php 1,300) from my local dealer (thats a price of new model that came out just a month), and i know the price could get lower depending on where you get it or who is selling it. #### Battery life I have been using my UV-3R+ as my EDC (Everyday Carry) for more than 2 years already, the only issues i have is the battery since it gets drained so fast. I normally use it for monitoring only so the battery takes couple days before it gets drained but if use it for TX it gets drained after a single day. Battery life is not really its strong point so i suggest getting a spare battery just in case, and the charger may require some careful use, mine is broken after a week. It still charges though just needed some careful push on the cable. ![](https://cdn-images-1.medium.com/max/800/1*WKLYJOc7ID36Aq1qttfvoQ.jpeg) _Baofeng UV-3R+ with stock antenna and battery_ #### Portability It is also comfortable to use, i can easily put it in my EDC bag or just on my pocket it fits perfectly. I usually used scanner antenna since i just monitor most of the time. The antenna is SMA-Female so you can interchanged it with any Baofeng antenna you already have. Just word of caution though if you are planning to TX, [always make sure to do SWR reading on the antenna before using it, if the SWR reading is high it could damage the finals of your radio. 1.0–1.5 is the ideal range.](https://medium.com/@hamph/swr-for-dummies-830f09855f95) ![](https://cdn-images-1.medium.com/max/800/1*sBpD4FcBeCJwqYekmEohTw.jpeg) _WLN KD-C1 and Baofeng UV-3R+_ #### TX/RX Performance Well i don't expect it to perform well on TX since it has limited transmit power (< 2W). You could still transmit though using the stock antenna and transmitting it into a repeater. In UHF where the 3R+ shines more, VHF not really much. However, RX is excellent, i use a scanner antenna so it is really small and i can easily pick up transmission from our local traffic agency. Since i’m usually located in an area where there is high RF noise i’m really surprise that it still have a decent RX. ![](https://cdn-images-1.medium.com/max/800/1*pVwIK4AGRmtrfICK8v8Khg.jpeg) _SMA-F antenna that i used with UV-3R+ and all my SMA-F typed radios. (Left to Right) Bullet antenna, Short stubby antenna, Flexible stubby antenna, Stock antenna, Long stock antenna._ ### Verdict So the verdict, will i recommend it? depends on the purpose. If you are planning to use it for monitoring and transmitting it to a nearby repeater, then YES i would recommend this. But if you want it to use for regular transmitting i may recommend other radio instead since this little radio is not really a top performer in terms of transmit, it transmit lesser than what it claims (2W) so not really much of a coverage and range. <file_sep>/_posts/2019-02-17-superheterodyne-vs-direct-conversion.md --- title: Superheterodyne vs Direct-Conversion description: >- Due to the increase of cheap Chinese radio a lot of people had been complaining that their receiver had been over modulated. date: '2019-02-17T04:01:00.694Z' thumbnail: https://cdn-images-1.medium.com/max/800/1*QRdijMeMYnNT3ZYGGhcbvQ.jpeg categories: 'Blogs' --- Due to the increase of cheap Chinese radio a lot of people had been complaining that their receiver had been over modulated (bingi) if they connect it to an external antenna. Over-modulation is a condition where there is a high level of modulating (transmitting) signal exceed the value necessary to produce 100% modulation of the carrier. It means you won’t be able to hear the other station because your receiver cannot filter all the modulating signal transmitted from other radio, even if they are transmitting on different frequency. ### What is a Superheterodyne receiver? The superheterodyne receiver or superhet, was invented in 1917, it is a type of receiver that uses frequency mixing to convert the received signal to a fixed intermediate frequency (IF) which can be easily process. Intermediate Frequency (IF) is a frequency to which a carrier wave is shifted as an intermediate step in transmission or reception. The basic principle is to convert a RF signals to an intermediate frequency (IF) by mixing a tunable local oscillator (LO) with incoming signals (_see Figure 1_). A fixed-frequency narrow-channel filter is applied at the mixer output, then followed by most of the receiver’s gain and demodulation. RF filters are placed before and after the LNA stage. ![Figure 1. Block diagram of a superheterodyne receiver.](https://cdn-images-1.medium.com/max/800/1*pMvVR-mk7_SWtqKPWseaSw.png) The benefits of a superhet are enormous and sometimes it outweighs the cost. Most of the filtering and gain takes place at one fixed frequency rather than requiring a tunable high-Q band pass filters. However, the cost and size of IF filters is still expensive to budget conscious manufacturer hence modern cheap transceiver nowadays either have Low-IF or Direct-Conversion receiver. ### What is a Low-IF receiver? Technically it is still superheterodyne, however the cost and size of IF component matters to some designers that they reduced the components of that bulky and expensive IF filters. The advantage over High-IF superhet is that the gain and filtering are done at a lower frequency, this reduces the power it uses thus making it possible to use on-chip components which in turns reducing the size and cost. The disadvantage of a near zero-IF is that the receiver’s polyphase filters require more components than an equivalent low-pass filter used in a direct-conversion filter. Another is the image cancellation is dependent on the LO quadrature accuracy which may vary with process variations and temperature changes. ### What is a Direct-Conversion receiver? Direct-Conversion receiver or homodyne, synchrodyne, or zero-IF receiver, is a type radio receiver where the local oscillator (LO) is set to the same frequency as the desired RF channel, that means the IF is zero or dc. The filtering and gain can take place at dc where gain is easier to achieve with low power and filter can be accomplished with on-chip resistors and capacitors instead of bulky surface-acoustic wave (SAW) filters. (_see Figure 2_) ![Figure 2. Block diagram of Direct-conversion receiver](https://cdn-images-1.medium.com/max/800/1*3ph9WifjnZDgwRifqLjYrw.png) ### Which one is better? So which is better? Depends on your needs, so which one is good for? **Superheterodyne** Suited for people who want radio with good filters, with this filter comes at a high price and I mean literally high price. Most superhet radios are expensive. **Direct-conversion** Direct-conversion is cheap and I mean dirt chip. Most Chinese radio uses RDA1486 system on chip (SOC) which basically do all the transceiver functions which made the manufacturing cheaper and smaller, at the expense of filters. ### The Future Direct-conversion is the future, it has still a long way to go but it’s going there anyway. The technology on Digital signal processing is also improving so that means we will have some direct-conversion radio in the future that is cheap but can perform similar to the superhet. ### Notes… So the next time you connect your Chinese radio into an external antenna, take time to do some propagation testing, see if your area has high RF traffic. If it does, I suggest getting a good radio with good filter. It will be expensive but it would surely give you peace of mind that every time you press that PTT your signal will always get through or you receive those important traffic. <file_sep>/README.md --- layout: post title: "About" permalink: /about.html --- __{{ site.title }}__ is an open source project of Ham Philippines in collaboration with _[<NAME>, DW7LFU](http://www.nopoweb.com)_ who developed the site.<file_sep>/_includes/card/featured.html <div class="post card flex-md-row mb-4 box-shadow h-md-250"> <div class="card-body d-flex flex-column align-items-start"> {% if post.categories.size > 1 %} {% assign tags = post.categories | shift %} {% else %} {% assign tags = post.categories %} {% endif %} <strong class="post-tags d-inline-block mb-1 text-primary">{{ tags }}</strong> <h3 class="post-title mb-0"> <a class="text-dark" href="{{ post.url }}">{{ post.title }}</a> </h3> <div class="post-date mt-1 mb-2">{{ post.date | date: "%-d %b %Y" }}</div> <div class="post-content card-text mb-auto"> <p> {% if post.description.size > site.excerpt_max.featured %} {{ post.description | slice: 0, site.excerpt_max.featured }}... {% else %} {{ post.description }} {% endif %} </p> </div> <a class="post-more btn-sm btn btn-outline-danger" href="{{ post.url }}">Continue reading</a> </div> {% if post.thumbnail %} {% assign thumbnail = post.thumbnail %} {% else %} {% assign thumbnail = '/assets/img/post.png' %} {% endif %} <div class="post-image card-img-right flex-auto d-none d-md-block"> <img class="" alt="{{ post.title }}" style="width: 200px; height: 250px;" src="{{ thumbnail }}" /> </div> </div> <!-- <div class="post-card bg-light mb-4"> <div class="row no-gutter"> <div class="post-image float-md-right col-md-5 col-sm-12 col-xs-12 bg-dark align-center"> {% if post.thumbnail %} {% assign thumbnail = post.thumbnail %} {% else %} {% assign thumbnail = '/assets/img/post.png' %} {% endif %} <img src="{{ thumbnail }}" alt="{{ post.title }}" title="{{ post.title }}" /> </div> <div class="p-4 post-meta float-md-left col-md-7 col-sm-12 col-xs-12"> <h3 class="post-title mb-4"> <a class="text-dark" href="{{ post.url }}" title="{{ post.title }}"> {% if post.title.size > 30 %} {{ post.title | slice: 0, 30 }}... {% else %} {{ post.title }} {% endif %} </a> </h3> <a href="{{ post.url }}">Continue reading</a> </div> </div> </div> --><file_sep>/_posts/2019-02-24-how-i-become-a-ham.md --- title: How i become a Ham description: >- Ham is not a processed meat, it’s a person who is skilled in the Amateur Radio. date: '2019-02-24T04:41:15.399Z' thumbnail: https://cdn-images-1.medium.com/max/800/1*cT-r0GUgJ3XI_Mwj758JAg.jpeg categories: 'Blogs' --- > Ham is not a processed meat, it’s a person who is skilled in the Amateur Radio. My first encounter with radio goes way back to early 90's when i was still living in a rural community in Northern Mindanao _(CARAGA)_, the place is not that remote but there is no phone or cellphone _(cellphone that time is expensive and bulky)_, our neighbor who’s mom is a member of local civic-communication group called REACT. ![View of Lake Mainit from Kitcharao, Agusan del Norte side.](https://cdn-images-1.medium.com/max/800/1*1RGavEgpR1U6gnOWyEdXsw.jpeg) Actually, i have known about radio before that but never got me interested with it, maybe the closest one that got me interested is when i get a hold on a toy walkie talkie which i eventually dismantled out of curiosity on how it works, that was like 6 years before i moved to Mindanao. Every afternoon or weekend i always go to my friend’s house to play with the radio, we always climbed on the roof and started scanning the frequency. Back then our interest was still not about the radio but to look for a YL _(young lady),_ we were boys then so its not really a surprise at that age. We do manage to talk some YL from time to time, we spend the whole afternoon taking turns in talking to the YL on the other line. It was fun, we meet some friends. When my friend became a member of REACT kids _(mostly kids of older member)_, and it got me interested what is it about this radio thing beside as means to communicate? I saw him doing civic work with his mom during a town event, and it got more curious as to what they are doing. When i asked my friend how to joined he told me either one of my parent should be a member. I felt disappointed because i can’t join, every time i saw my friend on every town event i felt envious and disappointed. When we move back to Cebu i never forgot about it even after more than 10 years since i learned about it. When i’m back in my home town _(yes, i’m from cebu originally)_ i’m already working and earning some money already i attempted to join a civic communication group. It didn't worked well, since at that time i still believe that radio is still expensive, despite i’m already earning is still not an option for me, and the group i inquired never replied to me. So i just move forward thinking that i will never be into this, maybe its not really for me. Or is it? ![More like, 5 years!](https://cdn-images-1.medium.com/max/800/1*e83emQWsUM-om3tq9ZHq7Q.jpeg) I was able to see an old friend Ariel from a previous company where i used to work, he is carrying a portable radio. I quickly asked him about it, and he said he is a licensed amateur radio operator or ham and he holds a licensed with a call sign of _DW7FAL (he is now DV7FAL)._ I told him about my story about radio and he invited me to join their club, Ham Radio Cebu (DX7CBU). That time i never think twice and immediately grab the opportunity. ![My club Ham Radio Cebu (DX7CBU)](https://cdn-images-1.medium.com/max/800/1*8cf6oW-I7Z4ONCsPhwijDA.jpeg) During this time i have no idea what is amateur radio nor even bother to google it, maybe i’m just hyped up that now i got a chance to become something that i wasn't able to do 20 years ago. He even suggested me a certain brand of radio which to my surprised its cheaper than i expected. I always have the notion that portable radio is still expensive since thats what i remember during the time when i’m so interested about it, maybe it got stuck on my that it never rubs off. I bought my first portable radio, it was a Cignus UV-85+ HP and a whip antenna, despite that i don’t have proper orientation yet _(the DX7CBU orientation is still on the weekend)._ The club president give me a temporary callsign 7HCJ _(originally it was 7HJC but was later changed due to conflict with another member call sign)._ I did a signal check to the DX7CBU repeater using only stock knowledge on how to operate a radio. I remember Ralph _(DV7MJL)_ responded to me, but somehow my signal is not propagating properly. ![](https://cdn-images-1.medium.com/max/800/1*kT2DUSyf58sBf1Ad6CMAxg.png) > I just focus on something that i’m sure ill pass, then ill worry the others later… — Me ### The moment of truth… Exam, day i reviewed for couple days, i keep my expectation low so i don’t get disappointed, i focused on Element 2 Radio Laws since i’m sure i can pass this one. However, for element 3 and 4 somehow i’m a bit skeptic since it includes numbers and calculations i don’t really do well with this _(despite that i have the same course back in college)._ I failed 3 and 4 but pass element 2, now i’m officially an amateur holding a Class D license with a call sign of DY7LFU. ![](https://cdn-images-1.medium.com/max/800/1*qtkKJrjuIf1iHAGnTYs5ZA.jpeg) > Not stopping until i’m Class A — me saying this to our club president Jet (4F7MHZ)… ### Worrying the later…. Remember last time i said i’ll focus on what i can pass and worry the later, well this is the time to worry the later, i take almost all opportunity to take the exam and upgrade my license, even to the point that i have to go the other province and travel overnight so i can take an exam. Me and my good friend Nick _(DW7FCC at this time now DU7FCC)_ went to Dumaguete City to take amateur exam despite during that time Dumaguete City is now separate from Region 7 NTC _(they Negros Island Region at that time and under NTC Bacolod)._ ### The Island hoping adventure.. Taking that exam on other province was fun, exciting and rewarding. Because its a good example for everyone that when you have the will you can always find a way. We left Cebu Friday, 7 PM and we arrive their 3 AM despite the lack sleep we persist, with no shower and rice porridge as our breakfast we move forward and go to the exam area. ### Class C, finally… ![](https://cdn-images-1.medium.com/max/800/1*dmVJVknEfBY7zwXcUC43GQ.jpeg) Alas, i pass the exam now i’m officially Class C with the call sign of DW7LFU. ![](https://cdn-images-1.medium.com/max/800/1*CVg-tQ9tlYVRVrvW3sc_Qg.jpeg) Beside from passing the exam, i met some friends there. ![Me, Nick with CUERA](https://cdn-images-1.medium.com/max/800/1*tq1Vl9GbE7jeMEOMVS84Zg.jpeg) ### Keep moving I move forward and upgrade to Class B only this time i failed twice _(i failed twice as well when i upgrade to Class C),_ partly because i was too busy on my day job that i don’t find any time anymore to review, nonetheless i still take the exam because its a passion _(i know reviewing is not really my thing, i learned from experiencing it personally, and not much of academics)._ ### Re-think and re-consider… I’m already strike 2, so i decided and reconsider maybe i need more experience and i should practice being ham more than just read those reviewer. I’m still gonna take the exam this year, but i made sure this time that i will gain experienced by immersing myself on the hobby more than ever before. Educating other people is my way of doing it, i immerse myself to the hobby, so i can be an effective educator to others. ### Educator… I always consider myself as an educator, i love teaching other people get them informed. Recently i’m into educating scouts for JOTA and for their radio badge. I enjoy it a lot, thats where i found my calling… i’m an educator. ![](https://cdn-images-1.medium.com/max/800/1*HGyKMhqQAMfioa_DrIpOcA.jpeg) ### Today… Focusing on my advocacy to educate other people about ham radio, i became active on my once dormant facebook page Ham Philippines. I started creating original content that helps educating people about the hobby. I will continue to do so until i can still do it. ### Why i’m a ham? I love technology, apart from that i love talking to people from far away. I know i can achieve that through modern technology like Internet i just don’t feel complete. So, i combined the best of this world. ![](https://cdn-images-1.medium.com/max/800/1*bLMS_dywvNs2sq6kJiXwNg.jpeg) ### Future I will continue to educate people, and hope that more people like me would do as well. I will try to encourage them. Things that i do really… ![](https://cdn-images-1.medium.com/max/800/1*o7OKJUsng_SJRgcMp-A_DQ.jpeg) ![](https://cdn-images-1.medium.com/max/800/1*D_zcRXTnrnwBgeia4rLSuw.jpeg) ![](https://cdn-images-1.medium.com/max/800/1*MRaWE_mkskbU7XXr1R7UMQ.jpeg) ![](https://cdn-images-1.medium.com/max/800/1*o_nICJx4Td1jgdCsqiquRA.jpeg) ![](https://cdn-images-1.medium.com/max/800/1*6HKMGkbGVsrB4xd3Zcc-KA.jpeg) ![](https://cdn-images-1.medium.com/max/800/1*APXTvcw6hs0j_wRi6ShdsQ.jpeg) ![](https://cdn-images-1.medium.com/max/800/1*YO91qQAMMuQTa4Gzsh-chA.jpeg) ![](https://cdn-images-1.medium.com/max/800/1*cT-r0GUgJ3XI_Mwj758JAg.jpeg)
5a96fa2229e1fa853dd73c9417fc5c0c5b93e0a6
[ "Markdown", "JavaScript", "HTML" ]
11
Markdown
juancaser/hamradioph
48ea7df6da8b53bb2400570fb16a3c7e97146374
d06df9eaf83f55e623ac62ee34c9587b6c44c7f4
refs/heads/main
<file_sep>let canvas=document.querySelector('canvas'); let width=900; let height=500; let score=0; let apple=new Image(); apple.src='apple.png'; // console.log(apple); let gameover_sound=new Audio('sound/game_over.mp3'); let score_sound=new Audio('sound/snake.mp3'); canvas.width=width; canvas.height=height; let speed=100; let ctx=canvas.getContext('2d'); let ctx_2=canvas.getContext('2d'); // ctx_2.fillRect(0,0,50,50); // ctx_2.drawImage(apple.src,0,0); let unit=20; ctx.fillStyle='green'; // constructor function pos(x,y) { this.x=x; this.y=y; } let pos_x=Math.floor(Math.random()*700); let pos_y=Math.floor(Math.random()*550); pos_x-=pos_x%unit; pos_y-=pos_y%unit; let fruit_x,fruit_y; let snake=[]; for(let i=0;i<=4;i++) { snake.push(new pos(pos_x,pos_y)); pos_x+=unit; // pos_y+=unit; // console.log(snake); } show(); show_fruit(); // apple.onload=() => ctx_2.drawImage(apple,fruit_x,fruit_y,20,20); window.addEventListener('keydown',arrow); let my_req; let turn='false'; let play=true; function arrow(event){ // console.log(event.code); let key=event.code; let num=event.keyCode; console.log(num); if(play){ if((key=='KeyW' || num==38) && turn!='down') { turn='up'; clearInterval(my_req); my_req=setInterval(up,speed); // apple.onload=() => { my_req=setInterval(up,speed);} // up(); } else if((key=='KeyS' || num==40) && turn!='up') { turn='down'; clearInterval(my_req); // apple.onload=() => { my_req=setInterval(up,speed);} my_req=setInterval(down,speed); // down(); } else if((key=='KeyD' || num==39) && turn !='left') { turn='right'; clearInterval(my_req); // apple.onload=() => { my_req=setInterval(up,speed);} my_req=setInterval(right,speed); // right(); } else if((key=='KeyA' || num==37) && turn!='right') { turn='left'; clearInterval(my_req); // apple.onload=() => { my_req=setInterval(up,speed);} my_req=setInterval(left,speed); // left(); } } } function show(){ ctx.fillStyle='green'; let i=0; for(i=0;i<snake.length;i++) { ctx.fillRect(snake[i].x,snake[i].y,20,20); ctx.strokeStyle='cornsilk'; ctx.strokeRect(snake[i].x,snake[i].y,20,20); } } function show_fruit() { // apple.onload=() => { // ctx.drawImage(apple) ctx_2.fillStyle='black'; fruit_x=Math.floor(Math.random()*700); fruit_y=Math.floor(Math.random()*550); fruit_x-=fruit_x%unit; fruit_y-=fruit_y%unit; ctx_2.fillRect(fruit_x,fruit_y,20,20); // ctx_2.drawImage(apple,fruit_x,fruit_y,20,20); //} } // apple.onload=() => setInterval(show_fruit,200); function update_score() { score_sound.play(); let doc=document.querySelector('#score'); doc.innerHTML=score; } function game_over() { // console.log(snake); gameover_sound.play(); let doc=document.querySelector('#gameover'); doc.innerHTML='GAME OVER <br> Restart to Play Again'; let body=document.querySelector('body'); body.style.backgroundColor='black'; let message=document.getElementsByTagName("h1"); // console.log(message); for(let i=0;i<message.length;i++) message[i].style.color='red'; } function up() { let last=snake[snake.length-1]; let tmp=new pos(last.x,last.y-unit); check(tmp) if((snake[snake.length-1].y-unit)<0) { // console.log(tmp); play=false; game_over(); clearInterval(my_req); } else { let first=snake[0]; snake.shift(); // let last=snake[snake.length-1]; snake.push(new pos(last.x,last.y-unit)); last=snake[snake.length-1]; if(last.x==fruit_x && last.y==fruit_y) { score+=1; snake.unshift(first); update_score(); // apple.onload=() => show_fruit(); while(check_fruit(fruit_x,fruit_y)) { show_fruit(); } // ctx_2.drawImage(apple,fruit_x,fruit_y,20,20); } else{ ctx.clearRect(first.x,first.y,20,20); // ctx.strokeStyle='' // ctx.strokeRect(first.x,first.y,20,20); } show(); } // console.log('UP'); } function down() { let last=snake[snake.length-1]; let tmp=new pos(last.x,last.y+unit); check(tmp); // last.y+=unit; // console.log(snake[snake.length-1]); if(snake[snake.length-1].y+unit>=height) { play=false; game_over(); clearInterval(my_req); } else { let first=snake[0]; snake.shift(); snake.push(new pos(last.x,last.y+unit)); last=snake[snake.length-1]; if(last.x==fruit_x && last.y==fruit_y) { score+=1; update_score(); snake.unshift(first); // apple.onload= show_fruit(); while(check_fruit(fruit_x,fruit_y)) { show_fruit(); } // apple.onload=() => ctx_2.drawImage(apple,fruit_x,fruit_y,20,20); } else{ ctx.clearRect(first.x,first.y,20,20); } show(); } // console.log('DOWN'); } function right() { let last=snake[snake.length-1]; let tmp=new pos(last.x+unit,last.y); check(tmp); // last.x+=unit; if(snake[snake.length-1].x+unit>=width) { play=false; game_over(); clearInterval(my_req); } else { // console.log('RIGHT'); let first=snake[0]; snake.shift(); snake.push(new pos(last.x+unit,last.y)); last=snake[snake.length-1]; if(last.x==fruit_x && last.y==fruit_y) { score+=1; update_score(); snake.unshift(first); // apple.onload= show_fruit(); while(check_fruit(fruit_x,fruit_y)) { show_fruit(); } // apple.onload=() => ctx_2.drawImage(apple,fruit_x,fruit_y,20,20); } else{ ctx.clearRect(first.x,first.y,20,20); } show(); } } function left() { let last=snake[snake.length-1]; let tmp=new pos(last.x-unit,last.y); check(tmp); // last.x-=unit; if((snake[snake.length-1].x-unit)<0) { play=false; game_over(); clearInterval(my_req); } else { let first=snake[0]; snake.shift(); snake.push(new pos(last.x-unit,last.y)); last=snake[snake.length-1]; if(last.x==fruit_x && last.y==fruit_y) { score+=1; update_score(); snake.unshift(first); // apple.onload= show_fruit(); while(check_fruit(fruit_x,fruit_y)) { show_fruit(); } // apple.onload=() => ctx_2.drawImage(apple,fruit_x,fruit_y,20,20); } else{ ctx.clearRect(first.x,first.y,20,20); } show(); } // console.log('LEFT'); } function check_fruit(m,n) { for(let i=0;i<snake.length;i++) { if(snake[i].x==m && snake[i].y==n) { return true; } } return false; } function check(node){ let flag=0; for(let i=0;i<snake.length;i++) { if(snake[i].x==node.x && snake[i].y==node.y) { flag=1; break; } } if(flag) { play=false; game_over(); clearInterval(my_req); } } <file_sep># Snake_game Basic Snake Game key Binding for movement 1> for UP -> W / UP arrow 2> for DOWN -> S / DOWN arrow 3> for RIGHT -> D / RIGHT arrow 4> for LEFT -> A / LEFT arrow
184ae17a20b5e03f3dfed36b2f4ccdfef9592159
[ "JavaScript", "Markdown" ]
2
JavaScript
amrojiqbal/Snake_game
d9ba477304b9ed4122c6e9fd460558fa6a50165f
cfbc30e3a2a7e4a79fd1dee10a8a17a98ada9315
refs/heads/master
<repo_name>rts-cmk-wu05/json-butiks-data-kawern<file_sep>/json.js const cars = [{ "make": "Toyota", "models": [{ "name": "Yaris" },{ "name": "Carina" }] },{ "make": "Ford", "models": [{ "name": "Mondeo" },{ "name": "Fiesta" }] }]; /* cars.forEach(function (car) { console.log(car.make); }); */ /* for (let int = 0; int < cars.length; int++) { console.log(cars[int].make); } */ /* let int = 0; while (int < cars.length) { console.log(cars[int].make); int++; } */ cars.forEach(function (car) { car.models.forEach(function (model) { console.log(car.make, model.name); }); });<file_sep>/README.md ![JSON logo](assets/json_logo-555px.png) JSON står for JavaScript Object Notation. Det er en struktureret syntaks til dataobjekter. JSON er et format til dataudveksling, som er let at læse og skrive. JSON objekter minder på mange måder om arrays. Et JSON objekt har _nøgler_ og _værdier_. Nøgler og værdier er adskilt af et enkelt kolon. ```json "nøgle": "værdi" ``` Hvis der er flere nøgle-værdi sæt i et JSON objekt skal de adskilles af et enkelt komma. ```json "nøgle": "værdi", "nøgle2": "værdi2", "nøgle3": "værdi3" ``` Alle nøgle-værdi sæt, som tilhører et enkelt objekt, skal præsenteres i krølleparentes. ```json { "nøgle": "værdi", "nøgle2": "værdi2", "nøgle3": "værdi3" } ``` Hvis der er flere objekter i et JSON objekt, skal disse adskilles af et enkelt komma. Udover komma-adskillelsen, skal hele objektet præsenteres i firkantede parenteser. Vi kalder et JSON objekt med flere objekter for en _samling_. ```json [{ "nøgle": "værdi", "nøgle2": "værdi2", "nøgle3": "værdi3" }, { "nøgle": "værdi", "nøgle2": "værdi2", "nøgle3": "værdi3" }, { "nøgle": "værdi", "nøgle2": "værdi2", "nøgle3": "værdi3" }] ``` >## Øvelse 1 >Lav et JSON objekt, der beskriver dig. Det kan indeholde ting som alder, køn, øjenfarve, fornavn, mellemnavne, efternavn, strømpefarve osv. Brug filen [migselv.json](migselv.json), som ligger i dette repository. # Datatyper En JSON værdi kan være en streng (`string`), tal (`number`), `array`, objekt (`object`), `boolean` eller `null`. ```json [{ "string": "Dette er en streng.", "number": 1234, "number": 123.4, "array": ["apples", "oranges", "strawberries"], "object": { "objectStuff": "Object content." }, "JSONisAwesome": true, "TimeForABreak": false, "IFinallyGetJSON": null }] ``` >## Øvelse 2 >Ret dit JSON objekt fra før til, så du bruger de forskellige datatyper. # Nesting JSON objekter understøtter _nesting_. Det vil sige, du kan have objekter inde i objekter. Der er ingen teoretisk grænse for hvor dybe objekter du kan lave, men forskellige sprog har begræsninger. For eksempel kan PHP klare 512 lag. Men hvis dit JSON objekt har så mange lag, skal du muligvis overveje, om din struktur er god. Et nested JSON objekt kan se således ud: ```json [{ "make": "Toyota", "models": [{ "name": "Yaris" },{ "name": "Carina" }] },{ "make": "Ford", "models": [{ "name": "Mondeo" },{ "name": "Fiesta" }] }] ``` Eller således: ```json [{ "name": { "family": "Emilius", "first": "Brian" }, "contact": { "email": "<EMAIL>", "github": "https://github.com/BrianEmilius" } }] ``` >## Øvelse 3 >Lav JSON objektet om dig selv om, så det benytter nesting, der hvor det giver mening. >## Opgave >Du skal nu lave dit eget JSON objekt, som repræsenterer et katalog over varene i en forretning. >Sådan et katalog indeholder nøgler som for eksempel varenummer, varenavn, pris, antal, beskrivelse, lagerbeholdning, billede, og så videre. >Du skal planlægge din samling ved at gøre brug af så mange af de forskellige datatyper, nesting, arrays, m.m. som du kan. >Emnet er: <NAME>. ___ ### Tips Du kan læse om JSON på hjemmesiden [json.org](http://json.org). Hvis du vil kontrollere om dit JSON objekt er korrekt formateret, kan du bruge validatoren [jsonlint.com](https://jsonlint.com). Mangler du inspiration til typer af oste, navne, beskrivelser og så videre, [så tag et kig her](http://lmgtfy.com/?q=oste).
bc306266c67397f0432b39219433c1dc6c98ebbb
[ "JavaScript", "Markdown" ]
2
JavaScript
rts-cmk-wu05/json-butiks-data-kawern
38bf6be4ea5465936e01f5080065d910374639af
2a1a045a24ae0e3bee6a500e6a1317c0c71666c9
refs/heads/main
<repo_name>Sau-ran/N_Bodies<file_sep>/Assets/Script/PhysicsNObjects.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class PhysicsNObjects : MonoBehaviour { [SerializeField] private List<Rigidbody> obj; [SerializeField] private Rigidbody rigSphere; [SerializeField] private float G = 9.8f; private Vector3 r; private float d; private RaycastHit hit; void Start() { for (int i = 0; i < obj.Count; i++) { obj[i].useGravity = false; } } void Update() { if (Input.GetMouseButtonDown(0)) { if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit)) { var sphere = Instantiate(rigSphere, hit.point + Vector3.back * 0.5f, Quaternion.identity); obj.Add(sphere); sphere.useGravity = false; sphere.mass = Random.Range(1, 5); } } for (int i = 0; i < obj.Count; i++) { for (int j = i+1; j < obj.Count; j++) { if (j != i) { r = obj[i].position - obj[j].position; d = r.magnitude; r.Normalize(); obj[i].AddRelativeForce(((r * G * obj[i].mass) / Mathf.Abs(d * d * d)), ForceMode.Force); } } } } }
153cef8226e466e21f7b379e7f69671a2469802d
[ "C#" ]
1
C#
Sau-ran/N_Bodies
9cc35a3b2d6b96e7ebdc53e7fac2a1928c1dbf82
936252a0e38fca5c50bf001c7a4e7934f10c2bb3
refs/heads/master
<repo_name>Marenthyu/NepDoc<file_sep>/ts.sh #!/bin/sh DATE=$(date '+%F %T%z') INPUT="$1" if [ -z "$1" ]; then INPUT='nepdoc.html' fi sed -i "/^<p class=\"lastupdate\">/c <p class=\"lastupdate\"><b>Last update</b>:&nbsp;<time datetime=\"${DATE}\">${DATE}</time></p>" $INPUT <file_sep>/deploy.sh #!/bin/bash ./ts.sh ruby nav.rb rm -rf ./deploy/{quickstart,adminref.html,fonts,godsound.ogg,main.css,nepdoc.html} cp -r {quickstart,adminref.html,fonts,godsound.ogg,main.css,nepdoc.html} ./deploy/ <file_sep>/nav.rb #!/usr/bin/env ruby levels = [0,0,0,0,0] last_level = -1 lines = [] lines << '<nav>' lines << '<ul>' File.open('nepdoc.html', 'rt') do |f| f.each do |l| next unless l =~ /^<h([1-5]) id="([^"]+)">([^<]+)<\/h/ level, href, heading = $1.to_i, '#'+$2, $3 reset = (level < last_level) case level when 1 levels = [levels[0]+1,0,0,0,0] when 2 levels = [levels[0],levels[1]+1,0,0,0] when 3 levels = [levels[0],levels[1],levels[2]+1,0,0] when 4 levels = [levels[0],levels[1],levels[2],levels[3]+1,0] end lines << "<li><a href=\"#{href}\">#{levels[0..(level-1)].join('.')}&nbsp;&nbsp;#{heading}</a>" last_level = level end end lines << '</ul>' lines << '</nav>' in_nav = false File.open('nepdoc.html', 'rt') do |inf| File.open('nepdoc.html.new', 'wt') do |outf| inf.each do |inline| # skip section between <nav></nav> if in_nav if inline.strip == '</nav>' in_nav = false outf.puts(lines.join("\n")) end next end if inline.strip == '<nav>' in_nav = true next end outf.puts(inline) end end end File.rename('nepdoc.html.new', 'nepdoc.html')
42eb83d59469cfd3112258b25c1d94a5870ccb8a
[ "Ruby", "Shell" ]
3
Shell
Marenthyu/NepDoc
4ea23cb1fe6a265c46b97efc74d08c3740e13708
c48dfc5b7bc33e1214349556d738960a999cb619
refs/heads/master
<file_sep>cmake_minimum_required(VERSION 3.13) project(bun C CXX) set(CMAKE_POSITION_INDEPENDENT_CODE ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(OOZ_SOURCES bitknit.cpp bits_rev_table.h compr_entropy.cpp compr_entropy.h compr_kraken.cpp compr_kraken.h compr_leviathan.cpp compr_leviathan.h compr_match_finder.cpp compr_match_finder.h compr_mermaid.cpp compr_mermaid.h compr_multiarray.cpp compr_tans.cpp compr_util.h compress.cpp compress.h kraken.cpp log_lookup.h lzna.cpp match_hasher.h qsort.h targetver.h ) add_executable(ooz ${OOZ_SOURCES}) add_library(libooz SHARED ${OOZ_SOURCES}) target_compile_definitions(libooz PUBLIC OOZ_DYNAMIC) target_compile_definitions(libooz PRIVATE OOZ_BUILD_DLL) add_library(bunutil STATIC "fnv.cpp" "fnv.h" "util.cpp" "util.h" "utf.cpp" "utf.h" ) target_include_directories(bunutil PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}) if (UNIX) find_package(PkgConfig REQUIRED) pkg_check_modules(libsodium REQUIRED IMPORTED_TARGET libsodium) target_link_libraries(bunutil PUBLIC PkgConfig::libsodium "unistring" ) endif() add_library(libbun SHARED "bun.cpp" "bun.h") target_compile_definitions(libbun PUBLIC BUN_DYNAMIC) target_compile_definitions(libbun PRIVATE BUN_BUILD_DLL) target_include_directories(libbun INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}) target_link_libraries(libbun PUBLIC bunutil) if (UNIX) target_link_libraries(libbun PRIVATE "-lstdc++fs" dl) endif() add_subdirectory(libpoe) add_executable(bun_extract_file "bun_extract_file.cpp" "path_rep.cpp" "path_rep.h" "ggpk_vfs.cpp" "ggpk_vfs.h") target_link_libraries(bun_extract_file PRIVATE libbun libpoe) if (UNIX) target_link_libraries(bun_extract_file PRIVATE "-lstdc++fs") endif() <file_sep>#pragma once #include <cstdint> #include <cstddef> namespace poe::util { using murmur2_32_digest = uint32_t; murmur2_32_digest oneshot_murmur2_32(std::byte const *data, size_t size); } // namespace poe::util<file_sep>#pragma once #include <poe/util/murmur2.hpp> #include <poe/util/random_access_file.hpp> #include <poe/util/sha256.hpp> #include <mio/mio.hpp> #include <array> #include <map> #include <string> #include <vector> namespace poe::format::ggpk { using chunk_tag = std::array<std::byte, 4>; chunk_tag constexpr make_text_tag(char a, char b, char c, char d) { return chunk_tag{ (std::byte)a, (std::byte)b, (std::byte)c, (std::byte)d, }; } chunk_tag constexpr make_text_tag(char const (&name)[5]) { return make_text_tag(name[0], name[1], name[2], name[3]); } constexpr chunk_tag FILE_TAG = make_text_tag("FILE"); constexpr chunk_tag FREE_TAG = make_text_tag("FREE"); constexpr chunk_tag GGPK_TAG = make_text_tag("GGPK"); constexpr chunk_tag PDIR_TAG = make_text_tag("PDIR"); struct parsed_entry { virtual ~parsed_entry() {} uint64_t offset_{}; std::u16string name_; poe::util::murmur2_32_digest name_hash_; poe::util::sha256_digest stored_digest_; struct parsed_directory *parent_{}; }; struct parsed_file : parsed_entry { uint64_t data_offset_; uint64_t data_size_; }; struct parsed_directory : parsed_entry { std::vector<std::unique_ptr<parsed_entry>> entries_; }; struct parsed_ggpk { uint32_t version_; poe::util::mmap_source mapping_; std::unique_ptr<parsed_entry> root_entry_; parsed_directory* root_; uint64_t free_offset_; }; std::unique_ptr<parsed_ggpk> index_ggpk(std::filesystem::path pack_path); } // namespace poe::format::ggpk<file_sep>#!/usr/bin/env python import struct import sys from cffi import FFI ffi = FFI() ffi.cdef(""" typedef uint8_t* OozMem; OozMem OozMemAlloc(size_t size); int64_t OozMemSize(OozMem mem); void OozMemFree(OozMem mem); int64_t OozDecompressBlock(uint8_t const* src_data, size_t src_size, uint8_t* dst_data, size_t dst_size); OozMem OozDecompressBlockAlloc(uint8_t const* src_data, size_t src_size, size_t dst_size); int64_t OozDecompressBundle(uint8_t const* src_data, size_t src_size, uint8_t* dst_data, size_t dst_size); OozMem OozDecompressBundleAlloc(uint8_t const* src_data, size_t src_size); """) ooz = ffi.dlopen("oozlib.dll") cmd = sys.argv[1] if cmd == 'block': filename = sys.argv[2] uncompressed_size = int(sys.argv[3]) with open(filename, 'rb') as f: data = f.read() unpacked_data = ffi.new("uint8_t[]", uncompressed_size) unpacked_size = ooz.OozDecompressBlock(data, len(data), unpacked_data, uncompressed_size) if unpacked_size != uncompressed_size: printf("Could not decompress block", file=sys.stderr) exit(1) sys.stdout.buffer.write(ffi.buffer(unpacked_data)) elif cmd == 'bundle': filename = sys.argv[2] with open(filename, 'rb') as f: data = f.read() bundle_mem = ooz.OozDecompressBundleAlloc(data, len(data)) if bundle_mem: size = ooz.OozMemSize(bundle_mem) sys.stdout.buffer.write(ffi.buffer(bundle_mem, size)) ooz.OozMemFree(bundle_mem) else: print("Could not decompress bundle", file=sys.stderr) exit(1)<file_sep>#include "ggpk_vfs.h" #include <poe/util/utf.hpp> struct GgpkVfs { Vfs vfs; std::unique_ptr<poe::format::ggpk::parsed_ggpk> pack; }; std::shared_ptr<GgpkVfs> open_ggpk(std::filesystem::path ggpk_path) { auto ret = std::make_shared<GgpkVfs>(); ret->pack = poe::format::ggpk::index_ggpk(ggpk_path); if (!ret->pack) { return {}; } ret->vfs.open = [](Vfs* vfs, char const* c_path) -> VfsFile* { auto* gvfs = reinterpret_cast<GgpkVfs*>(vfs); ggpk::parsed_directory const* dir = gvfs->pack->root_; std::u16string path = poe::util::lowercase(poe::util::to_u16string(c_path)); std::u16string_view tail(path); while (!tail.empty() && dir) { size_t delim = tail.find(u'/'); if (delim == 0) { continue; } std::u16string_view head = tail.substr(0, delim); bool next_found = false; for (auto& child : dir->entries_) { if (poe::util::lowercase(child->name_) == head) { if (delim == std::string_view::npos) { return (VfsFile*)dynamic_cast<ggpk::parsed_file const*>(child.get()); } else { dir = dynamic_cast<ggpk::parsed_directory const*>(child.get()); tail = tail.substr(delim + 1); next_found = true; } } } if (!next_found) { return nullptr; } } return nullptr; }; ret->vfs.close = [](Vfs* vfs, VfsFile* file) {}; ret->vfs.size = [](Vfs*, VfsFile* file) -> int64_t { auto* f = reinterpret_cast<ggpk::parsed_file const*>(file); return f ? f->data_size_ : -1; }; ret->vfs.read = [](Vfs* vfs, VfsFile* file, uint8_t* out, int64_t offset, int64_t size) -> int64_t { auto* gvfs = reinterpret_cast<GgpkVfs*>(vfs); auto* f = reinterpret_cast<ggpk::parsed_file const*>(file); if (offset + size > (int64_t)f->data_size_) { return -1; } memcpy(out, gvfs->pack->mapping_.data() + f->data_offset_ + offset, size); return size; }; ret->pack = poe::format::ggpk::index_ggpk(ggpk_path); return ret; } Vfs* borrow_vfs(std::shared_ptr<GgpkVfs>& vfs) { return vfs ? &vfs->vfs : nullptr; }<file_sep>#pragma once #include <stddef.h> #include <stdint.h> #if defined _WIN32 || defined __CYGWIN__ #ifdef BUN_BUILD_DLL #ifdef __GNUC__ #define BUN_DLL_PUBLIC __attribute__ ((dllexport)) #else #define BUN_DLL_PUBLIC __declspec(dllexport) // Note: actually gcc seems to also supports this syntax. #endif #else #ifdef __GNUC__ #define BUN_DLL_PUBLIC __attribute__ ((dllimport)) #else #define BUN_DLL_PUBLIC __declspec(dllimport) // Note: actually gcc seems to also supports this syntax. #endif #endif #define BUN_DLL_LOCAL #else #if __GNUC__ >= 4 #define BUN_DLL_PUBLIC __attribute__ ((visibility ("default"))) #define BUN_DLL_LOCAL __attribute__ ((visibility ("hidden"))) #else #define BUN_DLL_PUBLIC #define BUN_DLL_LOCAL #endif #endif extern "C" { /* BunMem is returned from functions that need to allocate the returned data. * It keeps track of its own size and needs to be freed from the application side * when the application is finished with it. */ typedef uint8_t* BunMem; struct Bun; struct BunIndex; struct VfsFile; struct Vfs { VfsFile* (*open)(Vfs*, char const*); void (*close)(Vfs*, VfsFile*); int64_t(*size)(Vfs*, VfsFile*); int64_t(*read)(Vfs*, VfsFile*, uint8_t* out, int64_t offset, int64_t size); }; BUN_DLL_PUBLIC BunMem BunMemAlloc(size_t size); BUN_DLL_PUBLIC int64_t BunMemSize(BunMem mem); BUN_DLL_PUBLIC void BunMemFree(BunMem mem); BUN_DLL_PUBLIC Bun* BunNew(char const* decompressor_path, char const* decompressor_export); BUN_DLL_PUBLIC void BunDelete(Bun* bun); BUN_DLL_PUBLIC BunIndex* BunIndexOpen(Bun* bun, Vfs* vfs, char const* bundle_dir); BUN_DLL_PUBLIC void BunIndexClose(BunIndex* idx); BUN_DLL_PUBLIC int32_t BunIndexLookupFileByPath(BunIndex* idx, char const* path); BUN_DLL_PUBLIC BunMem BunIndexExtractFile(BunIndex* idx, int32_t file_id); BUN_DLL_PUBLIC BunMem BunIndexExtractBundle(BunIndex* idx, int32_t bundle_id); BUN_DLL_PUBLIC int BunIndexBundleInfo(BunIndex const* idx, int32_t bundle_info_id, char const** name, uint32_t* uncompressed_size); BUN_DLL_PUBLIC int BunIndexFileInfo(BunIndex const* idx, int32_t file_info_id, uint64_t* path_hash, uint32_t* bundle_index_, uint32_t* file_offset_, uint32_t* file_size_); BUN_DLL_PUBLIC int BunIndexPathRepInfo(BunIndex const* idx, int32_t path_rep_id, uint64_t* hash, uint32_t* offset, uint32_t* size, uint32_t* recursive_size); BUN_DLL_PUBLIC BunMem BunIndexPathRepContents(BunIndex const* idx); BUN_DLL_PUBLIC int32_t BunIndexBundleCount(BunIndex* idx); BUN_DLL_PUBLIC int32_t BunIndexBundleIdByName(BunIndex* idx, char const* name); BUN_DLL_PUBLIC int32_t BunIndexBundleFileCount(BunIndex* idx, int32_t bundle_id); BUN_DLL_PUBLIC BunMem BunIndexBundleName(BunIndex* idx, int32_t bundle_id); BUN_DLL_PUBLIC int32_t BunIndexBundleFileOffset(BunIndex* idx, int32_t bundle_id, int32_t file_id); BUN_DLL_PUBLIC int32_t BunIndexBundleFileSize(BunIndex* idx, int32_t bundle_id, int32_t file_id); /* The BunDecompress family of functions decompresses either individual raw blocks or a full PoE bundle file. * They can either decompress into an user-supplied buffer of sufficient size or allocate a buffer for the caller. * Allocating functions return an BunMem or NULL. * Functions with user-supplied storage returns the resulting size or -1 in case of error. * The buffer supplied must have an additional 64 bytes of scratch space at the end. */ BUN_DLL_PUBLIC int BunDecompressBlock(Bun* bun, uint8_t const* src_data, size_t src_size, uint8_t* dst_data, size_t dst_size); BUN_DLL_PUBLIC BunMem BunDecompressBlockAlloc(Bun* bun, uint8_t const* src_data, size_t src_size, size_t dst_size); /* If the output buffer supplied to BunDecompressBundle is NULL or of zero size, the function returns the number of bytes needed. */ BUN_DLL_PUBLIC int64_t BunDecompressBundle(Bun* bun, uint8_t const* src_data, size_t src_size, uint8_t* dst_data, size_t dst_size); BUN_DLL_PUBLIC BunMem BunDecompressBundleAlloc(Bun* bun, uint8_t const* src_data, size_t src_size); } <file_sep>#include <poe/util/random_access_file.hpp> #ifdef _WIN32 #include <Windows.h> #else #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #endif namespace { uint64_t get_file_size(uintptr_t os_handle) { #ifdef _WIN32 HANDLE h = reinterpret_cast<HANDLE>(os_handle); LARGE_INTEGER size{}; GetFileSizeEx(h, &size); return static_cast<uint64_t>(size.QuadPart); #else int fd = static_cast<int>(os_handle); struct stat buf; fstat(fd, &buf); return static_cast<uint64_t>(buf.st_size); #endif } } // namespace namespace poe::util { random_access_file::random_access_file(std::filesystem::path path) { #ifdef _WIN32 HANDLE h = CreateFileW(path.wstring().c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr); if (h == INVALID_HANDLE_VALUE) { throw std::runtime_error("Could not load file"); } this->os_handle_ = reinterpret_cast<uintptr_t>(h); #else int fd = open(path.c_str(), O_RDONLY); if (fd < 0) { throw std::runtime_error("Could not load file"); } this->os_handle_ = static_cast<uintptr_t>(fd); #endif cached_size_ = get_file_size(this->os_handle_); } random_access_file::~random_access_file() { #ifdef _WIN32 HANDLE h = reinterpret_cast<HANDLE>(this->os_handle_); CloseHandle(h); #else int fd = static_cast<int>(this->os_handle_); close(fd); #endif } uint64_t random_access_file::size() const { return *cached_size_; } void record_histogram_entry(std::array<std::atomic<uint64_t>, 32> &buckets, uint64_t n) { for (size_t i = 0; i < 32; ++i) { uint64_t upper_bound = 2ull << i; if (n < upper_bound) { ++buckets[i]; break; } } } bool random_access_file::read_exact(uint64_t offset, std::byte *p, uint64_t n) const { if (offset + n > size()) { return false; } #ifdef _WIN32 HANDLE h = reinterpret_cast<HANDLE>(this->os_handle_); HANDLE guard = CreateEvent(nullptr, TRUE, FALSE, nullptr); uint64_t const BLOCK_SIZE = 1 << 20; uint64_t num_read = 0; for (uint64_t i = 0; i < n; i += BLOCK_SIZE) { uint64_t const block_n = (std::min)(BLOCK_SIZE, n - i); OVERLAPPED overlapped{}; uint64_t off = offset + i; overlapped.Offset = off & 0xFFFFFFFF; overlapped.OffsetHigh = off >> 32; overlapped.hEvent = guard; BOOL res = ReadFile(h, p + i, static_cast<DWORD>(block_n), nullptr, &overlapped); if (res == FALSE) { if (GetLastError() == ERROR_IO_PENDING) { DWORD block_read = 0; GetOverlappedResult(h, &overlapped, &block_read, TRUE); num_read += block_read; } else { CloseHandle(guard); return false; } } else { DWORD block_read = 0; GetOverlappedResult(h, &overlapped, &block_read, FALSE); num_read += block_read; } ++number_of_os_reads_; } record_histogram_entry(histogram_buckets_, n); ++number_of_exact_reads_; CloseHandle(guard); return num_read == n; #else int fd = static_cast<int>(this->os_handle_); ssize_t num_read = TEMP_FAILURE_RETRY(pread(fd, p, n, offset)); return num_read == n; #endif } uint64_t random_access_file::read_some(uint64_t offset, std::byte *p, uint64_t n) const { if (offset < size()) { uint64_t actual_n = (std::min)(n, size() - offset); if (this->read_exact(offset, p, actual_n)) { return actual_n; } } return 0; } } // namespace poe::util<file_sep>#include <poe/util/murmur2.hpp> #include "murmur2.hpp" namespace poe::util { murmur2_32_digest oneshot_murmur2_32(std::byte const *data, size_t size) { uint32_t const len = static_cast<uint32_t>(size); uint32_t const m = 0x5bd1'e995u; uint32_t const r = 24u; uint32_t h = len; uint32_t const rem = len % 4; uint32_t lim = (len - rem); for (size_t i = 0; i < lim; i += 4) { uint32_t const d0 = static_cast<uint32_t>(data[i]); uint32_t const d1 = static_cast<uint32_t>(data[i + 1]) << 8; uint32_t const d2 = static_cast<uint32_t>(data[i + 2]) << 16; uint32_t const d3 = static_cast<uint32_t>(data[i + 3]) << 24; uint32_t k = d0 | d1 | d2 | d3; k *= m; k ^= k >> r; k *= m; h *= m; h ^= k; } if (rem == 3) { h ^= static_cast<uint32_t>(data[lim + 2]) << 16; } if (rem >= 2) { h ^= static_cast<uint32_t>(data[lim + 1]) << 8; } if (rem >= 1) { h ^= static_cast<uint32_t>(data[lim]); h *= m; } h ^= h >> 13; h *= m; h ^= h >> 15; return h; } } // namespace poe::util<file_sep>#pragma once #include <string> namespace bun { namespace util { std::string lowercase(std::string const& s); std::u16string lowercase(std::u16string const& s); std::string to_string(std::u16string const& s); std::u16string to_u16string(std::string const& s); } }<file_sep>#pragma once #include <filesystem> #include <optional> #include <vector> namespace poe::util { enum class install_kind { Steam, Standalone, Bundled, Manual, }; std::optional<std::filesystem::path> own_install_dir(); std::vector<std::pair<install_kind, std::filesystem::path>> install_locations(); } // namespace poe::util<file_sep>#pragma once #include <string> namespace poe::util { struct less_without_case_predicate { bool operator()(std::u16string_view a, std::u16string_view b) const; }; std::u16string lowercase(std::u16string_view s); std::string to_string(std::u16string_view s); std::u16string to_u16string(std::string_view s); } // namespace poe::util<file_sep>#include <poe/util/install_location.hpp> #include <fstream> #include <optional> #include <regex> #include <string> #ifdef _WIN32 #include <Windows.h> #endif namespace poe::util { namespace { #ifdef _WIN32 std::optional<std::filesystem::path> get_reg_path(wchar_t const *subkey, wchar_t const *value) { std::vector<char> buf; while (true) { DWORD path_cb = (DWORD)buf.size(); void *p = buf.empty() ? nullptr : buf.data(); if (ERROR_SUCCESS == RegGetValueW(HKEY_CURRENT_USER, subkey, value, RRF_RT_REG_SZ, nullptr, p, &path_cb)) { if (path_cb <= buf.size()) { return std::filesystem::path(reinterpret_cast<char16_t *>(buf.data())); } buf.resize(path_cb); } else { return {}; } } } #endif std::optional<std::filesystem::path> standalone_install_dir() { #if _WIN32 return get_reg_path(LR"(SOFTWARE\GrindingGearGames\Path of Exile)", L"InstallLocation"); #else return {}; #endif } std::optional<std::filesystem::path> steam_install_dir() { #if _WIN32 auto steam_root = get_reg_path(LR"(SOFTWARE\Valve\Steam)", L"SteamPath"); if (!steam_root || !exists(*steam_root)) { return {}; } auto check_for_poe_dir = [](auto steamapps) -> std::optional<std::filesystem::path> { uint32_t const poe_appid = 238960; char buf[128]; sprintf(buf, "appmanifest_%u.acf", poe_appid); std::string const manifest_filename = buf; auto manifest_path = steamapps / manifest_filename; if (exists(manifest_path)) { auto poe_path = steamapps / "common/Path of Exile"; if (exists(poe_path)) { return poe_path; } } return {}; }; auto steamapps_path = *steam_root / "steamapps"; if (auto dir = check_for_poe_dir(*steam_root / "steamapps")) { return dir; } auto lib_folders_path = steamapps_path / "libraryfolders.vdf"; if (std::ifstream lib_folders_file(lib_folders_path); lib_folders_file) { enum class parse_step { Nothing, LibraryFoldersLiteral, LibraryFoldersOpenCurly, LibraryFoldersCloseCurly, }; parse_step step = parse_step::Nothing; std::string line; while (std::getline(lib_folders_file, line)) { switch (step) { case parse_step::Nothing: { if (line == R"("LibraryFolders")") { step = parse_step::LibraryFoldersLiteral; } } break; case parse_step::LibraryFoldersLiteral: { if (line == "{") { step = parse_step::LibraryFoldersOpenCurly; } } break; case parse_step::LibraryFoldersOpenCurly: { if (line == "}") { step = parse_step::LibraryFoldersCloseCurly; } else { std::regex rx(R"!!(\s*"(\d+)"\s+"([^"]*)"\s*)!!"); std::smatch match; if (regex_match(line, match, rx)) { std::filesystem::path p = match.str(2); if (auto dir = check_for_poe_dir(p / "steamapps")) { return dir; } } } } break; case parse_step::LibraryFoldersCloseCurly: { return {}; } break; } } } return {}; #else return {}; #endif } } // namespace std::optional<std::filesystem::path> own_install_dir() { #ifdef _WIN32 std::vector<wchar_t> buf(1 << 20); GetModuleFileNameW(nullptr, buf.data(), static_cast<DWORD>(buf.size())); std::filesystem::path p = buf.data(); if (p.has_parent_path()) { return p.parent_path(); } else { return {}; } #else return {}; // TODO(LV): Implement #endif } std::vector<std::pair<install_kind, std::filesystem::path>> install_locations() { std::vector<std::pair<install_kind, std::optional<std::filesystem::path>>> candidate_dirs = { {install_kind::Standalone, standalone_install_dir()}, { install_kind::Steam, steam_install_dir(), }, { install_kind::Bundled, own_install_dir(), }, }; std::vector<std::pair<install_kind, std::filesystem::path>> found_ggpks; for (auto [kind, cand] : candidate_dirs) { if (cand) { auto p = *cand / "Content.ggpk"; if (exists(p)) { found_ggpks.push_back({kind, *cand}); } } } return found_ggpks; } } // namespace poe::util <file_sep>#include "fnv.h" static uint64_t const FNV1_OFFSET_BASIS_64 = 0xcbf29ce484222325ull; static uint64_t const FNV1_PRIME_64 = 0x100000001b3; uint64_t fnv1_64(void const* data, size_t n) { uint64_t hash = FNV1_OFFSET_BASIS_64; auto* p = reinterpret_cast<uint8_t const*>(data), * end = p + n; while (p != end) { hash = hash * FNV1_PRIME_64; hash = hash ^ *p; ++p; } return hash; } uint64_t fnv1a_64(void const* data, size_t n) { uint64_t hash = FNV1_OFFSET_BASIS_64; auto* p = reinterpret_cast<uint8_t const*>(data), * end = p + n; while (p != end) { hash = hash ^ *p; hash = hash * FNV1_PRIME_64; ++p; } return hash; } FNV1A64::FNV1A64() : hash_(FNV1_OFFSET_BASIS_64) {} uint64_t FNV1A64::feed(void const* data, size_t n) { auto* p = reinterpret_cast<uint8_t const*>(data), * end = p + n; while (p != end) { hash_ = hash_ ^ *p; hash_ = hash_ * FNV1_PRIME_64; ++p; } return hash_; }<file_sep>#include "bun.h" #include <stddef.h> #include <string.h> #include <algorithm> #include <filesystem> #include <fstream> #include <map> #include <memory> #include <set> #include <sstream> #include <string> #include <unordered_map> #include <vector> #include "fnv.h" #include "util.h" #ifdef _WIN32 #include <Windows.h> #define DECOMPRESS_API WINAPI #else #include <sys/mman.h> #include <unistd.h> #include <dlfcn.h> #define DECOMPRESS_API #endif size_t const SAFE_SPACE = 64; using decompress_fun = int(DECOMPRESS_API *)(uint8_t const *src_buf, int src_len, uint8_t *dst, size_t dst_size, int, int, int, uint8_t *, size_t, void *, void *, void *, size_t, int); struct Bun { std::shared_ptr<void> decompress_mod_; decompress_fun decompress_fun_; }; struct bundle_info { std::string name_; uint32_t uncompressed_size_; }; struct file_info { uint64_t path_hash_; uint32_t bundle_index_; uint32_t file_offset_; uint32_t file_size_; }; struct path_rep_info { uint64_t hash; uint32_t offset; uint32_t size; uint32_t recursive_size; }; struct BunIndex { bool read_file(char const *path, std::vector<uint8_t> &out); Bun *bun_; Vfs *vfs_; std::string bundle_root_; BunMem index_mem_; std::vector<bundle_info> bundle_infos_; std::vector<file_info> file_infos_; std::vector<path_rep_info> path_rep_infos_; std::unordered_map<uint64_t, uint32_t> path_hash_to_file_info; BunMem inner_mem_; }; bool BunIndex::read_file(char const *path, std::vector<uint8_t> &out) { std::string full_path = bundle_root_ + '/' + path; if (vfs_) { auto fh = vfs_->open(vfs_, full_path.c_str()); if (!fh) { return false; } auto size = vfs_->size(vfs_, fh); out.resize(size); bool success = vfs_->read(vfs_, fh, out.data(), 0, size) == size; vfs_->close(vfs_, fh); return success; } else { std::ifstream is(full_path, std::ios::binary); if (!is) { return false; } is.seekg(0, std::ios::end); auto size = is.tellg(); is.seekg(0, std::ios::beg); out.resize(size); return !!is.read(reinterpret_cast<char *>(out.data()), out.size()); } } BUN_DLL_PUBLIC Bun *BunNew(char const *decompressor_path, char const *decompressor_export) { if (!decompressor_export) { decompressor_export = "OodleLZ_Decompress"; } auto bun = std::make_unique<Bun>(); #ifdef _WIN32 auto mod = LoadLibraryA(decompressor_path); if (!mod) { return nullptr; } bun->decompress_mod_.reset(mod, &FreeLibrary); auto fun = reinterpret_cast<decompress_fun>(GetProcAddress((HMODULE)bun->decompress_mod_.get(), decompressor_export)); if (!fun) { return nullptr; } bun->decompress_fun_ = fun; #else auto mod = dlopen(decompressor_path, RTLD_NOW | RTLD_LOCAL); if (!mod) { return nullptr; } bun->decompress_mod_.reset(mod, &dlclose); auto fun = reinterpret_cast<decompress_fun>(dlsym(mod, decompressor_export)); if (!fun) { return nullptr; } bun->decompress_fun_ = fun; #endif return bun.release(); } BUN_DLL_PUBLIC void BunDelete(Bun *bun) { delete bun; } std::string printable_string(uint32_t x) { std::string s; for (size_t i = 0; i < 4; ++i) { auto shift = i * 8; uint8_t c = (x >> shift) & 0xFF; if (c == '"') { s += "\"\""; } else if (isprint((int)c)) { s += c; } else { s += "."; } } return s; } std::string hex_dump(size_t width, uint8_t const *p, size_t n) { std::string s; char buf[10]; while (n) { size_t k = (std::min<size_t>)(n, width); for (size_t i = 0; i < k; ++i) { sprintf(buf, "%s%02X", (i ? " " : ""), p[i]); s += buf; } for (size_t i = k; i < width; ++i) { s += " "; } s += " | "; for (size_t i = 0; i < k; ++i) { auto c = p[i]; if (isprint((int)c)) { s += c; } else { s += "."; } } s += "\n"; p += k; n -= k; } return s; } BUN_DLL_PUBLIC BunIndex *BunIndexOpen(Bun *bun, Vfs *vfs, char const *root_dir) { auto idx = std::make_unique<BunIndex>(); idx->bun_ = bun; idx->vfs_ = vfs; idx->bundle_root_ = vfs ? "Bundles2" : (root_dir + std::string("/Bundles2")); std::vector<uint8_t> index_bin_src; if (!idx->read_file("_.index.bin", index_bin_src)) { fprintf(stderr, "Could not read _.index.bin\n"); return nullptr; } auto index_bin_mem = BunDecompressBundleAlloc(bun, index_bin_src.data(), index_bin_src.size()); if (!index_bin_mem) { fprintf(stderr, "Could not decompress _.index.bin\n"); return nullptr; } fprintf(stderr, "Index bundle decompressed, %lld bytes\n", BunMemSize(index_bin_mem)); idx->index_mem_ = index_bin_mem; uint32_t bundle_count; reader r{idx->index_mem_, (size_t)BunMemSize(idx->index_mem_)}; r.read(bundle_count); idx->bundle_infos_.reserve(bundle_count); std::map<std::string, size_t> bundle_index_from_name; for (size_t i = 0; i < bundle_count; ++i) { bundle_info bi; uint32_t name_length; r.read(name_length); std::vector<char> name_buf(name_length); r.read(name_buf); bi.name_.assign(name_buf.begin(), name_buf.end()); r.read(bi.uncompressed_size_); bundle_index_from_name[bi.name_] = i; idx->bundle_infos_.push_back(bi); } std::map<std::string, size_t> bundle_name_to_bundle_index; std::vector<std::vector<std::string>> bundled_filenames(idx->bundle_infos_.size()); using FilenameBundle = std::map<std::string, size_t>; FilenameBundle filename_bundle; std::map<size_t, std::vector<size_t>> bundle_file_seqs; uint32_t file_count; r.read(file_count); for (size_t i = 0; i < file_count; ++i) { file_info fi; r.read(fi.path_hash_); r.read(fi.bundle_index_); r.read(fi.file_offset_); r.read(fi.file_size_); idx->path_hash_to_file_info[fi.path_hash_] = (uint32_t)i; bundle_file_seqs[fi.bundle_index_].push_back(i); idx->file_infos_.push_back(fi); } #if 0 for (size_t i = 0; i < idx->bundle_infos_.size(); ++i) { size_t binary_bundle_size = bundle_file_seqs[i].size(); size_t text_bundle_size = bundled_filenames[i].size(); if (binary_bundle_size != text_bundle_size) { fprintf(stderr, "File count for bundle %zu (\"%s\") mismatch - binary (%zu) and text (%zu)\n", i, idx->bundle_infos_[i].name_.c_str(), binary_bundle_size, text_bundle_size); } } #endif fprintf(stderr, "Bundle count in index binary: %zu\n", idx->bundle_infos_.size()); // fprintf(stderr, "Bundle count in index text: %zu\n", text_bundle_count); fprintf(stderr, "File count in index binary: %zu\n", idx->file_infos_.size()); // fprintf(stderr, "File count in index text: %zu\n", text_file_count); #if 0 auto I = std::find_if(idx->bundle_infos_.begin(), idx->bundle_infos_.end(), [](auto a) { return a.name_ == "Data.dat_4"; }); if (I != idx->bundle_infos_.end()) { auto& bi = *I; size_t i = I - idx->bundle_infos_.begin(); fprintf(stderr, "Bundle %zu - name: \"%s\", uncompressed size: %u\n", i, bi.name_.c_str(), bi.uncompressed_size_); } #endif uint32_t some_count; r.read(some_count); idx->path_rep_infos_.reserve(some_count); for (size_t i = 0; i < some_count; ++i) { path_rep_info si; r.read(si.hash); r.read(si.offset); r.read(si.size); r.read(si.recursive_size); idx->path_rep_infos_.push_back(si); } auto inner_mem = BunDecompressBundleAlloc(idx->bun_, r.p_, r.n_); idx->inner_mem_ = inner_mem; fprintf(stderr, "Decompressed inner size: %lld\n", BunMemSize(inner_mem)); { std::ofstream os("C:/Temp/_.index.mem", std::ios::binary); os.write((char const *)idx->index_mem_, BunMemSize(idx->index_mem_)); } { std::ofstream os("C:/Temp/_.index-inner.mem", std::ios::binary); os.write((char const *)idx->inner_mem_, BunMemSize(idx->inner_mem_)); } #if 0 #endif return idx.release(); } BUN_DLL_PUBLIC void BunIndexClose(BunIndex *idx) { if (idx) { BunMemFree(idx->index_mem_); BunMemFree(idx->inner_mem_); } } uint64_t hash_directory(std::string path) { while (path.back() == '/') { path.pop_back(); } path += "++"; return fnv1a_64(path.data(), path.size()); } uint64_t hash_file(std::string path) { for (auto &ch : path) { ch = (char)std::tolower((int)(unsigned char)ch); } path += "++"; return fnv1a_64(path.data(), path.size()); } BUN_DLL_PUBLIC int32_t BunIndexLookupFileByPath(BunIndex *idx, char const *path) { if (!idx) { return -1; } auto path_hash = hash_file(path); auto I = idx->path_hash_to_file_info.find(path_hash); if (I != idx->path_hash_to_file_info.end()) { return I->second; } return -1; } BUN_DLL_PUBLIC BunMem BunIndexExtractFile(BunIndex *idx, int32_t file_id) { if (!idx || file_id < 0 || file_id >= idx->file_infos_.size()) { return nullptr; } auto &fi = idx->file_infos_[file_id]; auto &bi = idx->bundle_infos_[fi.bundle_index_]; std::filesystem::path bundle_path = idx->bundle_root_; bundle_path /= bi.name_ + ".bundle.bin"; std::vector<uint8_t> bundle_data; slurp_file(bundle_path, bundle_data); BunMem all_data = BunDecompressBundleAlloc(idx->bun_, bundle_data.data(), bundle_data.size()); BunMem ret_mem = BunMemAlloc(fi.file_size_); memcpy(ret_mem, all_data + fi.file_offset_, fi.file_size_); BunMemFree(all_data); return ret_mem; } BUN_DLL_PUBLIC BunMem BunIndexExtractBundle(BunIndex *idx, int32_t bundle_id) { if (!idx || bundle_id < 0 || bundle_id >= idx->bundle_infos_.size()) { return nullptr; } auto &bi = idx->bundle_infos_[bundle_id]; std::string bundle_path = bi.name_ + ".bundle.bin"; std::vector<uint8_t> bundle_data; if (!idx->read_file(bundle_path.c_str(), bundle_data)) { return nullptr; } return BunDecompressBundleAlloc(idx->bun_, bundle_data.data(), bundle_data.size()); } BUN_DLL_PUBLIC int BunIndexBundleInfo(BunIndex const *idx, int32_t bundle_info_id, char const **name, uint32_t *uncompressed_size) { if (!idx || bundle_info_id < 0 || bundle_info_id >= idx->bundle_infos_.size()) { return -1; } auto &bi = idx->bundle_infos_[bundle_info_id]; *name = bi.name_.c_str(); *uncompressed_size = bi.uncompressed_size_; return 0; } BUN_DLL_PUBLIC int BunIndexFileInfo(BunIndex const *idx, int32_t file_info_id, uint64_t *path_hash, uint32_t *bundle_index, uint32_t *file_offset, uint32_t *file_size) { if (!idx || file_info_id < 0 || file_info_id >= idx->file_infos_.size()) { return -1; } auto &fi = idx->file_infos_[file_info_id]; *path_hash = fi.path_hash_; *bundle_index = fi.bundle_index_; *file_offset = fi.file_offset_; *file_size = fi.file_size_; return 0; } BUN_DLL_PUBLIC int BunIndexPathRepInfo(BunIndex const *idx, int32_t path_rep_id, uint64_t *hash, uint32_t *offset, uint32_t *size, uint32_t *recursive_size) { if (!idx || path_rep_id < 0 || path_rep_id >= idx->path_rep_infos_.size()) { return -1; } auto si = idx->path_rep_infos_[path_rep_id]; *hash = si.hash; *offset = si.offset; *size = si.size; *recursive_size = si.recursive_size; return 0; } BUN_DLL_PUBLIC BunMem BunIndexPathRepContents(BunIndex const *idx) { if (!idx) { return nullptr; } return idx->inner_mem_; } BUN_DLL_PUBLIC int32_t BunIndexBundleCount(BunIndex *idx) { if (!idx) { return -1; } return static_cast<int32_t>(idx->bundle_infos_.size()); } BUN_DLL_PUBLIC int32_t BunIndexBundleIdByName(BunIndex *idx, char const *name) { if (!idx) { return -1; } for (size_t i = 0; i < idx->bundle_infos_.size(); ++i) { if (idx->bundle_infos_[i].name_ == name) { return static_cast<int32_t>(i); } } return -1; } BUN_DLL_PUBLIC int32_t BunIndexBundleFileCount(BunIndex *idx, int32_t bundle_id) { if (!idx || bundle_id < 0 || bundle_id >= idx->bundle_infos_.size()) { return -1; } auto count = std::count_if(idx->file_infos_.begin(), idx->file_infos_.end(), [&](file_info const &fi) { return fi.bundle_index_ == bundle_id; }); return static_cast<uint32_t>(count); } BUN_DLL_PUBLIC BunMem BunIndexBundleName(BunIndex *idx, int32_t bundle_id) { if (!idx || bundle_id < 0 || bundle_id >= idx->bundle_infos_.size()) { return nullptr; } auto &bi = idx->bundle_infos_[bundle_id]; auto &name = bi.name_; BunMem ret = BunMemAlloc(name.size() + 1); memcpy(ret, name.c_str(), name.size() + 1); return ret; } static file_info const *find_file_in_index(BunIndex *idx, int32_t bundle_id, int32_t file_id) { if (!idx || bundle_id < 0 || bundle_id >= idx->bundle_infos_.size()) { return nullptr; } if (file_id < 0) { return nullptr; } size_t bundle_matches = 0; for (auto &fi : idx->file_infos_) { if (fi.bundle_index_ == bundle_id) { if (bundle_matches == file_id) { return &fi; } ++bundle_matches; } } return nullptr; } int32_t BunIndexBundleFileOffset(BunIndex *idx, int32_t bundle_id, int32_t file_id) { if (auto *fi = find_file_in_index(idx, bundle_id, file_id)) { return fi->file_offset_; } return -1; } int32_t BunIndexBundleFileSize(BunIndex *idx, int32_t bundle_id, int32_t file_id) { if (auto *fi = find_file_in_index(idx, bundle_id, file_id)) { return fi->file_size_; } return -1; } using BunMemHeader = int64_t; BunMem BunMemAlloc(size_t size) { BunMemHeader h = size; uint8_t *p = new uint8_t[sizeof(BunMemHeader) + size]; memcpy(p, &h, sizeof(BunMemHeader)); return p + sizeof(BunMemHeader); } int64_t BunMemSize(BunMem mem) { if (!mem) { return -1; } BunMemHeader h; memcpy(&h, mem - sizeof(BunMemHeader), sizeof(BunMemHeader)); return h; } void BunMemShrink(BunMem mem, int64_t new_size) { if (mem) { uint8_t *header_ptr = mem - sizeof(BunMemHeader); size_t const header_size = sizeof(BunMemHeader); BunMemHeader h; memcpy(&h, header_ptr, header_size); if (h >= new_size) { h = new_size; memcpy(header_ptr, &h, header_size); } } } void BunMemFree(BunMem mem) { if (!mem) { return; } uint8_t *p = mem - sizeof(BunMemHeader); delete[] p; } #ifdef _WIN32 uint8_t *ro_clone(uint8_t const *src_data, size_t src_size) { auto *mem = (uint8_t *)malloc(src_size); memcpy(mem, src_data, src_size); return mem; } void ro_free(uint8_t *s, size_t src_size) { free(s); } #else uint8_t *ro_clone(uint8_t const *src_data, size_t src_size) { auto page_size = sysconf(_SC_PAGESIZE); auto pages = (src_size + page_size - 1) / page_size; auto rounded_src_size = (pages + 1) * page_size; auto *s = (uint8_t *)aligned_alloc(page_size, rounded_src_size); memcpy(s, src_data, src_size); mprotect(s + pages * page_size, page_size, PROT_READ); return s; } void ro_free(uint8_t *s, size_t src_size) { auto page_size = sysconf(_SC_PAGESIZE); auto pages = (src_size + page_size - 1) / page_size; auto rounded_src_size = (pages + 1) * page_size; mprotect(s + pages * page_size, page_size, PROT_READ | PROT_WRITE); free(s); } #endif int BunDecompressBlock(Bun *bun, uint8_t const *src_data, size_t src_size, uint8_t *dst_data, size_t dst_size) { auto *s = ro_clone(src_data, src_size); int res = bun->decompress_fun_(s, (int)src_size, dst_data, (int)dst_size, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); ro_free(s, src_size); return res; } BunMem BunDecompressBlockAlloc(Bun *bun, uint8_t const *src_data, size_t src_size, size_t dst_size) { BunMem mem = BunMemAlloc(dst_size + SAFE_SPACE); for (size_t i = 0; i < SAFE_SPACE; ++i) { mem[dst_size + i] = 0xCD; } auto *s = ro_clone(src_data, src_size); int res = bun->decompress_fun_(s, (int)src_size, mem, (int)dst_size, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); ro_free(s, src_size); if (res != dst_size) { BunMemFree(mem); return nullptr; } for (size_t i = 0; i < SAFE_SPACE; ++i) { if (mem[dst_size + i] != 0xCD) { // fprintf(stderr, "Decompress function clobbered safe space at byte %zu\n", i); // fflush(stderr); } } BunMemShrink(mem, dst_size); return mem; } struct bundle_fixed_header { uint32_t uncompressed_size; uint32_t total_payload_size; uint32_t head_payload_size; enum encoding_schemes { Kraken_6 = 8, Mermaid_A = 9, Leviathan_C = 13 }; uint32_t first_file_encode; uint32_t unk10; uint64_t uncompressed_size2; uint64_t total_payload_size2; uint32_t block_count; uint32_t unk28[5]; }; int64_t BunDecompressBundle(Bun *bun, uint8_t const *src_data, size_t src_size, uint8_t *dst_data, size_t dst_size) { reader r = {src_data, src_size}; bundle_fixed_header fix_h; if (!r.read(fix_h.uncompressed_size) || !r.read(fix_h.total_payload_size) || !r.read(fix_h.head_payload_size) || !r.read(fix_h.first_file_encode) || !r.read(fix_h.unk10) || !r.read(fix_h.uncompressed_size2) || !r.read(fix_h.total_payload_size2) || !r.read(fix_h.block_count) || !r.read(fix_h.unk28)) { return -1; } if (dst_size < fix_h.uncompressed_size2) { // If an empty buffer is supplied, return the amount the caller needs to allocate. return fix_h.uncompressed_size2; } std::vector<uint32_t> entry_sizes(fix_h.block_count); if (!r.read(entry_sizes)) { return -1; } if (r.n_ < fix_h.total_payload_size2) { return -1; } uint8_t const *p = r.p_; size_t n = r.n_; uint8_t *out_p = dst_data; size_t out_cur = 0; for (size_t i = 0; i < entry_sizes.size(); ++i) { size_t amount_to_write = (std::min<size_t>)(fix_h.uncompressed_size2 - out_cur, fix_h.unk28[0]); // int64_t amount_written = BunDecompressBlock(bun, p, entry_sizes[i], out_p + out_cur, amount_to_write); auto mem = BunDecompressBlockAlloc(bun, p, entry_sizes[i], amount_to_write); auto amount_written = mem ? amount_to_write : 0; memcpy(out_p + out_cur, mem, amount_written); BunMemFree(mem); p += entry_sizes[i]; n -= entry_sizes[i]; out_cur += amount_to_write; if (amount_written != amount_to_write) { return -1; } } return out_cur; } BunMem BunDecompressBundleAlloc(Bun *bun, uint8_t const *src_data, size_t src_size) { int64_t dst_size = BunDecompressBundle(bun, src_data, src_size, nullptr, 0); BunMem dst_mem = BunMemAlloc(dst_size + SAFE_SPACE); if (dst_size != BunDecompressBundle(bun, src_data, src_size, dst_mem, dst_size)) { BunMemFree(dst_mem); return nullptr; } BunMemShrink(dst_mem, dst_size); return dst_mem; } <file_sep>#include "utf.h" #include <vector> #ifdef _WIN32 #include <Windows.h> #else #include <unicase.h> #include <unistr.h> #endif namespace bun { namespace util { std::u16string lowercase(std::u16string const& s) { if (s.empty()) { return std::u16string(s); } #ifdef _WIN32 auto src = reinterpret_cast<LPCWSTR>(s.data()); auto src_cch = static_cast<int>(s.size()); auto dst_cch = LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, src, src_cch, nullptr, 0, nullptr, nullptr, 0); std::vector<char16_t> dst(dst_cch); LCMapStringEx(LOCALE_NAME_INVARIANT, LCMAP_LOWERCASE, src, src_cch, reinterpret_cast<LPWSTR>(dst.data()), dst_cch, nullptr, nullptr, 0); return std::u16string(std::u16string(dst.data(), dst.data() + dst.size())); #else // TODO(LV): implement auto src = reinterpret_cast<uint16_t const*>(s.data()); size_t dst_cch = 0; u16_tolower(src, s.size(), nullptr, nullptr, nullptr, &dst_cch); std::vector<char16_t> dst(dst_cch); u16_tolower(src, s.size(), nullptr, nullptr, reinterpret_cast<uint16_t*>(dst.data()), &dst_cch); return std::u16string(std::u16string_view(dst.data(), dst.size())); #endif } namespace { template <typename String> void convert_string(std::u16string const& src, String& dest) { using CharT = typename String::value_type; #ifdef _WIN32 LPCWCH src_p = reinterpret_cast<LPCWCH>(src.data()); int src_n = static_cast<int>(src.size()); int cch = WideCharToMultiByte(CP_UTF8, 0, src_p, src_n, nullptr, 0, nullptr, nullptr); std::vector<char> buf(cch); WideCharToMultiByte(CP_UTF8, 0, src_p, src_n, buf.data(), static_cast<int>(buf.size()), nullptr, nullptr); dest.assign(reinterpret_cast<CharT*>(buf.data()), buf.size()); #else size_t cch{}; uint8_t* p = u16_to_u8(reinterpret_cast<uint16_t const*>(src.data()), src.size(), nullptr, &cch); dest.assign(reinterpret_cast<CharT*>(p), cch); free(p); #endif } void convert_string(std::string const& src, std::u16string& dest) { #ifdef _WIN32 LPCCH src_p = reinterpret_cast<LPCCH>(src.data()); int src_n = static_cast<int>(src.size()); int cch = MultiByteToWideChar(CP_UTF8, 0, src_p, src_n, nullptr, 0); std::vector<wchar_t> buf(cch); MultiByteToWideChar(CP_UTF8, 0, src_p, src_n, buf.data(), static_cast<int>(buf.size())); dest.assign(reinterpret_cast<char16_t*>(buf.data()), buf.size()); #else size_t cch{}; uint16_t* p = u8_to_u16(reinterpret_cast<uint8_t const*>(src.data()), src.size(), nullptr, &cch); dest.assign(reinterpret_cast<char16_t*>(p), cch); free(p); #endif } } // namespace std::string to_string(std::u16string const& s) { std::string ret; convert_string(s, ret); return ret; } std::u16string to_u16string(std::string const& s) { std::u16string ret; convert_string(s, ret); return ret; } } } <file_sep>#pragma once #include <poe/format/ggpk.hpp> #include "bun.h" #include <memory> namespace ggpk = poe::format::ggpk; struct GgpkVfs; std::shared_ptr<GgpkVfs> open_ggpk(std::filesystem::path path); Vfs* borrow_vfs(std::shared_ptr<GgpkVfs>& vfs);<file_sep>#pragma once #include <string> #include <vector> std::vector<std::string> generate_paths(void const* spec_data, size_t spec_size); void explain_paths(void const* spec_data, size_t spec_size);<file_sep>#include <poe/util/sha256.hpp> #include <memory> #ifdef _WIN32 #include <Windows.h> #include <bcrypt.h> #pragma comment(lib, "Bcrypt.lib") #else #include <sodium/crypto_hash_sha256.h> #endif namespace poe::util { std::string digest_to_string(sha256_digest const& digest) { char buf[128]; char* p = buf; for (auto b : digest) { sprintf(p, "%02x", b); } return buf; } #ifdef _WIN32 struct sha256_win32 : sha256 { sha256_win32() { BCryptOpenAlgorithmProvider(&alg_handle_, BCRYPT_SHA256_ALGORITHM, nullptr, BCRYPT_HASH_REUSABLE_FLAG); BCryptCreateHash(alg_handle_, &hash_handle_, nullptr, 0, nullptr, 0, BCRYPT_HASH_REUSABLE_FLAG); } ~sha256_win32() { BCryptDestroyHash(hash_handle_); BCryptCloseAlgorithmProvider(alg_handle_, 0); } sha256_win32(sha256_win32&) = delete; sha256_win32 operator=(sha256_win32&) = delete; void reset() override { finish(); } void feed(uint8_t const* data, size_t size) override { UCHAR* p = const_cast<UCHAR*>(reinterpret_cast<UCHAR const*>(data)); ULONG n = static_cast<ULONG>(size); BCryptHashData(hash_handle_, p, n, 0); } sha256_digest finish() override { sha256_digest ret{}; UCHAR* p = const_cast<UCHAR*>(reinterpret_cast<UCHAR const*>(ret.data())); ULONG n = static_cast<ULONG>(ret.size()); BCryptFinishHash(hash_handle_, p, n, 0); return ret; } private: BCRYPT_ALG_HANDLE alg_handle_; BCRYPT_HASH_HANDLE hash_handle_; }; using sha256_impl = sha256_win32; #else struct sha256_linux : sha256 { sha256_linux() { reset(); } sha256_linux(sha256_linux&) = delete; sha256_linux operator=(sha256_linux&) = delete; void reset() override { crypto_hash_sha256_init(&state_); } void feed(uint8_t const* data, size_t size) override { crypto_hash_sha256_update(&state_, reinterpret_cast<unsigned char const*>(data), size); } sha256_digest finish() override { sha256_digest ret{}; crypto_hash_sha256_final(&state_, reinterpret_cast<unsigned char*>(ret.data())); reset(); return ret; } private: crypto_hash_sha256_state state_; }; using sha256_impl = sha256_linux; #endif sha256_digest oneshot_sha256(uint8_t const* data, size_t size) { sha256_impl hasher; hasher.feed(data, size); return hasher.finish(); } std::unique_ptr<sha256> incremental_sha256() { return std::make_unique<sha256_impl>(); } } // namespace poe::util <file_sep>#include "util.h" #include <fstream> std::string hex_dump(size_t width, void const* data, size_t size) { auto* p = reinterpret_cast<uint8_t const*>(data); auto n = size; std::string s; char buf[10]; while (n) { size_t k = (std::min<size_t>)(n, width); for (size_t i = 0; i < k; ++i) { sprintf(buf, "%s%02X", (i ? " " : ""), p[i]); s += buf; } for (size_t i = k; i < width; ++i) { s += " "; } s += " | "; for (size_t i = 0; i < k; ++i) { auto c = p[i]; if (isprint((int)c)) { s += c; } else { s += "."; } } s += "\n"; p += k; n -= k; } return s; } bool slurp_file(std::filesystem::path path, std::vector<uint8_t>& data) { std::ifstream is(path, std::ios::binary); if (!is) { return false; } is.seekg(0, std::ios::end); auto size = static_cast<uint64_t>(is.tellg()); is.seekg(0, std::ios::beg); data.resize(size); if (!is.read(reinterpret_cast<char*>(data.data()), data.size())) { return false; } return true; } bool dump_file(std::filesystem::path filename, void const* data, size_t size) { std::ofstream os(filename, std::ios::binary | std::ios::trunc); if (!os) { return false; } return !!os.write(reinterpret_cast<char const*>(data), size); }<file_sep>#pragma once #include <cstring> #include <filesystem> #include <string> #include <vector> std::string hex_dump(size_t width, void const* data, size_t size); bool slurp_file(std::filesystem::path path, std::vector<uint8_t>& data); bool dump_file(std::filesystem::path filename, void const* data, size_t size); struct reader { reader(void const* p, size_t n) : reader(reinterpret_cast<uint8_t const*>(p), n) {} template <typename T> reader(T const* p, size_t n) : p_(reinterpret_cast<uint8_t const*>(p)), n_(n * sizeof(T)) {} template <typename T> bool read(T& t) { size_t const k = sizeof(T); if (n_ < k) { return false; } memcpy(&t, p_, k); p_ += k; n_ -= k; return true; } template <typename T> bool read(std::vector<T>& v) { size_t const k = v.size() * sizeof(T); if (n_ < k) { return false; } memcpy(v.data(), p_, k); p_ += k; n_ -= k; return true; } bool read(std::string& s) { auto* beg = reinterpret_cast<char const*>(p_); auto* end = reinterpret_cast<char const*>(memchr(p_, 0, n_)); if (!end) { return false; } s.assign(beg, end); p_ += s.size() + 1; n_ -= s.size() + 1; return true; } uint8_t const* p_; size_t n_; }; <file_sep>#pragma once #include <array> #include <memory> #include <string> namespace poe::util { using sha256_digest = std::array<uint8_t, 32>; std::string digest_to_string(sha256_digest const &digest); struct sha256 { virtual ~sha256() {} virtual void reset() = 0; virtual void feed(uint8_t const *data, size_t size) = 0; virtual sha256_digest finish() = 0; }; sha256_digest oneshot_sha256(uint8_t const *data, size_t size); std::unique_ptr<sha256> incremental_sha256(); } // namespace poe::util<file_sep>#include <poe/format/ggpk.hpp> #include <poe/util/murmur2.hpp> #include <poe/util/random_access_file.hpp> #include <poe/util/utf.hpp> #include <variant> namespace poe::format::ggpk { struct raw_entry { uint32_t rec_len_; chunk_tag tag_; uint64_t offset_; std::u16string name_; poe::util::murmur2_32_digest name_hash_; poe::util::sha256_digest stored_digest_; struct directory { std::vector<uint32_t> hashes_; std::vector<uint64_t> offsets_; }; struct file { uint64_t data_offset_; uint64_t data_size_; }; using info = std::variant<directory, file>; info info_; }; using entry_lookup = std::map<uint64_t, raw_entry>; struct index_builder { index_builder(poe::util::mmap_source const& source, entry_lookup const& entries) : source_(source), entries_(entries) {} poe::util::mmap_source const &source_; entry_lookup const &entries_; std::unique_ptr<parsed_entry> index_entry(uint64_t offset); std::unique_ptr<parsed_file> index_file(raw_entry const &e); std::unique_ptr<parsed_directory> index_directory(raw_entry const &e); }; std::unique_ptr<parsed_file> index_builder::index_file(raw_entry const &e) { auto info = std::get_if<raw_entry::file>(&e.info_); if (!info) { return {}; } auto ret = std::make_unique<parsed_file>(); ret->offset_ = e.offset_; ret->name_ = e.name_; ret->stored_digest_ = e.stored_digest_; ret->data_offset_ = info->data_offset_; ret->data_size_ = info->data_size_; return ret; } std::unique_ptr<parsed_directory> index_builder::index_directory(raw_entry const &e) { auto info = std::get_if<raw_entry::directory>(&e.info_); if (!info) { return {}; } auto dir_obj = std::make_unique<parsed_directory>(); dir_obj->offset_ = e.offset_; dir_obj->name_ = e.name_; dir_obj->stored_digest_ = e.stored_digest_; { size_t child_count = info->hashes_.size(); for (size_t i = 0; i < child_count; ++i) { auto child_obj = index_entry(info->offsets_[i]); if (!child_obj) { return {}; } child_obj->name_hash_ = info->hashes_[i]; child_obj->parent_ = dir_obj.get(); dir_obj->entries_.push_back(std::move(child_obj)); } } return dir_obj; } std::unique_ptr<parsed_entry> index_builder::index_entry(uint64_t offset) { auto raw = entries_.find(offset); if (raw == entries_.end()) { return {}; } auto &e = raw->second; if (e.tag_ == FILE_TAG) { return index_file(e); } else if (e.tag_ == PDIR_TAG) { return index_directory(e); } return {}; } std::unique_ptr<parsed_ggpk> index_ggpk(std::filesystem::path pack_path) { std::error_code ec; auto source = mio::make_mmap<poe::util::mmap_source>(pack_path.string(), 0, mio::map_entire_file, ec); if (ec) { return {}; } std::map<uint64_t, raw_entry> entries; { // Sweep file linearly for FILE and PDIR entries, jumping over FREE and GGPK chunks uint64_t offset = 0; uint64_t end = source.size(); while (offset < end) { if (end - offset < 8) { return {}; } uint32_t rec_len{}; ggpk::chunk_tag tag{}; memcpy(&rec_len, source.data() + offset, 4); if (offset + rec_len > end) { return {}; } memcpy(&tag, source.data() + offset + 4, 4); if (tag == ggpk::FILE_TAG || tag == ggpk::PDIR_TAG) { bool is_dir = tag == ggpk::PDIR_TAG; auto o = offset + 8; uint32_t name_len; memcpy(&name_len, source.data() + o, 4); o += 4; uint32_t child_count{}; if (is_dir) { memcpy(&child_count, source.data() + o, 4); o += 4; } poe::util::sha256_digest digest; memcpy(digest.data(), source.data() + o, digest.size()); o += digest.size(); if (name_len == 0) { return {}; } std::vector<char16_t> name_buf(name_len); memcpy(name_buf.data(), source.data() + o, name_buf.size() * 2); o += name_buf.size() * 2; std::u16string name(name_buf.data()); std::u16string name_lower = poe::util::lowercase(name.data()); auto name_hash = poe::util::oneshot_murmur2_32(reinterpret_cast<std::byte const*>(name_lower.data()), name_lower.size() * 2); std::vector<uint32_t> child_hashes(child_count); std::vector<uint64_t> child_offsets(child_count); if (is_dir) { for (size_t i = 0; i < child_count; ++i) { memcpy(&child_hashes[i], source.data() + o, 4); o += 4; memcpy(&child_offsets[i], source.data() + o, 8); o += 8; } } raw_entry::info info; if (is_dir) { raw_entry::directory d; d.hashes_ = child_hashes; d.offsets_ = child_offsets; info = d; } else { raw_entry::file f; f.data_offset_ = o; f.data_size_ = rec_len - (o - offset); info = f; } raw_entry entry; entry.rec_len_ = rec_len; entry.tag_ = tag; entry.offset_ = offset; entry.name_ = std::move(name); entry.name_hash_ = name_hash; entry.stored_digest_ = digest; entry.info_ = std::move(info); entries[offset] = std::move(entry); } else if (tag != ggpk::FREE_TAG && tag != ggpk::GGPK_TAG) { return {}; } offset += rec_len; } } auto reader = poe::util::make_stream_reader(source, 0); struct ggpk_header { uint32_t rec_len; poe::format::ggpk::chunk_tag tag; uint32_t version; std::array<uint64_t, 2> children; } ggpk_h; if (!reader->read_one(ggpk_h.rec_len) || !reader->read_one(ggpk_h.tag) || ggpk_h.tag != poe::format::ggpk::GGPK_TAG || !reader->read_one(ggpk_h.version) || (uint64_t)ggpk_h.children.size() * 12 > source.size()) { return {}; } if (!reader->read_many(ggpk_h.children.data(), ggpk_h.children.size())) { return {}; } bool free_encountered = false; bool pdir_encountered = false; auto ret = std::make_unique<parsed_ggpk>(); for (auto child : ggpk_h.children) { if (child > source.size()) { return {}; } if (child == 0) { free_encountered = true; // assume zero offset means no FREE chunk continue; } uint32_t rec_len; poe::format::ggpk::chunk_tag tag; auto reader = poe::util::make_stream_reader(source, child); if (!reader->read_one(rec_len) || !reader->read_one(tag)) { return {}; } if (tag == poe::format::ggpk::FREE_TAG) { if (free_encountered) { return {}; } ret->free_offset_ = child; free_encountered = true; } else if (tag == poe::format::ggpk::PDIR_TAG) { if (pdir_encountered) { return {}; } auto indexer = index_builder{source, entries}; auto root_entry = indexer.index_entry(child); auto root_dir = dynamic_cast<parsed_directory*>(root_entry.get()); if (!root_dir) { return {}; } ret->root_entry_ = std::move(root_entry); ret->root_ = root_dir; pdir_encountered = true; } else { return {}; } } if (!free_encountered || !pdir_encountered) { return {}; } ret->version_ = ggpk_h.version; ret->mapping_ = std::move(source); return ret; } } // namespace poe::format::ggpk<file_sep>#include "path_rep.h" #include "util.h" /* The blocks in the tail section of the index bundle are generated through an * alternating-phase algorithm where in the first phase a set of strings are built * to serve as bases for the second phase where they are combined with suffixes * to form the full outputs of the algorithm. * * u32 words control the generation and strings are null-terminated UTF-8. * A zero word toggles the phase, input starts with a 0 to indicate the base phase. * * In the base phase a non-zero word inserts a new string into the base set or * inserts a the concatenation of the base string and the following input. * * In the generation phase a non-zero word references a string in the base set * and outputs the concatenation of the base string and the following input. * * The index words are one-based where 1 refers to the first string. * * A zero can toggle back to the generation phase in which all base strings shall * be removed as if starting from scratch. * * The template section can be empty (two zero words after each other), typically * done to emit a single string as-is. */ std::vector<std::string> generate_paths(void const* spec_data, size_t spec_size) { reader r(spec_data, spec_size); bool base_phase = false; std::vector<std::string> bases; std::vector<std::string> results; while (r.n_) { uint32_t cmd; if (!r.read(cmd)) { abort(); } if (cmd == 0) { base_phase = !base_phase; if (base_phase) { bases.clear(); } } if (cmd != 0) { std::string fragment; if (!r.read(fragment)) { abort(); } // the input is one-indexed size_t index = cmd - 1; if (index < bases.size()) { // Back-ref to existing string, concatenate and insert/emit. std::string full = bases[index] + fragment; if (base_phase) { bases.push_back(full); } else { results.push_back(full); } } else { // New string, insert or emit as-is. if (base_phase) { bases.push_back(fragment); } else { results.push_back(fragment); } } } } return results; } void explain_paths(void const* spec_data, size_t spec_size) { reader r(spec_data, spec_size); bool base_phase = false; std::vector<std::string> bases; std::vector<std::string> results; while (r.n_) { uint32_t cmd; if (!r.read(cmd)) { abort(); } fprintf(stderr, "Command %08u\n", cmd); if (cmd == 0) { base_phase = !base_phase; if (base_phase) { fprintf(stderr, "Entering template phase\n"); bases.clear(); } else { fprintf(stderr, "Entering generation phase\n"); } } if (cmd != 0) { std::string fragment; if (!r.read(fragment)) { abort(); } // the input is one-indexed size_t index = cmd - 1; if (index < bases.size()) { // Back-ref to existing string, concatenate and insert/emit. std::string full = bases[index] + fragment; if (base_phase) { bases.push_back(full); fprintf(stderr, "Add new reference %zu \"%s\" + \"%s\"\n", bases.size(), bases[index].c_str(), fragment.c_str()); } else { results.push_back(full); fprintf(stderr, "Generating string \"%s\" + \"%s\"\n", bases[index].c_str(), fragment.c_str()); } } else { // New string, insert or emit as-is. if (base_phase) { bases.push_back(fragment); fprintf(stderr, "Add new reference %zu \"%s\"\n", bases.size(), fragment.c_str()); } else { results.push_back(fragment); fprintf(stderr, "Generate string \"%s\"\n", fragment.c_str()); } } } } }<file_sep>#pragma once #include <mio/mio.hpp> #include <array> #include <atomic> #include <cstdint> #include <cstring> #include <filesystem> #include <optional> #include <vector> namespace poe::util { class random_access_file { public: explicit random_access_file(std::filesystem::path path); ~random_access_file(); random_access_file(random_access_file &) = delete; random_access_file &operator=(random_access_file &) = delete; uint64_t size() const; bool read_exact(uint64_t offset, std::byte *p, uint64_t n) const; uint64_t read_some(uint64_t offset, std::byte *p, uint64_t n) const; uint64_t debug_number_of_os_reads() const { return number_of_os_reads_; } uint64_t debug_number_of_exact_reads() const { return number_of_exact_reads_; } std::string debug_render_histogram() const; private: uintptr_t os_handle_; std::optional<uint64_t> cached_size_; mutable std::atomic<uint64_t> number_of_os_reads_ = 0; mutable std::atomic<uint64_t> number_of_exact_reads_ = 0; mutable std::array<std::atomic<uint64_t>, 32> histogram_buckets_; }; using mmap_source = mio::basic_mmap_source<std::byte>; inline uint64_t read_some(std::byte const *src_data, uint64_t src_size, uint64_t offset, std::byte *p, size_t n) { if (!n) { return 0; } uint64_t end = (std::min)(offset + n, src_size); uint64_t amount = end - offset; if (!amount) { return 0; } std::memcpy(p, src_data + offset, amount); return amount; } inline uint64_t read_some(mmap_source const &source, uint64_t offset, std::byte *p, size_t n) { return read_some(source.data(), source.size(), offset, p, n); } inline bool read_exact(mmap_source const &source, uint64_t offset, std::byte *p, size_t n) { if (!n) { return true; } if (offset + n > source.size()) { return false; } std::memcpy(p, source.data() + offset, n); return true; } struct stream_reader { stream_reader(std::byte const *p, size_t n, uint64_t offset) : data_(p), size_(n), cursor_(offset), buffer_(8 << 10), buffer_valid_begin_(0), buffer_valid_end_(0), buffer_cursor_(offset) {} stream_reader(mmap_source const &file, uint64_t offset) : stream_reader(file.data(), file.size(), offset) {} bool read_exact(std::byte *p, size_t n) { if (!n) { return true; } while (true) { size_t in_buffer = buffer_valid_end_ - buffer_valid_begin_; size_t amount = (std::min)(in_buffer, n); memcpy(p, buffer_.data() + buffer_valid_begin_, amount); buffer_valid_begin_ += amount; p += amount; n -= amount; cursor_ += amount; if (!n) { break; } buffer_valid_begin_ = 0; if (n > buffer_.size()) { if (!read_some(data_, size_, buffer_cursor_, p, n)) { return false; } buffer_cursor_ += n; buffer_valid_end_ = 0; return true; } else { buffer_valid_begin_ = 0; buffer_valid_end_ = read_some(data_, size_, buffer_cursor_, buffer_.data(), buffer_.size()); buffer_cursor_ += buffer_valid_end_; if (buffer_valid_end_ == 0) { return false; } } } return true; } template <typename T> bool read_one(T &t) { constexpr size_t N = sizeof(T); std::array<std::byte, N> buf; if (!read_exact(buf.data(), buf.size())) { return false; } memcpy(&t, buf.data(), buf.size()); return true; } template <typename T> bool read_many(T *t, size_t n) { if (!n) { return true; } size_t const N = sizeof(T) * n; std::vector<std::byte> buf(N); if (!read_exact(buf.data(), buf.size())) { return false; } memcpy(t, buf.data(), buf.size()); return true; } bool read_terminated_u16string(std::u16string &s, size_t cch_including_terminator) { std::vector<char16_t> buf((std::max<size_t>)(1u, cch_including_terminator)); if (!read_many(buf.data(), buf.size())) { return false; } s = std::u16string(buf.data()); return true; } bool skip(uint64_t n) { auto buffer_cut = (std::min)(buffer_valid_end_ - buffer_valid_begin_, n); if (buffer_cut != 0) { n -= buffer_cut; buffer_valid_begin_ += buffer_cut; } if (cursor_ + n <= size_) { cursor_ += n; return true; } return false; } uint64_t cursor() const { return cursor_; } private: std::byte const *data_; uint64_t size_; uint64_t cursor_; std::vector<std::byte> buffer_; uint64_t buffer_valid_begin_; uint64_t buffer_valid_end_; uint64_t buffer_cursor_; }; inline std::unique_ptr<stream_reader> make_stream_reader(std::byte const *p, size_t n, uint64_t offset) { return std::make_unique<stream_reader>(p, n, offset); } inline std::unique_ptr<stream_reader> make_stream_reader(mmap_source const &file, uint64_t offset) { return std::make_unique<stream_reader>(std::cref(file), offset); } } // namespace poe::util<file_sep>#pragma once #include <cstddef> #include <cstdint> uint64_t fnv1_64(void const* data, size_t n); uint64_t fnv1a_64(void const* data, size_t n); struct FNV1A64 { FNV1A64(); uint64_t feed(void const* data, size_t n); uint64_t hash_; };<file_sep>add_library(libpoe STATIC "poe/format/ggpk.cpp" "poe/format/ggpk.hpp" "poe/util/install_location.cpp" "poe/util/install_location.hpp" "poe/util/murmur2.cpp" "poe/util/murmur2.hpp" "poe/util/random_access_file.cpp" "poe/util/random_access_file.hpp" "poe/util/sha256.cpp" "poe/util/sha256.hpp" "poe/util/utf.cpp" "poe/util/utf.hpp" ) target_include_directories(libpoe PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/mio/single_include)<file_sep>#include <bun.h> #include <cstdio> #include <filesystem> #include <fstream> #include <iostream> #include <regex> #include <string> #include <unordered_map> #include <unordered_set> #include "ggpk_vfs.h" #include "path_rep.h" #include "util.h" #include <poe/util/utf.hpp> using namespace std::string_view_literals; static char const* const USAGE = "bun_extract_file list-files GGPK_OR_STEAM_DIR\n" "bun_extract_file extract-files [--regex] GGPK_OR_STEAM_DIR OUTPUT_DIR [FILE_PATHS...]\n\n" "GGPK_OR_STEAM_DIR should be either a full path to a Standalone GGPK file or the Steam game directory.\n" "If FILE_PATHS are omitted the file paths are taken from stdin.\n" "If --regex is given, FILE_PATHS are interpreted as regular expressions to match.\n"; int main(int argc, char* argv[]) { std::error_code ec; if (argc < 2 || argv[1] == "--help"sv || argv[1] == "-h"sv) { fprintf(stderr, USAGE); return 1; } std::string command; std::filesystem::path ggpk_or_steam_dir; std::filesystem::path output_dir; bool use_regex = false; std::vector<std::string> tail_args; command = argv[1]; int argi = 2; while (argi < argc) { if (argv[argi] == "--regex"sv) { use_regex = true; ++argi; } else { break; } } if (command == "list-files"sv) { if (argi < argc) { ggpk_or_steam_dir = argv[argi++]; } if (argi != argc) { fprintf(stderr, USAGE); return 1; } } else if (command == "extract-files"sv) { if (argi + 1 < argc) { ggpk_or_steam_dir = argv[argi++]; output_dir = argv[argi++]; while (argi < argc) { tail_args.push_back(argv[argi++]); } } } else { fprintf(stderr, USAGE); return 1; } std::shared_ptr<GgpkVfs> vfs; if (ggpk_or_steam_dir.extension() == ".ggpk") { vfs = open_ggpk(ggpk_or_steam_dir); } #if _WIN32 std::string ooz_dll = "libooz.dll"; #else std::string ooz_dll = "liblibooz.so"; #endif Bun* bun = BunNew(ooz_dll.c_str(), "Ooz_Decompress"); if (!bun) { bun = BunNew(("./" + ooz_dll).c_str(), "Ooz_Decompress"); if (!bun) { fprintf(stderr, "Could not initialize Bun library\n"); return 1; } } BunIndex* idx = BunIndexOpen(bun, borrow_vfs(vfs), ggpk_or_steam_dir.string().c_str()); if (!idx) { fprintf(stderr, "Could not open index\n"); return 1; } if (command == "list-files") { auto rep_mem = BunIndexPathRepContents(idx); for (size_t path_rep_id = 0;; ++path_rep_id) { uint64_t hash; uint32_t offset; uint32_t size; uint32_t recursive_size; if (BunIndexPathRepInfo(idx, (int32_t)path_rep_id, &hash, &offset, &size, &recursive_size) < 0) { break; } auto generated = generate_paths(rep_mem + offset, size); for (auto& p : generated) { std::cout << p << std::endl; } } return 0; } std::vector<std::string> wanted_paths = tail_args; if (wanted_paths.empty()) { std::string line; while (std::getline(std::cin, line)) { wanted_paths.push_back(line); } } std::vector<std::regex> regexes; if (use_regex) { bool regexes_good = true; for (auto& path : wanted_paths) { try { regexes.push_back(std::regex(path)); } catch (std::exception& e) { fprintf(stderr, "Could not compile regex \"%s\": %s\n", path.c_str(), e.what()); regexes_good = false; } } if (!regexes_good) { return 1; } if (command == "extract-files") { std::unordered_set<std::string> matching_paths; auto rep_mem = BunIndexPathRepContents(idx); for (size_t path_rep_id = 0;; ++path_rep_id) { uint64_t hash; uint32_t offset; uint32_t size; uint32_t recursive_size; if (BunIndexPathRepInfo(idx, (int32_t)path_rep_id, &hash, &offset, &size, &recursive_size) < 0) { break; } auto generated = generate_paths(rep_mem + offset, size); for (auto& p : generated) { if (!matching_paths.count(p)) { for (auto& r : regexes) { if (std::regex_match(p, r)) { matching_paths.insert(p); } } } } } wanted_paths.assign(matching_paths.begin(), matching_paths.end()); } } struct extract_info { std::string path; uint32_t offset; uint32_t size; }; std::unordered_map<uint32_t, std::vector<extract_info>> bundle_parts_to_extract; for (auto path : wanted_paths) { if (path.front() == '"' && path.back() == '"') { path = path.substr(1, path.size() - 2); } int32_t file_id = BunIndexLookupFileByPath(idx, path.c_str()); if (file_id < 0) { fprintf(stderr, "Could not find file \"%s\"\n", path.c_str()); } uint32_t bundle_id; uint64_t path_hash; extract_info ei; ei.path = path; BunIndexFileInfo(idx, file_id, &path_hash, &bundle_id, &ei.offset, &ei.size); bundle_parts_to_extract[bundle_id].push_back(ei); } size_t extracted = 0; size_t missed = 0; for (auto& [bundle_id, parts] : bundle_parts_to_extract) { std::vector<uint8_t> bundle_data; auto bundle_mem = BunIndexExtractBundle(idx, bundle_id); if (!bundle_mem) { missed += parts.size(); char const* name; uint32_t cb; BunIndexBundleInfo(idx, bundle_id, &name, &cb); fprintf(stderr, "Could not open bundle \"%s\", missing %zu files.\n", name, parts.size()); continue; } for (auto& part : parts) { std::filesystem::path output_path = output_dir / part.path; std::filesystem::create_directories(output_path.parent_path(), ec); if (!dump_file(output_path, bundle_mem + part.offset, part.size)) { fprintf(stderr, "Could not write file \"%s\"\n", output_path.string().c_str()); ++missed; continue; } ++extracted; } BunMemFree(bundle_mem); } fprintf(stderr, "Done, %zu/%zu extracted, %zu missed.\n", extracted, wanted_paths.size(), missed); BunIndexClose(idx); BunDelete(bun); return 0; }
d2488a393cf61ec5264634df8ff6da3ad8260152
[ "C", "Python", "CMake", "C++" ]
27
CMake
erosson/ooz
57a8a22c09330e35664be87460547b1e3f22e597
6520f525a5ada39d8300446751dd816fe267e87e
refs/heads/master
<file_sep>class SessionsController < ApplicationController def new @user = User.new end def destroy session[:user_id] = nil flash[:alert] = "sucessfully logged out" redirect_to root_path end def create # passing in username and password # setting to instance variable username = params[:username] password = params[:password] # using the params username we should be able to find with this # where will always return an array...must state .first # want a single user, not an array within an array @user = User.where(username: username).first # if they entered wrong username if @user.nil? flash[:alert] = "Not a user" # redirect_to...find a path to redirect to OR redirect_to root_path else # success password case if @user.password == <PASSWORD> session[:user_id] = @user.id flash[:alert] = "Welcome" redirect_to posts_path else # wrong password case flash[:alert] = "Incorrect password" redirect_to root_path end end end end <file_sep>class CommentsController < ApplicationController def create # used relationship with user and comments @comment = current_user.comments.create whitelisted_params # after create comment this redirect to post index redirect_to posts_path end def show end private def whitelisted_params # only the attributes of an individual comment which are permitted here are allowed to save to the comment params.require(:comment).permit(:commentbody, :post_id) end end <file_sep> <div id="video-background"> <%= video_tag '("empty_theater_stage.mp4", controls: false, autoplay: true, preload: auto)' %> </div> <video id = "video-background" preload = "auto" autoplay = "true" loop = "loop"> <source type="video/webm" src="/assets/empty_theater_stage.webm" /> <source type="video/mp4" src="/assets/empty_theater_stage.mp4" /> </video> <% @posts.order(created_at: :desc).each do |post| %> <div class="post_comment"> <div class="post"> <h3> <%= post.title %> </h3> <div id="border"></div> <p> <%= truncate post.body, length: 150 %> <% if post.body.length > 150 %> <%= link_to "Read More", user_path(post.user_id), id:"readmore" %> <% end %> </p> <p id="by"> Posted by: <%= link_to post.user.fname, user_path(post.user_id) %> <span>at</span> <%= post.created_at.to_s(:long) %> </p> </div> <div class="comment"> <h3>Comments?</h3> <% if current_user %> <%= form_for Comment.new do |f| %> <%= f.text_area :comment%> <%= f.hidden_field :post_id, value: post.id %> </br> <%= f.submit :submit %> <% end %> <% end %> <% post.comments.each do |comment| %> <p> <%= comment.comment %> </p> <p id="by"> Posted by <%= comment.user.username %> <span>at</span> <%= comment.created_at.to_s(:short) %> </p> <% end %> </div> </div> <% end %> <file_sep>class User < ActiveRecord::Base # when user deletes account they can delete comments & posts assiciated with a deleted user account has_many :posts, dependent: :destroy has_many :comments, dependent: :destroy end
5811452f00ac45c6a56f140092e0e553bd909682
[ "RDoc", "Ruby" ]
4
Ruby
stephsem23/DevTalk
6ee02b2e16c409549c918155c0f7f8c05dec3752
260a2d52b6e3815172dd330e406e50d8b546a34c
refs/heads/master
<file_sep>package com.github.michalszukala.luckyhit; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.chart.ScatterChart; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.layout.GridPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; import java.awt.*; import java.io.IOException; import java.net.URI; public class Main extends Application { private SearchingForLinks search = new SearchingForLinks(); public static void main(String[] args) { launch(args); } //setting up stage, layout and all the elements on the layout @Override public void start(Stage primaryStage) throws Exception{ GridPane layout = layout(); TextField startingUrl = startingUrl(); Button buttonLuckyHit = buttonLuckyHit(startingUrl, layout); layout.getChildren().addAll(startingUrl, buttonLuckyHit); primaryStage.setTitle("Lucky Hit"); Scene scene = new Scene(layout, 500, 300); primaryStage.setScene(scene); primaryStage.setResizable(false); primaryStage.show(); } //creating layout public GridPane layout(){ GridPane layout = new GridPane(); layout.setAlignment(Pos.CENTER); layout.setHgap(20); layout.setVgap(20); layout.setPadding(new Insets(25, 25, 25, 25)); layout.setStyle("-fx-background-color: #383838"); return layout; } //creating TextField for starting Url public TextField startingUrl(){ TextField startingUrl = new TextField(); startingUrl.setPrefWidth(380); startingUrl.setPromptText("Type your starting page, and wait......"); startingUrl.setStyle("-fx-prompt-text-fill: derive(-fx-control-inner-background,-30%); -fx-font-size: 18"); return startingUrl; } //creating button that display the "lucky" link public Button buttonResult(String message){ Button button = new Button(message); button.setStyle("-fx-font-size: 11; -fx-font-weight: bold"); GridPane.setConstraints(button,0,2); button.setPrefSize(380, 35); return button; } //creating button that display a chart for all the searched links public Button buttonChart(){ Button button = new Button("Chart Analysis"); GridPane.setConstraints(button,1,2); button.setPrefSize(100, 25); button.setStyle("-fx-font-size: 11; -fx-font-weight: bold"); button.setOnAction(e->{ Stage chartStage = new Stage(); chartStage.setTitle("Lucky-Hit Chart"); Scene sceneChart = chartScene(); chartStage.setScene(sceneChart); chartStage.show(); }); return button; } //creating button that will access SearchForLinks starting method and will search for "lucky" link public Button buttonLuckyHit( TextField startingUrl, GridPane layout){ Button button = new Button("Lucky-Hit"); GridPane.setConstraints(button,1,0); button.setMinWidth(100); button.setStyle("-fx-font-size: 14; -fx-font-weight: bold"); button.setOnAction(e -> { String startingPage = startingUrl.getText(); startingPage = startingPage.trim(); if(startingPage.isEmpty()){ Button buttonResult = buttonResult("No URL, Try new one"); layout.getChildren().add(buttonResult); } else { String luckyHit = search.start(startingPage); if (luckyHit != null) { Button buttonResult = buttonResult(luckyHit); Button buttonChart = buttonChart(); layout.getChildren().add(buttonResult); layout.getChildren().add(buttonChart); buttonResult.setOnAction(e1->{ try { Desktop.getDesktop().browse(URI.create(luckyHit)); } catch (IOException ex) { ex.printStackTrace(); } }); } else { Button buttonResult = buttonResult("Wrong URL, Try new one"); layout.getChildren().add(buttonResult); } } }); return button; } //creating new scene with the chart on it public Scene chartScene (){ ScatterChart scatterChart = search.chart(); VBox vbox = new VBox(scatterChart); Scene scene = new Scene(vbox, 500, 300); return scene; } } <file_sep>package com.github.michalszukala.luckyhit; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.ScatterChart; import javafx.scene.chart.XYChart; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Random; public class SearchingForLinks { private List<Integer> numberOfLinksArray = new ArrayList<>(); //Collecting all the links from web page and following the random link to the new place on the web public String start(String startingUrl){ String luckyLink; List<String> oldArrayList; List<String> arrayList; numberOfLinksArray.clear(); int count = 0; arrayList = linksOnPage("http://" + startingUrl); if(arrayList.size() == 0) { return null; } do { oldArrayList = new ArrayList<>(arrayList); int numberOfLinks = arrayList.size(); if(numberOfLinks != 0) numberOfLinksArray.add(numberOfLinks); luckyLink = randomLink(arrayList); arrayList = linksOnPage(luckyLink); if(arrayList.size() == 0) { arrayList = oldArrayList; } count++; }while(count < 12); return luckyLink; } //it scraping the web page and returning ArrayList with all the possible links on the web page public List<String> linksOnPage(String startingUrl) { List<String> linksArray = new ArrayList<>(); try { Document doc = Jsoup.connect(startingUrl).ignoreContentType(true).userAgent("Mozilla").get(); Elements linksOnPage = doc.select("a[href]"); for (Element link : linksOnPage) { String validLink = link.attr("href"); if (validLink.contains("http://") || validLink.contains("https://")) { linksArray.add(link.attr("href")); } } } catch (IOException e) {} return linksArray; } // from the ArrayList of links is choosing one random link public String randomLink(List<String> linksArray){ int randomNumber; String randomLink; Random randomGenerator = new Random(); randomNumber = randomGenerator.nextInt(linksArray.size()); randomLink = linksArray.get(randomNumber); return randomLink; } //from all the links will generate the chart public ScatterChart chart(){ NumberAxis xAxis = new NumberAxis(); xAxis.setLabel("Number of the web page"); NumberAxis yAxis = new NumberAxis(); yAxis.setLabel("Number of links"); ScatterChart scatterChart = new ScatterChart(xAxis, yAxis); XYChart.Series dataSeries = new XYChart.Series(); dataSeries.setName("Number of links per visited web page"); for(int i = 0; i < numberOfLinksArray.size(); i++){ dataSeries.getData().add(new XYChart.Data( (i + 1), numberOfLinksArray.get(i))); } scatterChart.getData().add(dataSeries); return scatterChart; } } <file_sep>"Lucky Hit" is a program that will lead you to the darkest places of the Internet. After providing a starting URL, it will scrape the web page for all the links and randomly follow one until you reach an unknown place on the net. It is also providing charts with the number of all the links it scraped on the way. The code is written using JavaFX in two versions, with the use of FXML and without. Code was written in Intelji 2017. The executable file is in out/artifacts/LuckyHit_jar folder. ![](LuckyHitFXML/Screenshot/Lucky-hit.png)
e211e09d37a2bcec2107b8777d5222d8c215de4a
[ "Markdown", "Java" ]
3
Java
MichalSzukala/Lucky-Hit
922632552dcf8cff40d1ae88312a6130da822658
1d149416846616131cd2f5ba1812afa3b2b96027
refs/heads/main
<repo_name>LucasSilvaMarts/Express-Exercise<file_sep>/index.js const express = require('express'); const app = express(); const recipes = [ { id: 12345, name: '<NAME>', ingredients: ['farofa', 'bacon'] }, { id: 12346, name: '<NAME>', ingredients: ['ovo'] } ] app.delete('/recipe/:id', (req, res) => { const result = deleteRecipes(req.params.id); res.send(result); }); function deleteRecipes(id) { const result = recipes.find((i) => i.id === parseInt(id, 10)); if(!result) { return 'recipe not found' } else { return result } } app.listen(3001, () => { console.log('Hello'); });
2f422b23a71d80be6614f895692f44449f00b4ac
[ "JavaScript" ]
1
JavaScript
LucasSilvaMarts/Express-Exercise
2121c670a6532926e8da9671169349b2548ab703
75ac35184d395514163c0df0c112380209078ecc
refs/heads/master
<repo_name>Nathanael2611/Nathanael2611-Launcher-Commons<file_sep>/settings.gradle rootProject.name = 'Nathanael2611-Launcher-Commons' <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/versions/Download.java package fr.nathanael2611.commons.launcher.update.minecraft.versions; public class Download { private String sha1; private String url; private String size; public Download(final String sha1, final String url, final String size) { this.sha1 = sha1; this.url = url; this.size = size; } public String getArtifactURL(final String name) { if (name == null) { throw new IllegalStateException("Cannot get artifact dir of empty/blank artifact"); } final String[] parts = name.split(":", 4); final String text = String.format("%s/%s/%s", parts[0].replaceAll("\\.", "/"), parts[1], parts[2]); if (parts.length == 4) { return String.valueOf(text) + "/" + parts[1] + "-" + parts[2] + "-" + parts[3] + ".jar"; } return String.valueOf(text) + "/" + parts[1] + "-" + parts[2] + ".jar"; } public String getSha1() { return this.sha1; } public void setSha1(final String sha1) { this.sha1 = sha1; } public String getUrl() { return this.url; } public void setUrl(final String url) { this.url = url; } public String getSize() { return this.size; } public void setSize(final String size) { this.size = size; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/launch/LaunchManager.java package fr.nathanael2611.commons.launcher.launch; import fr.nathanael2611.commons.launcher.BaseLauncher; import java.util.Arrays; public class LaunchManager { private BaseLauncher launcher; private String serverIp = null; public LaunchManager(BaseLauncher launcher) { this.launcher = launcher; } public void enableAutoServerConnect(String serverIp) { this.serverIp = serverIp; } public void disabledAutoServerConnect() { this.serverIp = null; } public void launch() { MinecraftLauncher launcher = new MinecraftLauncher(this.launcher); if(this.serverIp != null) { String[] parts = this.serverIp.split(":"); launcher.getArgs().add("--server=" + parts[0]); if(parts.length > 1) { launcher.getArgs().add("--port=" + parts[1]); } else { launcher.getArgs().add("--port=25565"); } } final int minRam = 512; launcher.getVmArgs().addAll(Arrays.asList("-Xms" + minRam + "M", "-Xmx" + (int) (this.launcher.getLoginManager().getRam() * 1000) + "M")); try { launcher.launch(); } catch (LaunchException e) { e.printStackTrace(); } System.exit(0); } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/LightVersion.java package fr.nathanael2611.commons.launcher.update.minecraft; import fr.nathanael2611.commons.launcher.BaseLauncher; import fr.nathanael2611.commons.launcher.update.UpdateManager; import fr.nathanael2611.commons.launcher.update.minecraft.versions.CompleteVersion; import fr.nathanael2611.commons.launcher.update.minecraft.versions.ForgeVersion; import java.net.URL; public class LightVersion extends fr.nathanael2611.commons.launcher.update.minecraft.versions.Version { private CompleteVersion completeVersion; private ForgeVersion forgeVersion; public void setId(String id) { super.setID(id); } public void setUrl(URL url) { super.setUrl(url); } public void setType(fr.nathanael2611.commons.launcher.update.minecraft.Version.VersionType type) { super.setType(type); } public void setForgeVersion(ForgeVersion forgeVersion) { this.forgeVersion = forgeVersion; } public ForgeVersion getForgeVersion() { return forgeVersion; } @Override public URL getUrl() { return super.getUrl(); } public String getId() { return super.getId(); } public fr.nathanael2611.commons.launcher.update.minecraft.Version.VersionType getVersionType() { return super.getType(); } public CompleteVersion getCompleteVersion() { return completeVersion; } public void setCompleteVersion(CompleteVersion completeVersion) { this.completeVersion = completeVersion; } @Override public Game update(BaseLauncher launcher) { UpdateManager manager = launcher.getUpdateManager(); manager.setMinecraftVersionDownloader(new VersionDownloader(launcher)); Game game = manager.getMinecraftVersionDownloader().downloadVersion(launcher, this, this.getCompleteVersion()); manager.getMinecraftVersionDownloader().getDownloadManager().check(); manager.getMinecraftVersionDownloader().getDownloadManager().startDownload(); manager.getMinecraftVersionDownloader().unzipNatives(); manager.getMinecraftVersionDownloader().getDownloadManager().check(); return game; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/download/DownloadManager.java package fr.nathanael2611.commons.launcher.update.minecraft.download; import fr.nathanael2611.commons.launcher.update.minecraft.utils.FileUtils; import fr.nathanael2611.commons.launcher.util.Helpers; import fr.nathanael2611.commons.launcher.util.MinecraftFolder; import java.io.File; import java.util.ArrayList; public class DownloadManager { private MinecraftFolder folder; public ArrayList<DownloadEntry> filesToDownload; public ArrayList<DownloadEntry> downloadedFile; private ArrayList<String> dontDelete; private int value; public DownloadManager(final MinecraftFolder folder) { this.filesToDownload = new ArrayList<DownloadEntry>(); this.downloadedFile = new ArrayList<DownloadEntry>(); this.dontDelete = new ArrayList<String>(); this.folder = folder; } public DownloadEntry addDownloadableFile(final DownloadEntry file) { if (!this.filesToDownload.contains(file)) { this.dontDelete.add(file.getDestination().getAbsolutePath()); if (file.needDownload()) { this.filesToDownload.add(file); } } return file; } public void startDownload() { if (this.filesToDownload.size() == 0) { Helpers.sendMessageInConsole("[MinecraftDownloader] Nothing to download!", false); return; } value = this.filesToDownload.size(); Helpers.sendMessageInConsole("[MinecraftDownloader] " + this.filesToDownload.size() + " files to download.", false); for (final DownloadEntry download : this.filesToDownload) { Helpers.sendMessageInConsole("[MinecraftDownloader] Download: " + download.getURL() + " | " + getDownloadPercentage() + "% | " + downloadedFile.size() + "/" + filesToDownload.size(), false); download.download(); this.downloadedFile.add(download); } Helpers.sendMessageInConsole("[MinecraftDownloader] Finished download !", false); } private int getPercentToDownload() { return (value / this.filesToDownload.size()) * 100; } public static int crossMult(int value, int maximum, int coefficient) { return (int) ((double) value / (double) maximum * (double) coefficient); } public int removeSurplus(final File folder) { final ArrayList<File> files = FileUtils.listFilesForFolder(folder); int count = 0; for (final File f : files) { if (f.isDirectory()) { boolean good = true; final ArrayList<File> files2 = FileUtils.listFilesForFolder(f); if (files2.isEmpty()) { f.delete(); } else { for (final File f2 : files2) { if (!f2.isDirectory()) { good = true; break; } good = false; } if (!good) { f.delete(); } } } if (!this.dontDelete.contains(f.getAbsolutePath()) && !f.isDirectory()) { f.delete(); if (folder == this.folder.getNativesFolder()) { continue; } ++count; } } return count; } public void clearDownloads() { this.filesToDownload.clear(); this.downloadedFile.clear(); this.dontDelete.clear(); } public float getDownloadPercentage() { return ((downloadedFile.size() / this.filesToDownload.size()) * 100); } public boolean isDownloadFinished() { return this.filesToDownload.size() == 0; } public void check() { int count = 0; if (this.folder.getLibrariesFolder() != null && !this.folder.getLibrariesFolder().exists()) { this.folder.getLibrariesFolder().mkdirs(); } if (this.folder.getNativesFolder() != null && !this.folder.getNativesFolder().exists()) { this.folder.getNativesFolder().mkdirs(); } if (this.folder.getLibrariesFolder() != null) { count += this.removeSurplus(this.folder.getLibrariesFolder()); } if (count != 0) { Helpers.sendMessageInConsole("[MinecraftDownloader]Deleted " + count + " files.", false); } } public ArrayList<String> getDontDownload() { return this.dontDelete; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/login/model/response/AuthResponse.java /* * Copyright 2015 TheShark34 * * This file is part of OpenAuth. * OpenAuth 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 3 of the License, or * (at your option) any later version. * * OpenAuth 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 OpenAuth. If not, see <http://www.gnu.org/licenses/>. */ package fr.nathanael2611.commons.launcher.login.model.response; import fr.nathanael2611.commons.launcher.login.model.AuthProfile; /** * JSON Model of an authentication response * * @version 1.0.4 * @author Litarvan */ public class AuthResponse { /** * The access token */ private String accessToken; /** * The client token (same as the one given by the request) */ private String clientToken; /** * All available profiles */ private AuthProfile[] availableProfiles; /** * The current selected profile from the agent */ private AuthProfile selectedProfile; /** * Auth Response constructor * * @param accessToken * The access token * @param clientToken * The client token (same as the one given by the request) * @param availableProfiles * All available profiles * @param selectedProfile * The current selected profile from the agent */ public AuthResponse(String accessToken, String clientToken, AuthProfile[] availableProfiles, AuthProfile selectedProfile) { this.accessToken = accessToken; this.clientToken = clientToken; this.availableProfiles = availableProfiles; this.selectedProfile = selectedProfile; } /** * Returns the access token * * @return The access token */ public String getAccessToken() { return this.accessToken; } /** * Returns the client token (same as the one given by the request) * * @return The client token */ public String getClientToken() { return this.clientToken; } /** * Returns the available profiles * * @return The available profiles */ public AuthProfile[] getAvailableProfiles() { return this.availableProfiles; } /** * Returns the selected profile from the agent * * @return The selected profile */ public AuthProfile getSelectedProfile() { return this.selectedProfile; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/UpdateManager.java package fr.nathanael2611.commons.launcher.update; import fr.nathanael2611.commons.launcher.BaseLauncher; import fr.nathanael2611.commons.launcher.update.minecraft.Game; import fr.nathanael2611.commons.launcher.update.minecraft.Version; import fr.nathanael2611.commons.launcher.update.minecraft.VersionDownloader; import fr.nathanael2611.commons.launcher.util.Helpers; import fr.nathanael2611.commons.launcher.util.JavaUtil; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; public class UpdateManager { private BaseLauncher launcher; private String updateMessage; private String jreLink = null; private String jreMd5 = null; private Game game; private VersionDownloader minecraftVersionDownloader; private ConcurrentLinkedQueue<EazyUpdater> updaters = new ConcurrentLinkedQueue<>(); private Version version = null; private boolean isDownloading = false; private boolean isDownloadingMc = false; public UpdateManager(BaseLauncher launcher) { this.launcher = launcher; } public String getUpdateMessage() { return updateMessage; } public void setUpdateMessage(String updateMessage) { this.updateMessage = updateMessage; } public void enableCustomJre(String downloadLink, String md5) { this.jreLink = downloadLink; this.jreMd5 = md5; } public boolean hasCustomJre() { return this.jreLink != null && this.jreMd5 != null; } public void setMinecraftVersionDownloader(VersionDownloader minecraftVersionDownloader) { this.minecraftVersionDownloader = minecraftVersionDownloader; } public void setGame(Game game) { this.game = game; } public Game getGame() { return game; } public VersionDownloader getMinecraftVersionDownloader() { return minecraftVersionDownloader; } public Version getVersionObj() { if (this.version == null) { Helpers.sendMessageInConsole("Getting the version...", false); this.version = Version.build(this.launcher); } return this.version; } public void updateAll() { this.isDownloading = true; downloadJava(); if(!this.launcher.isMCP()) downloadMc(); this.updaters.forEach(updater -> { updater.startDownload(this); this.updaters.remove(); }); this.isDownloading = false; } public void downloadMc() { isDownloadingMc = true; updateMessage = "Verifying assets..."; Version version = this.getVersionObj(); updateMessage = "Downloading Minecraft..."; this.setGame(version.update()); isDownloadingMc = false; } public void downloadJava() { updateMessage = "Java verification"; Helpers.sendMessageInConsole("Vérification de votre version de Java..."); if(JavaUtil.hasJava64()) { Helpers.sendMessageInConsole("Vous avez Java 64 ! Tout est bon. ;)"); return; } else if(!hasCustomJre()) { Helpers.crash("Vous n'avez pas Java 64 bit !", "Désolé, pour jouer à Minecraft il faut avoir Java \n 64 bit."); } this.launcher.CUSTOM_JRE_DIR.mkdir(); try { if (this.launcher.CUSTOM_JRE_ZIP.exists()) { String md5 = DigestUtils.md5Hex(FileUtils.readFileToByteArray(this.launcher.CUSTOM_JRE_ZIP)); if (!md5.equalsIgnoreCase(this.jreMd5)) { Helpers.sendMessageInConsole("Mauvaise version du JRE... Suppression du Custom-JRE actuel...", true); FileUtils.forceDelete(this.launcher.CUSTOM_JRE_ZIP); FileUtils.deleteDirectory(this.launcher.CUSTOM_JRE_DIR); } else { Helpers.sendMessageInConsole("Vous avez la bonne version, \"fullgood\""); return; } } } catch (IOException ex){ ex.printStackTrace(); } updateMessage = "Downloading Java"; try { Helpers.sendMessageInConsole("Téléchargement de Java 64..."); FileUtils.copyURLToFile(new URL(this.jreLink), this.launcher.CUSTOM_JRE_ZIP); } catch (IOException e) { e.printStackTrace(); } updateMessage = "Unzipping JRE..."; Helpers.sendMessageInConsole("Unzipping JRE.."); try { fr.nathanael2611.commons.launcher.update.minecraft.utils.FileUtils.unzip(this.launcher.CUSTOM_JRE_ZIP, this.launcher.CUSTOM_JRE_DIR); } catch (IOException e) { e.printStackTrace(); } } public boolean isDownloadingMc() { return isDownloadingMc; } public boolean isDownloading() { return isDownloading; } public int getTotalFiles() { if(this.isDownloadingMc && this.minecraftVersionDownloader != null) return this.minecraftVersionDownloader.getDownloadManager().filesToDownload.size(); return this.getActualUpdater() != null ? this.getActualUpdater().getTotalFilesToDownload() : 0; } public int getDownloadedFiles() { if(this.isDownloadingMc && this.minecraftVersionDownloader != null) return this.minecraftVersionDownloader.getDownloadManager().downloadedFile.size(); return this.getActualUpdater() != null ? this.getActualUpdater().getDownloadedFiles() : 0; } public EazyUpdater getActualUpdater() { return this.updaters.peek(); } public ConcurrentLinkedQueue<EazyUpdater> getUpdaters() { return updaters; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/login/model/AuthError.java /* * Copyright 2015 TheShark34 * * This file is part of OpenAuth. * OpenAuth 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 3 of the License, or * (at your option) any later version. * * OpenAuth 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 OpenAuth. If not, see <http://www.gnu.org/licenses/>. */ package fr.nathanael2611.commons.launcher.login.model; /** * JSON model of an error * * @version 1.0.4 * @author Litarvan */ public class AuthError { /** * Short description of the error */ private String error; /** * Longer description wich can be shown to the user */ private String errorMessage; /** * Cause of the error (optional) */ private String cause; /** * Auth Error constructor * * @param error * Short description of the error * @param errorMessage * Longer description wich can be shown to the user * @param cause * Cause of the error */ public AuthError(String error, String errorMessage, String cause) { this.error = error; this.errorMessage = errorMessage; this.cause = cause; } /** * Returns the error (Short description of the error) * * @return The error */ public String getError() { return error; } /** * Returns the error message (Longer description of the error) * * @return The error message */ public String getErrorMessage() { return this.errorMessage; } /** * Returns the cause of the error * * @return The cause */ public String getCause() { return cause; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/util/MinecraftFolder.java package fr.nathanael2611.commons.launcher.util; import java.io.File; import java.net.URL; public class MinecraftFolder { private File gameFolder; private File librariesFolder; private File nativesFolder; private File assetsFolder; private File clientJarFile; private String clientJarSHA1; private URL clientJarURL; public MinecraftFolder(File gameFolder, File assetsFolder, File librariesFolder, File nativesFolder, File clientJarFile, URL clientJarURL, String clientJarSHA1) { this.gameFolder = gameFolder; this.librariesFolder = librariesFolder; this.nativesFolder = nativesFolder; this.assetsFolder = assetsFolder; this.clientJarFile = clientJarFile; this.clientJarURL = clientJarURL; this.clientJarSHA1 = clientJarSHA1; } public File getGameFolder() {return this.gameFolder;} public File getLibrariesFolder() {return this.librariesFolder;} public File getNativesFolder() {return this.nativesFolder;} public File getAssetsFolder() {return this.assetsFolder;} public File getClientJarFile() {return this.clientJarFile;} public void setClientJarSHA1(String clientJarSHA1) {this.clientJarSHA1 = clientJarSHA1;} public URL getClientJarURL() {return this.clientJarURL;} public void setClientJarURL(URL clientJarURL) {this.clientJarURL = clientJarURL;} } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/login/model/request/AuthRequest.java /* * Copyright 2015 TheShark34 * * This file is part of OpenAuth. * OpenAuth 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 3 of the License, or * (at your option) any later version. * * OpenAuth 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 OpenAuth. If not, see <http://www.gnu.org/licenses/>. */ package fr.nathanael2611.commons.launcher.login.model.request; import fr.nathanael2611.commons.launcher.login.model.AuthAgent; /** * JSON Model of an authentication request * * @version 1.0.4 * @author Litarvan */ public class AuthRequest { /** * The authentication agent (Optional, the game profile you want to use, Minecraft, Scrolls, etc...) */ private AuthAgent agent; /** * The username (The username of the player you want to authenticate) */ private String username; /** * The password (The password of the player you want to authenticate) */ private String password; /** * The client token (Optional, it's like a password for the access token) */ private String clientToken; /** * Authentication Request * * @param agent * The authentication agent (Optional, the game you want to use, Minecraft, Scrolls, etc...) * @param username * The username (The username of the player you want to authenticate) * @param password * The password (The password of the player you want to authenticate) * @param clientToken * The client token (Optional, It's like a password for the access token) */ public AuthRequest(AuthAgent agent, String username, String password, String clientToken) { this.agent = agent; this.username = username; this.password = <PASSWORD>; this.clientToken = clientToken; } /** * Sets a new authentication agent (Optional, the game you want to use, Minecraft, Scrolls, etc...) * * @param agent * The new agent */ public void setAgent(AuthAgent agent) { this.agent = agent; } /** * Returns the authentication agent (Given with the constructor or the setter) * * @return The given auth agent */ public AuthAgent getAgent() { return this.agent; } /** * Sets a new username (The username of the player you want to authenticate) * * @param username * The new username */ public void setUsername(String username) { this.username = username; } /** * Returns the username (Given with the constructor or the setter) * * @return The given username */ public String getUsername() { return this.username; } /** * Sets a new password (The password of the player you want to authenticate) * * @param password * The new password */ public void setPassword(String password) { this.password = <PASSWORD>; } /** * Returns the password (Given with the constructor or the setter) * * @return The given password */ public String getPassword() { return this.password; } /** * Sets a new client token (It's like a password for the access token) * * @param clientToken * The new client token */ public void setClientToken(String clientToken) { this.clientToken = clientToken; } /** * Returns the client token (Given with the constructor or the setter) * * @return The given client token */ public String getClientToken() { return clientToken; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/launch/GameType.java /* * Copyright 2015-2017 Adrien "Litarvan" Navratil * * This file is part of the OpenLauncherLib. * The OpenLauncherLib 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 3 of the License, or * (at your option) any later version. * * The OpenLauncherLib 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 the OpenLauncherLib. If not, see <http://www.gnu.org/licenses/>. */ package fr.nathanael2611.commons.launcher.launch; import fr.nathanael2611.commons.launcher.BaseLauncher; import fr.nathanael2611.commons.launcher.login.LoginManager; import java.io.File; import java.util.ArrayList; /** * The Game Type * * <p> * This class contains the specifics informations about a version * or a group of verison of Minecraft. * * It contains its main class, and its arguments. * </p> * * @author Litarvan * @version 3.0.4 * @since 2.0.0-SNAPSHOT */ public abstract class GameType { public static GameType get(String version) { if(version.equalsIgnoreCase("1.7.10")) { return GameType.V1_7_10; } return GameType.V1_8_HIGHER; } /** * The 1.7.10 Game Type */ public static final GameType V1_7_10 = new GameType() { @Override public String getName() { return "1.7.10"; } @Override public String getMainClass() { return "net.minecraft.client.main.Main"; } @Override public ArrayList<String> getLaunchArgs(BaseLauncher launcher) { ArrayList<String> arguments = new ArrayList<String>(); LoginManager manager = launcher.getLoginManager(); arguments.add("--username=" + manager.getAuthResponse().getSelectedProfile().getName()); arguments.add("--accessToken"); arguments.add(manager.getAuthResponse().getAccessToken()); if (manager.getAuthResponse().getClientToken() != null) { arguments.add("--clientToken"); arguments.add(manager.getAuthResponse().getClientToken()); } arguments.add("--version"); arguments.add(launcher.getMinecraftVersion()); arguments.add("--gameDir"); arguments.add(launcher.minecraftDir.getAbsolutePath()); arguments.add("--assetsDir"); File assetsDir = launcher.getMinecraftFolder().getAssetsFolder(); arguments.add(assetsDir.getAbsolutePath()); arguments.add("--assetIndex"); arguments.add("1.7.10"); arguments.add("--userProperties"); arguments.add("{}"); arguments.add("--uuid"); arguments.add(manager.getAuthResponse().getSelectedProfile().getId()); arguments.add("--userType"); arguments.add("legacy"); return arguments; } }; /** * The 1.8 or higher Game Type */ public static final GameType V1_8_HIGHER = new GameType() { @Override public String getName() { return "1.8 or higher"; } @Override public String getMainClass() { return "net.minecraft.client.main.Main"; } @Override public ArrayList<String> getLaunchArgs(BaseLauncher launcher) { ArrayList<String> arguments = new ArrayList<String>(); LoginManager manager = launcher.getLoginManager(); arguments.add("--username=" + manager.getAuthResponse().getSelectedProfile().getName()); arguments.add("--accessToken"); arguments.add(manager.getAuthResponse().getAccessToken()); if (manager.getAuthResponse().getClientToken() != null) { arguments.add("--clientToken"); arguments.add(manager.getAuthResponse().getClientToken()); } arguments.add("--version"); arguments.add(launcher.getMinecraftVersion()); arguments.add("--gameDir"); arguments.add(launcher.minecraftDir.getAbsolutePath()); arguments.add("--assetsDir"); File assetsDir = launcher.getMinecraftFolder().getAssetsFolder(); arguments.add(assetsDir.getAbsolutePath()); arguments.add("--assetIndex"); String version = launcher.getMinecraftVersion(); int first = version.indexOf('.'); int second = version.lastIndexOf('.'); if (first != second) { version = version.substring(0, version.lastIndexOf('.')); } if (launcher.getMinecraftVersion().equals("1.13.1") || launcher.getMinecraftVersion().equals("1.13.2")) version = "1.13.1"; arguments.add(version); arguments.add("--userProperties"); arguments.add("{}"); arguments.add("--uuid"); arguments.add(manager.getAuthResponse().getSelectedProfile().getId()); arguments.add("--userType"); arguments.add("legacy"); return arguments; } }; public abstract String getName(); public abstract ArrayList<String> getLaunchArgs(BaseLauncher launcher); public abstract String getMainClass(); } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/versions/Version.java package fr.nathanael2611.commons.launcher.update.minecraft.versions; import fr.nathanael2611.commons.launcher.BaseLauncher; import fr.nathanael2611.commons.launcher.update.minecraft.Game; import java.net.URL; import java.util.Date; public class Version { private String id; private Date time; private Date releaseTime; private URL url; private fr.nathanael2611.commons.launcher.update.minecraft.Version.VersionType type; public String getId() { return this.id; } public Date getUpdatedTime() { return this.time; } public void setUpdatedTime(final Date time) { this.time = time; } public Date getReleaseTime() { return this.releaseTime; } public void setReleaseTime(final Date time) { this.releaseTime = time; } public URL getUrl() { return this.url; } public void setUrl(final URL url) { this.url = url; } public void setID(final String id) { this.id = id; } public fr.nathanael2611.commons.launcher.update.minecraft.Version.VersionType getType() { return this.type; } public void setType(final fr.nathanael2611.commons.launcher.update.minecraft.Version.VersionType type) { this.type = type; } public Game update(BaseLauncher launcher){ return null; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/ui/swing/ComponentListener.java package fr.nathanael2611.commons.launcher.ui.swing; import java.util.EventListener; public interface ComponentListener extends EventListener { public abstract void run(); } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/login/model/AuthProfile.java /* * Copyright 2015 TheShark34 * * This file is part of OpenAuth. * OpenAuth 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 3 of the License, or * (at your option) any later version. * * OpenAuth 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 OpenAuth. If not, see <http://www.gnu.org/licenses/>. */ package fr.nathanael2611.commons.launcher.login.model; /** * JSON model of a profile * * @version 1.0.4 * @author Litarvan */ public class AuthProfile { /** * The profile name */ private String name; /** * The profile UUID */ private String id; /** * Blank auth profile */ public AuthProfile() { this.name = ""; this.id = ""; } /** * Normal auth profile * * @param name * The profile name * @param id * The profile UUID */ public AuthProfile(String name, String id) { this.name = name; this.id = id; } /** * Returns the name of the profile * * @return The profile name */ public String getName() { return this.name; } /** * Returns the profile UUID * * @return The profile UUID */ public String getId() { return this.id; } } <file_sep>/build.gradle plugins { id 'java' id "com.github.johnrengelman.shadow" version "4.0.0" id "application" } application { mainClassName = "fr.nathanael2611.commons.minecraft.launcher.BaseLauncher" } group 'fr.nathanael2611.commons.minecraft.launcher' version '1.0-SNAPSHOT' compileJava.options.encoding = 'UTF-8' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { implementation 'com.google.code.gson:gson:2.8.5' compile group: 'commons-codec', name: 'commons-codec', version: '1.5' compile group: 'commons-io', name: 'commons-io', version: '2.6' compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.1' } shadowJar { mergeServiceFiles() }<file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/data/DownloadableResource.java package fr.nathanael2611.commons.launcher.update.data; import fr.nathanael2611.commons.launcher.update.EazyUpdater; import fr.nathanael2611.commons.launcher.util.Helpers; import org.apache.commons.io.FileUtils; import java.io.BufferedInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; public class DownloadableResource { private String fileName; private String downloadUrl; private String relativePath; private String md5; private int size; public DownloadableResource(String fileName, String downloadUrl, String relativePath, String md5, int size) { this.fileName = fileName; this.downloadUrl = downloadUrl; this.relativePath = relativePath; this.md5 = md5; this.size = size; } public String getFileName() { return fileName; } public String getDownloadUrl() { return downloadUrl; } public String getRelativePath() { return relativePath; } public String getMd5() { return md5; } public int getSize() { return size; } public void download(File baseDir, EazyUpdater updater) { baseDir.mkdir(); new File(baseDir, getRelativePath()).mkdirs(); File file = new File(new File(baseDir, getRelativePath()), getFileName()); if(updater.getProfile().getIgnoreList().contains(file.getAbsolutePath(), updater)) return; if(file.exists()) { String md5 = Helpers.md5File(file); if(!md5.equals(getMd5())){ try { FileUtils.forceDelete(file); Helpers.sendMessageInConsole("Deleting " + file.getAbsolutePath()); } catch (IOException e) { e.printStackTrace(); } } else { updater.incrementDownloadedBytes(this.size); return; } } Helpers.sendMessageInConsole("Starting download of " + getDownloadUrl()); try (BufferedInputStream in = new BufferedInputStream(new URL(getDownloadUrl()).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(file)) { byte dataBuffer[] = new byte[1024]; int bytesRead; while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { fileOutputStream.write(dataBuffer, 0, bytesRead); updater.incrementDownloadedBytes(1024); } } catch (IOException e) { } } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/versions/AssetDownloadable.java package fr.nathanael2611.commons.launcher.update.minecraft.versions; import fr.nathanael2611.commons.launcher.BaseLauncher; import fr.nathanael2611.commons.launcher.update.minecraft.download.DownloadEntry; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.*; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.zip.GZIPInputStream; public class AssetDownloadable extends DownloadEntry { private final AssetIndex.AssetObject asset; private final File destination; public AssetDownloadable(BaseLauncher launcher, final String name, final AssetIndex.AssetObject asset, final String url, final File destination) throws MalformedURLException { super(launcher, new URL(String.valueOf(url) + createPathFromHash(asset.getHash())), null, null); this.asset = asset; this.destination = destination; this.setTarget(new File(destination, createPathFromHash(asset.getHash()))); } protected static String createPathFromHash(final String hash) { return String.valueOf(hash.substring(0, 2)) + "/" + hash; } @Override public void download() { try { final File localAsset = super.getTarget(); final File localCompressed = this.asset.hasCompressedAlternative() ? new File(this.destination, createPathFromHash(this.asset.getCompressedHash())) : null; final URL remoteAsset = this.getURL(); URL url; if (this.asset.hasCompressedAlternative()) { final StringBuilder sb = new StringBuilder(String.valueOf(this.getURL().toString())); url = new URL(sb.append(createPathFromHash(this.asset.getCompressedHash())).toString()); } else { url = null; } final URL remoteCompressed = url; this.ensureFileWritable(localAsset); if (localCompressed != null) { super.ensureFileWritable(localCompressed); } if (localAsset.isFile()) { if (FileUtils.sizeOf(localAsset) == this.asset.getSize()) { return; } FileUtils.deleteQuietly(localAsset); } if (localCompressed != null && localCompressed.isFile()) { final String localCompressedHash = DownloadEntry.getDigest(localCompressed, "SHA", 40); if (localCompressedHash.equalsIgnoreCase(this.asset.getCompressedHash())) { this.decompressAsset(localAsset, localCompressed); return; } FileUtils.deleteQuietly(localCompressed); } if (remoteCompressed != null && localCompressed != null) { final HttpURLConnection connection = this.makeConnection(remoteCompressed); final int status = connection.getResponseCode(); if (status / 100 != 2) { throw new RuntimeException("Server responded with " + status); } final InputStream inputStream = connection.getInputStream(); final FileOutputStream outputStream = new FileOutputStream(localCompressed); final String hash = this.copyAndDigest(inputStream, outputStream, "SHA", 40); if (hash.equalsIgnoreCase(this.asset.getCompressedHash())) { this.decompressAsset(localAsset, localCompressed); return; } FileUtils.deleteQuietly(localCompressed); throw new RuntimeException(String.format("Hash did not match downloaded compressed asset (Expected %s, downloaded %s)", this.asset.getCompressedHash(), hash)); } else { final HttpURLConnection connection = this.makeConnection(remoteAsset); final int status = connection.getResponseCode(); if (status / 100 != 2) { throw new RuntimeException("Server responded with " + status); } final InputStream inputStream = connection.getInputStream(); final FileOutputStream outputStream = new FileOutputStream(localAsset); final String hash = this.copyAndDigest(inputStream, outputStream, "SHA", 40); if (hash.equalsIgnoreCase(this.asset.getHash())) { return; } FileUtils.deleteQuietly(localAsset); throw new RuntimeException(String.format("Hash did not match downloaded asset (Expected %s, downloaded %s)", this.asset.getHash(), hash)); } } catch (Exception e) { e.printStackTrace(); } } protected HttpURLConnection makeConnection(final URL url) throws IOException { final HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setUseCaches(false); connection.setDefaultUseCaches(false); connection.setRequestProperty("Cache-Control", "no-store,max-age=0,no-cache"); connection.setRequestProperty("Expires", "0"); connection.setRequestProperty("Pragma", "no-cache"); connection.setConnectTimeout(5000); connection.setReadTimeout(30000); return connection; } @SuppressWarnings("deprecation") protected void decompressAsset(final File localAsset, final File localCompressed) throws IOException { final OutputStream outputStream = FileUtils.openOutputStream(localAsset); final InputStream inputStream = new GZIPInputStream(FileUtils.openInputStream(localCompressed)); String hash = null; try { hash = this.copyAndDigest(inputStream, outputStream, "SHA", 40); } finally { IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); } IOUtils.closeQuietly(outputStream); IOUtils.closeQuietly(inputStream); if (hash.equalsIgnoreCase(this.asset.getHash())) { return; } FileUtils.deleteQuietly(localAsset); throw new RuntimeException("Had local compressed asset but unpacked hash did not match (expected " + this.asset.getHash() + " but had " + hash + ")"); } @Override public boolean needDownload() { return !this.getTarget().exists(); } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/login/model/AuthAgent.java /* * Copyright 2015 TheShark34 * * This file is part of OpenAuth. * OpenAuth 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 3 of the License, or * (at your option) any later version. * * OpenAuth 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 OpenAuth. If not, see <http://www.gnu.org/licenses/>. */ package fr.nathanael2611.commons.launcher.login.model; /** * JSON model of an auth agent * * @version 1.0.4 * @author Litarvan */ public class AuthAgent { /** * The Minecraft auth agent */ public static final AuthAgent MINECRAFT = new AuthAgent("Minecraft", 1); /** * The Scroll auth agent */ public static final AuthAgent SCROLLS = new AuthAgent("Scrolls", 1); /** * The agent name */ private String name; /** * The agent version */ private int version; /** * Agent constructor * * @param name * The name of the agent * @param version * The version of the agent (1 by default) */ public AuthAgent(String name, int version) { this.name = name; this.version = version; } /** * Sets a new name * * @param name * The new name */ public void setName(String name) { this.name = name; } /** * Returns the name of the agent * * @return The agent name */ public String getName() { return this.name; } /** * Sets a new version * * @param version * The new version */ public void setVersion(int version) { this.version = version; } /** * Returns the version of the agent * * @return The agent version */ public int getVersion() { return this.version; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/login/Authenticator.java /* * Copyright 2015-2016 Adrien 'Litarvan' Navratil * * This file is part of OpenAuth. * OpenAuth 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 3 of the License, or * (at your option) any later version. * * OpenAuth 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 OpenAuth. If not, see <http://www.gnu.org/licenses/>. */ package fr.nathanael2611.commons.launcher.login; import com.google.gson.Gson; import fr.nathanael2611.commons.launcher.login.model.AuthAgent; import fr.nathanael2611.commons.launcher.login.model.AuthError; import fr.nathanael2611.commons.launcher.login.model.request.*; import fr.nathanael2611.commons.launcher.login.model.response.AuthResponse; import fr.nathanael2611.commons.launcher.login.model.response.RefreshResponse; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; /** * The Authenticator * * <p> * The main class of the lib, use it to authenticate a user ! * </p> * * @version 1.0.4 * @author Litarvan */ public class Authenticator { /** * The Mojang official auth server */ public static final String MOJANG_AUTH_URL = "https://authserver.mojang.com/"; /** * The auth server URL */ private String authURL; /** * The server auth points */ private AuthPoints authPoints; /** * Create an authenticator * * @param authURL * The auth server URL * * @param authPoints * The URIs of the multiple requests */ public Authenticator(String authURL, AuthPoints authPoints) { this.authURL = authURL; this.authPoints = authPoints; } /** * Authenticates an user using his password. * * @param agent * The auth agent (optional) * @param username * User mojang account name * @param password * User mojang account password * @param clientToken * The client token (optional, like a key for the access token) * * @throws AuthenticationException If the server returned an error as a JSON * * @return The response sent by the server (parsed from a JSON) */ public AuthResponse authenticate(AuthAgent agent, String username, String password, String clientToken) throws AuthenticationException { AuthRequest request = new AuthRequest(agent, username, password, clientToken); return (AuthResponse) sendRequest(request, AuthResponse.class, authPoints.getAuthenticatePoint()); } /** * Refresh a valid access token. It can be uses to keep a user logged in between gaming sessions * and is preferred over storing the user's password in a file. * * @param accessToken * The saved access token * @param clientToken * The saved client token (need to be the same used when authenticated to get the acces token) * * @throws AuthenticationException If the server returned an error as a JSON * * @return The response sent by the server (parsed from a JSON) */ public RefreshResponse refresh(String accessToken, String clientToken) throws AuthenticationException { RefreshRequest request = new RefreshRequest(accessToken, clientToken); return (RefreshResponse) sendRequest(request, RefreshResponse.class, authPoints.getRefreshPoint()); } /** * Check if an access token is a valid session token with a currently-active session. * Note: this method will not respond successfully to all currently-logged-in sessions, * just the most recently-logged-in for each user. It is intended to be used by servers to validate * that a user should be connecting (and reject users who have logged in elsewhere since starting Minecraft), * NOT to auth that a particular session token is valid for authentication purposes. * To authenticate a user by session token, use the refresh verb and catch resulting errors. * * @param accessToken * The access token to check * * @throws AuthenticationException If the server returned an error as a JSON */ public void validate(String accessToken) throws AuthenticationException { ValidateRequest request = new ValidateRequest(accessToken); sendRequest(request, null, authPoints.getValidatePoint()); } /** * Invalidates accessTokens using an account's username and password * * @param username * User mojang account name * @param password * User mojang account password * * @throws AuthenticationException If the server returned an error as a JSON */ public void signout(String username, String password) throws AuthenticationException { SignoutRequest request = new SignoutRequest(username, password); sendRequest(request, null, authPoints.getSignoutPoint()); } /** * Invalidates accessTokens using a client/access token pair * * @param accessToken * Valid access token to invalidate * @param clientToken * Client token used when authenticated to get the access token * * @throws AuthenticationException If the server returned an error as a JSON */ public void invalidate(String accessToken, String clientToken) throws AuthenticationException { InvalidateRequest request = new InvalidateRequest(accessToken, clientToken); sendRequest(request, null, authPoints.getInvalidatePoint()); } /** * Send a request to the auth server * * @param request * The auth request to send * @param model * The model of the reponse * @param authPoint * The auth point of the request * @throws AuthenticationException * If it returned an error or the request failed * * @throws AuthenticationException If the server returned an error as a JSON * * @return Instance of the given reponse model if it not null */ private Object sendRequest(Object request, Class<?> model, String authPoint) throws AuthenticationException { Gson gson = new Gson(); String response; try { response = sendPostRequest(this.authURL + authPoint, gson.toJson(request)); } catch (IOException e) { throw new AuthenticationException(new AuthError("Can't send the request : " + e.getClass().getName(), e.getMessage(), "Unknown")); } if(model != null) return gson.fromJson(response, model); else return null; } /** * Sends a post request of a json * * @param url * The url to send the request * @param json * The json to send * @throws IOException * If it failed * * @throws AuthenticationException If the request returned an error JSON or not a JSON * * @return The request response */ private String sendPostRequest(String url, String json) throws AuthenticationException, IOException { URL serverURL = new URL(url); HttpURLConnection connection = (HttpURLConnection) serverURL.openConnection(); connection.setRequestMethod("POST"); // Sending post request connection.setDoOutput(true); connection.addRequestProperty("Content-Type", "application/json;charset=utf-8"); DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes(json); wr.flush(); wr.close(); connection.connect(); int responseCode = connection.getResponseCode(); if(responseCode == 204) { connection.disconnect(); return null; } InputStream is; if(responseCode == 200) is = connection.getInputStream(); else is = connection.getErrorStream(); String response; BufferedReader br = new BufferedReader(new InputStreamReader(is)); response = br.readLine(); try { br.close(); } catch (IOException e) { e.printStackTrace(); } connection.disconnect(); while (response != null && response.startsWith("\uFEFF")) response = response.substring(1); if (responseCode != 200) { Gson gson = new Gson(); if (response != null && !response.startsWith("{")) throw new AuthenticationException(new AuthError("Internal server error", response, "Remote")); throw new AuthenticationException(gson.fromJson(response, AuthError.class)); } return response; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/LauncherConfig.java package fr.nathanael2611.commons.launcher; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; import java.io.IOException; import java.util.HashMap; import static fr.nathanael2611.commons.launcher.util.Helpers.readJsonFromUrl; public class LauncherConfig { private final HashMap<String, JsonElement> ELEMENTS = new HashMap<>(); public void read(String url) { ELEMENTS.clear(); try { String json = readJsonFromUrl(url); new JsonParser().parse(json).getAsJsonObject().entrySet().forEach(entry -> ELEMENTS.put(entry.getKey(), entry.getValue())); } catch (IOException e) { e.printStackTrace(); } } public JsonElement get(String key, JsonElement defaultValue) { return ELEMENTS.getOrDefault(key, defaultValue); } public String getString(String key) { return get(key, new JsonPrimitive("")).getAsString(); } public boolean getBoolean(String key) { return get(key, new JsonPrimitive(false)).getAsBoolean(); } public int getInteger(String key) { return get(key, new JsonPrimitive(0)).getAsInt(); } public double getDouble(String key) { return get(key, new JsonPrimitive(0)).getAsDouble(); } public float getFoat(String key) { return get(key, new JsonPrimitive(0)).getAsFloat(); } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/data/SyncedDirectory.java package fr.nathanael2611.commons.launcher.update.data; import fr.nathanael2611.commons.launcher.update.EazyUpdater; import fr.nathanael2611.commons.launcher.util.Helpers; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Objects; public class SyncedDirectory { private String relativePath; private List<String> filesMd5; public SyncedDirectory(String relativePath, List<String> filesMd5) { this.relativePath = relativePath; this.filesMd5 = filesMd5; } public String getRelativePath() { return relativePath; } public List<String> getFilesMd5() { return filesMd5; } public void removeSurplus(File baseDir, EazyUpdater updater) { File dir = new File(baseDir, relativePath); if(dir.listFiles() != null) { for (File f : Objects.requireNonNull(dir.listFiles(), "Pas fou")) { if(f.isFile()) { if (!filesMd5.contains(Helpers.md5File(f))) { if(!updater.getProfile().getIgnoreList().contains(f.getAbsolutePath(), updater)) { try { Helpers.sendMessageInConsole("Deleting " + f.getAbsolutePath()); FileUtils.forceDelete(f); } catch (IOException e) { e.printStackTrace(); } } } } } } } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/login/LoginManager.java package fr.nathanael2611.commons.launcher.login; import com.google.gson.*; import fr.nathanael2611.commons.launcher.BaseLauncher; import fr.nathanael2611.commons.launcher.login.model.AuthAgent; import fr.nathanael2611.commons.launcher.login.model.AuthError; import fr.nathanael2611.commons.launcher.login.model.AuthProfile; import fr.nathanael2611.commons.launcher.login.model.response.AuthResponse; import fr.nathanael2611.commons.launcher.util.Helpers; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.Base64; public class LoginManager { private final File userInfos; private Gson gson = new GsonBuilder().setPrettyPrinting().create(); private String email = ""; private String password = ""; private double ram = 2; private boolean saveEmail = false; private boolean savePassword = false; private boolean crack = false; private AuthResponse authResponse = null; private JsonObject customData; public LoginManager(BaseLauncher launcher) { this.userInfos = launcher.USER_INFOS; this.userInfos.getParentFile().mkdirs(); if(!userInfos.exists()) { try { userInfos.createNewFile(); FileWriter writer = new FileWriter(userInfos); writer.write("{}"); writer.close(); } catch (IOException e) { e.printStackTrace(); } } this.read(); } public void read() { JsonObject object = new JsonParser().parse("{}").getAsJsonObject(); try { object = new JsonParser().parse(FileUtils.readFileToString(this.userInfos, "UTF-8")).getAsJsonObject(); } catch (IOException e) { e.printStackTrace(); } this.email = object.has("email") ? object.get("email").getAsString() : ""; this.password = object.has("password") ? object.get("password").getAsString() : ""; this.ram = object.has("ram") ? object.get("ram").getAsDouble() : 2; this.crack = object.has("crack") && object.get("crack").getAsBoolean(); this.customData = object.has("customData") ? object.getAsJsonObject("customData") : new JsonObject(); } public void save() { JsonObject object = new JsonObject(); if(this.saveEmail) object.add("email", new JsonPrimitive(this.email)); if(this.savePassword) object.add("password", new JsonPrimitive(this.password)); object.add("ram", new JsonPrimitive(this.ram)); object.add("crack", new JsonPrimitive(this.crack)); object.add("customData", this.customData); try { FileUtils.write(this.userInfos, gson.toJson(object), "UTF-8"); } catch (IOException e) { e.printStackTrace(); } } public void setInfos(String email, String password) { try { this.email = IOUtils.toString(Base64.getEncoder().encode(email.getBytes())); } catch (IOException e) { e.printStackTrace(); } try { this.password = IOUtils.toString(Base64.getEncoder().encode(password.getBytes())); } catch (IOException e) { e.printStackTrace(); } save(); } public String getEmail() { try { return IOUtils.toString(Base64.getDecoder().decode(email)); } catch (IOException e) { return ""; } } public String getPassword() { try { return IOUtils.toString(Base64.getDecoder().decode(password)); } catch (IOException e) { return ""; } } public void setRam(double ram) { this.ram = ram; save(); } public double getRam() { return ram; } public void tryLogin() throws AuthenticationException { Authenticator authenticator = new Authenticator(Authenticator.MOJANG_AUTH_URL, AuthPoints.NORMAL_AUTH_POINTS); try { if(this.crack) { if(this.email.length() < 4) throw new AuthenticationException(new AuthError("Username too short", "Your username has to be at least 4 characters", "")); this.authResponse = new AuthResponse("non", "non", new AuthProfile[]{}, new AuthProfile(getEmail(), "non")); } else { this.authResponse = authenticator.authenticate(AuthAgent.MINECRAFT, this.getEmail(), this.getPassword(), null); } } catch (AuthenticationException e) { this.authResponse = null; throw e; } } public boolean isLoggedIn() { return this.authResponse != null; } public void setCrack(boolean crack) { this.crack = crack; } public boolean isCrackAccount() { return this.crack; } public AuthResponse getAuthResponse() { return authResponse; } public void disconnect() { this.email = ""; this.password = ""; this.authResponse = null; this.save(); } public void setRemeberOptions(boolean saveEmail, boolean savePassword) { this.saveEmail = saveEmail; this.savePassword = <PASSWORD>; } public JsonObject getCustomData() { return customData; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/utils/FileUtils.java package fr.nathanael2611.commons.launcher.update.minecraft.utils; import javax.xml.bind.annotation.adapters.HexBinaryAdapter; import java.io.*; import java.security.MessageDigest; import java.util.ArrayList; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class FileUtils { public static String getFileExtension(final File file) { final String fileName = file.getName(); final int dotIndex = fileName.lastIndexOf(46); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1); } public static String removeExtension(final String fileName) { if (fileName == null) { return ""; } if (!getFileExtension(new File(fileName)).isEmpty()) { return fileName.substring(0, fileName.lastIndexOf(46)); } return fileName; } public static String getSHA1(final File file) { try { final InputStream input = new FileInputStream(file); try { final MessageDigest sha1 = MessageDigest.getInstance("SHA-1"); final byte[] buffer = new byte[8192]; for (int len = input.read(buffer); len != -1; len = input.read(buffer)) { sha1.update(buffer, 0, len); } return new HexBinaryAdapter().marshal(sha1.digest()).toLowerCase(); } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } } }catch(Exception e){ e.printStackTrace(); } return null; } public static ArrayList<File> listFilesForFolder(final File folder) { final ArrayList<File> files = new ArrayList<File>(); File[] listFiles; for (int length = (listFiles = folder.listFiles()).length, i = 0; i < length; ++i) { final File fileEntry = listFiles[i]; if (fileEntry.isDirectory()) { files.addAll(listFilesForFolder(fileEntry)); files.add(fileEntry); } else { files.add(fileEntry); } } return files; } public static void unzip(final File zipfile, final File folder) throws FileNotFoundException, IOException { final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipfile.getCanonicalFile()))); ZipEntry ze = null; try { while ((ze = zis.getNextEntry()) != null) { final File f = new File(folder.getCanonicalPath(), ze.getName()); if (ze.isDirectory()) { f.mkdirs(); } else { f.getParentFile().mkdirs(); final OutputStream fos = new BufferedOutputStream(new FileOutputStream(f)); try { try { final byte[] buf = new byte[8192]; int bytesRead; while (-1 != (bytesRead = zis.read(buf))) { fos.write(buf, 0, bytesRead); } } finally { fos.close(); } fos.close(); } catch (IOException ioe) { f.delete(); throw ioe; } } } } finally { zis.close(); } zis.close(); } public static void removeFolder(final File folder) { if (folder.exists() && folder.isDirectory()) { final ArrayList<File> files = listFilesForFolder(folder); if (files.isEmpty()) { folder.delete(); return; } for (final File f : files) { f.delete(); } folder.delete(); } } /** * List the sub-files and sub-directory of a given one, recursively * * @param directory The directory to list * * @return The generated list of files */ public static ArrayList<File> listRecursive(File directory) { ArrayList<File> files = new ArrayList<File>(); File[] fs = directory.listFiles(); if (fs == null) return files; for (File f : fs) { if (f.isDirectory()) files.addAll(listRecursive(f)); files.add(f); } return files; } /** * Get a file in a directory and checks if it is existing * (throws a FailException if not) * * @param root The root directory where the file is supposed to be * @param file The name of the file to get * * @return The found file */ public static File get(File root, String file) { File f = new File(root, file); return f; } public static File dir(File d) { return d; } /** * Mix between the get method and the dir method * * @param root The directory where the other one is supposed to be * @param dir The name of the directory to get * * @return The got directory * * @see #get(File, String) * @see #dir(File) */ public static File dir(File root, String dir) { return dir(get(root, dir)); } /** * Return the list of the files of the given directory, but * checks if it is a directory, and return an empty file list if listFiles returns null * * @param dir The directory to list * * @return The files in the given directory * * @see #dir(File) */ public static File[] list(File dir) { File[] files = dir(dir).listFiles(); return files == null ? new File[0] : files; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/ui/swing/components/button/AbstractButton.java package fr.nathanael2611.commons.launcher.ui.swing.components.button; import fr.nathanael2611.commons.launcher.ui.swing.ComponentListener; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.List; public abstract class AbstractButton extends JComponent implements MouseListener { private String text; private Color textColor; private boolean hover = false; public AbstractButton() { this.addMouseListener(this); } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { if(this.isEnabled()) { this.listeners.forEach(ComponentListener::run); } } @Override public void mouseEntered(MouseEvent e) { hover = true; repaint(); } @Override public void mouseExited(MouseEvent e) { hover = false; repaint(); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); repaint(); } public void setText(String text) { if(text == null) throw new IllegalArgumentException("text == null"); this.text = text; repaint(); } public String getText() { return text; } public void setTextColor(Color textColor) { if(textColor == null) throw new IllegalArgumentException("textColor == null"); this.textColor = textColor; repaint(); } public Color getTextColor() { return textColor; } private List<ComponentListener> listeners = new ArrayList<>(); public void addListener(ComponentListener listener) { this.listeners.add(listener); } public boolean isHover() { return this.hover; } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/versions/Library.java package fr.nathanael2611.commons.launcher.update.minecraft.versions; import fr.nathanael2611.commons.launcher.update.minecraft.utils.OperatingSystem; import org.apache.commons.lang3.text.StrSubstitutor; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @SuppressWarnings({ "unchecked", "deprecation", "serial", "rawtypes" }) public class Library{ private static final StrSubstitutor SUBSTITUTOR; private String name; private List<CompatibilityRule> rules; private Natives natives; private ExtractRules extract; public Downloads downloads; public String url; private String sha1; private Downloads.Classifier classifiers; static { SUBSTITUTOR = new StrSubstitutor((Map)new HashMap() {}); } public Library() { } public Library(final String name) { if (name == null || name.length() == 0) { throw new IllegalArgumentException("Library name cannot be null or empty"); } this.name = name; } public Library(final Library library) { this.name = library.name; if (library.extract != null) { this.extract = new ExtractRules(library.extract); } if (library.rules != null) { this.rules = new ArrayList<CompatibilityRule>(); for (final CompatibilityRule compatibilityRule : library.rules) { this.rules.add(new CompatibilityRule(compatibilityRule)); } } this.natives = library.natives; } public String getName() { return this.name; } public List<CompatibilityRule> getCompatibilityRules() { return this.rules; } public boolean appliesToCurrentEnvironment(final CompatibilityRule.FeatureMatcher featureMatcher) { if (this.rules == null) { return true; } CompatibilityRule.Action lastAction = CompatibilityRule.Action.DISALLOW; for (final CompatibilityRule compatibilityRule : this.rules) { final CompatibilityRule.Action action = compatibilityRule.getAppliedAction(featureMatcher); if (action != null) { lastAction = action; } } return lastAction == CompatibilityRule.Action.ALLOW; } public String getNative() { final OperatingSystem system = OperatingSystem.getCurrentPlatform(); if (this.natives == null) { return null; } if (this.natives.getWindows() != null && system == OperatingSystem.WINDOWS) { return "natives-windows"; } if (this.natives.getLinux() != null && system == OperatingSystem.LINUX) { return "natives-linux"; } if (this.natives.getOsx() != null && system == OperatingSystem.OSX) { return "natives-osx"; } return null; } public ExtractRules getExtractRules() { return this.extract; } public Library setExtractRules(final ExtractRules rules) { this.extract = rules; return this; } public String getArtifactBaseDir() { if (this.name == null) { throw new IllegalStateException("Cannot get artifact dir of empty/blank artifact"); } final String[] parts = this.name.split(":", 3); return String.format("%s/%s/%s", parts[0].replaceAll("\\.", "/"), parts[1], parts[2]); } public String getArtifactURL() { if (this.name == null) { throw new IllegalStateException("Cannot get artifact dir of empty/blank artifact"); } final String[] parts = this.name.split(":", 4); final String text = String.format("%s/%s/%s", parts[0].replaceAll("\\.", "/"), parts[1], parts[2]); if (parts.length == 4) { return String.valueOf(text) + "/" + parts[1] + "-" + parts[2] + "-" + parts[3] + ".jar"; } return String.valueOf(text) + "/" + parts[1] + "-" + parts[2] + ".jar"; } public String getArtifactPath() { return this.getArtifactPath(null); } public String getArtifactPath(final String classifier) { if (this.name == null) { throw new IllegalStateException("Cannot get artifact path of empty/blank artifact"); } return String.format("%s/%s", this.getArtifactBaseDir(), this.getArtifactFilename(classifier)); } public String getArtifactFilename(final String classifier) { if (this.name == null) { throw new IllegalStateException("Cannot get artifact filename of empty/blank artifact"); } final String[] parts = this.name.split(":", 3); String result = null; if (classifier != null) { result = String.format("%s-%s%s.jar", parts[1], parts[2], "-" + classifier); } else { result = String.format("%s-%s.jar", parts[1], parts[2]); } return Library.SUBSTITUTOR.replace(result); } public Downloads getDownloads() { return this.downloads; } public String getURL() { return (this.url != null) ? (String.valueOf(this.url) + this.getArtifactURL()) : ("https://libraries.minecraft.net/" + this.getArtifactPath()); } public String getSHA1() { return this.sha1; } public Downloads.Classifier getClassifiers() { return this.classifiers; } public class Natives { private String osx; private String windows; private String linux; public String getOsx() { return this.osx; } public void setOsx(final String osx) { this.osx = osx; } public String getWindows() { return this.windows; } public void setWindows(final String windows) { this.windows = windows; } public String getLinux() { return this.linux; } public void setLinux(final String linux) { this.linux = linux; } } } <file_sep>/src/main/java/fr/nathanael2611/commons/launcher/update/minecraft/utils/MathUtils.java package fr.nathanael2611.commons.launcher.update.minecraft.utils; public class MathUtils { public static double round(final double val) { return Math.floor(val * 1.0) / 1.0; } }
21272b69e82472085987459da409bf27e9a452cf
[ "Java", "Gradle" ]
26
Gradle
Nathanael2611/Nathanael2611-Launcher-Commons
0367686856feebdafef902e8f97a836bbeb1d72c
28da588ef6fc2394602a3707f9ce6add77b039f8
refs/heads/master
<file_sep># -*- coding: utf-8 -*- # from __future__ import unicode_literals from django.http import QueryDict from core.tests.utils import TestCase, skip_if_not_pg from core.views import SuggestBaseView class SuggestBaseViewTestCase(TestCase): """ Тестирование SuggestBaseView базового класса для построения API подсказок """ class View(SuggestBaseView): def get_result(self, q): return [{}] view = View() def test_norm(self): """ Нормальный запрос """ self.POST = QueryDict('query=Москва', mutable=True) response = self.view.post(self) data = self.json(response) self.assertEqual(data['status'], 200) self.assertEqual(len(data.get('result', [])), 1) def test_latin(self): """ Отправляем запрос латинскими буквами """ self.POST = QueryDict('query=mosc', mutable=True) response = self.view.post(self) data = self.json(response) self.assertEqual(data['status'], 404) self.assertEqual(len(data.get('result', [])), 0) <file_sep># coding=utf-8 from __future__ import unicode_literals """ This file was generated with the customdashboard management command and contains the class for the main dashboard. To activate your index dashboard add the following to your settings.py:: GRAPPELLI_INDEX_DASHBOARD = 'erwin.grappelli.ErwinIndexDashboard' """ from django.utils.translation import ugettext_lazy as _ from django.core.urlresolvers import reverse from grappelli.dashboard import modules, Dashboard from grappelli.dashboard.utils import get_admin_site_name class ErwinIndexDashboard(Dashboard): def init_with_context(self, context): site_name = get_admin_site_name(context) # append another link list module for "support". self.children.append(modules.LinkList( _('Администрирование Erwin'), column=1, children=[ { 'title': _('Главная страница'), 'url': reverse('admin:first_page_slide_changelist'), 'external': False, }, { 'title': _('Меню ресторана'), 'url': reverse('admin:restaurant_menu_menu_changelist'), 'external': False, }, { 'title': _('События ресторана'), 'url': reverse('admin:event_event_changelist'), 'external': False, }, { 'title': _('Фотогалерея'), 'url': reverse('admin:photogalery_album_changelist'), 'external': False, }, { 'title': _('Контакты'), 'url': reverse('admin:site_conf_contacts_changelist'), 'external': False, }, ] )) # append another link list module for "support". self.children.append(modules.LinkList( _('Media Management'), column=1, children=[ { 'title': _('FileBrowser'), 'url': '/admin/filebrowser/browse/', 'external': False, }, ] )) # append another link list module for "support". self.children.append(modules.LinkList( _('Бронирование'), column=2, children=[ { 'title': _('Заявки'), 'url': reverse('reservation:requests'), 'external': False, }, { 'title': _('Актуальные брони'), 'url': reverse('reservation:actuals'), 'external': False, }, { 'title': _('Предыдущие брони'), 'url': reverse('reservation:notactuals'), 'external': False, }, { 'title': _('Столики'), 'url': reverse('admin:reservation_zone_change', args=(2,)), 'external': False, }, ] )) # append a recent actions module self.children.append(modules.RecentActions( _('Recent Actions'), limit=5, collapsible=False, column=3, )) <file_sep># coding: utf-8 import unittest import time import re import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException sys.path.append('./core') import base class TestCase1(base.TestCase): """ Все поля формы заполнены корректно """ def test_1(self): driver = self.driver driver.get("http://erwin:404@erwin.dev.dvhb.ru/") driver.find_element_by_xpath( "//a[contains(@href, '/reservation/add/')]").click() driver.find_element_by_id("id_guest_name").clear() driver.find_element_by_id("id_guest_name").send_keys("test") driver.find_element_by_id("id_guest_count").clear() driver.find_element_by_id("id_guest_count").send_keys("2") driver.find_element_by_id("datepicker").click() driver.find_element_by_css_selector("div.pmu-next.pmu-button").click() driver.find_element_by_css_selector("div.pmu-next.pmu-button").click() driver.find_element_by_xpath("//div[34]").click() driver.find_element_by_id("timepicker").clear() driver.find_element_by_id("timepicker").send_keys("12:12") driver.find_element_by_id("id_phone").clear() driver.find_element_by_id("id_phone").send_keys("8(111)111-11-11") driver.find_element_by_id("id_comment").clear() driver.find_element_by_id("id_comment").send_keys("test") driver.find_element_by_id("btn_reserv").click() try: self.assertEqual(u'Мы приняли вашу заявку на бронирование \ столика:\ntest,\n2 человек,\n1.08.2015 12:12,\n8 (811) 111-11-11', driver.find_element_by_css_selector("p").text) except AssertionError as e: self.verificationErrors.append(str(e)) try: self.assertEqual(u"Мы свяжется с Вами в ближайшее время,\n\ чтобы подтвердить бронь.", driver.find_element_by_xpath("//p[2]").text) except AssertionError as e: self.verificationErrors.append(str(e)) if __name__ == "__main__": print __file__ print u"Все поля формы заполнены корректно" unittest.main() <file_sep>from . import models from core.views import JSONListView from django.views.generic import ListView class AlbumListView(ListView): model = models.Album template_name = 'photogalery/albums.jade' album_list = AlbumListView.as_view() class PhotoListView(JSONListView): model = models.Photo paginate_by = None fields = ['photo'] def get(self, request, *args, **kwargs): album_id = kwargs.pop('album') self.queryset = self.model.objects.filter(album_id=album_id) return super(PhotoListView, self).get(request, *args, **kwargs) photo_json = PhotoListView.as_view() <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import filebrowser.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Event', fields=[ ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)), ('edate', models.DateTimeField(verbose_name='Дата события')), ('title', models.CharField(verbose_name='Титул', max_length=255)), ('content', models.TextField(verbose_name='Контент')), ('announce', models.TextField(verbose_name='Анонс')), ('announce_photo', filebrowser.fields.FileBrowseField(verbose_name='Графический файл анонса', max_length=255)), ('event_order', models.IntegerField(verbose_name='Индекс сортировки')), ], options={ 'verbose_name': 'событие', 'verbose_name_plural': 'события', }, bases=(models.Model,), ), migrations.CreateModel( name='Photo', fields=[ ('id', models.AutoField(verbose_name='ID', auto_created=True, primary_key=True, serialize=False)), ('name', models.CharField(verbose_name='Название фото', max_length=255, blank=True)), ('photo', filebrowser.fields.FileBrowseField(verbose_name='Графический файл', max_length=255)), ('photo_order', models.IntegerField(verbose_name='Индекс сортировки')), ('event', models.ForeignKey(to='event.Event', verbose_name='Событие', related_name='photos')), ], options={ 'verbose_name': 'фотографии', 'verbose_name_plural': 'фотографии', }, bases=(models.Model,), ), ] <file_sep># coding=utf-8 from __future__ import unicode_literals from datetime import timedelta from django.db import models from django.db.models import Q from django.utils import timezone from . import consts class ActualRequestManager(models.Manager): delta = timedelta(minutes=30) def get_queryset(self): return super( ActualRequestManager, self ).get_queryset( ).select_related( 'table' ).extra( select={'sort_field': 'COALESCE(reservation_date, NOW())'} ).filter( ( Q(reservation_date__gte=timezone.now() - self.delta) | Q(reservation_date__isnull=True) ) & ( Q(status=consts.STATUS_REQUEST) | Q(table__isnull=True, status=consts.STATUS_APPROVE) ) ).order_by('sort_field') class ActualReservationManager(models.Manager): def get_queryset(self): qs = super(ActualReservationManager, self).get_queryset() qs = qs.exclude( reservation_date__lt=timezone.now() ).exclude( status=consts.STATUS_REQUEST ).select_related( 'table' ).extra( select={'sort_field': 'COALESCE(reservation_date, NOW())'} ).order_by('sort_field') return qs class NotActualReservationManager(models.Manager): def get_queryset(self): qs = super(NotActualReservationManager, self).get_queryset() qs = qs.filter( reservation_date__lt=timezone.now() ).select_related('table') return qs <file_sep>$(function(){ var $footer_holder = $('.footer-holder'); var $footer = $('.footer'); var $menuBurger = $('.header-burger'); if( $menuBurger.length ){ var $menuSidebar = $menuBurger.parent(); $menuBurger.click(function(){ if( $menuSidebar.hasClass('_expanded') ){ $menuSidebar.removeClass('_expanded'); }else{ $menuSidebar.addClass('_expanded'); } return false; }) $(window).resize(function(){ $menuSidebar.removeClass('_expanded'); }); } if( $footer.length ){ $(window).resize(function(){ $footer_holder.height( $footer.height() + 80 ); }).resize(); } });<file_sep>from django.shortcuts import render from django.views.generic import ListView from . import models class MenuListView(ListView): model = models.Menu template_name = 'restaurant_menu/menu.jade' menu_list = MenuListView.as_view() <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import filebrowser.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Album', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)), ('name', models.CharField(verbose_name='Название альбома', max_length=255)), ], options={ 'verbose_name': 'альбом', 'verbose_name_plural': 'альбомы', }, bases=(models.Model,), ), migrations.CreateModel( name='Photo', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)), ('name', models.CharField(verbose_name='Название фото', max_length=255, blank=True)), ('photo', filebrowser.fields.FileBrowseField(verbose_name='Графический файл', max_length=255)), ('file_order', models.IntegerField(verbose_name='Индекс сортировки')), ('album', models.ForeignKey(verbose_name='Альбом', to='photogalery.Album')), ], options={ 'verbose_name': 'фотографии', 'verbose_name_plural': 'фотографии', }, bases=(models.Model,), ), ] <file_sep>$(function(){ var $frontSlider = $('.pageFront-firstScreen-slider'); if( $frontSlider.length ){ if ( $('.pageFront-firstScreen-slider__item', $frontSlider).length > 1 ){ $frontSlider.responsiveSlides({ timeout: 7000 }); } } });<file_sep>from .settings import * TEST_MODE = True DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'cache-for-tests' } } <file_sep>#!/bin/bash python ./test1.py python ./test2.py python ./test3.py python ./test4.py python ./test5.py python ./test6.py python ./test7.py python ./test8.py python ./test9.py <file_sep># coding: utf-8 """ This file was generated with the custommenu management command, it contains the classes for the admin menu, you can customize this class as you want. To activate your custom menu add the following to your settings.py:: ADMIN_TOOLS_MENU = 'erwin.menu.CustomMenu' """ from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from admin_tools.menu import items, Menu from django.db.models.loading import get_model from django.core.urlresolvers import reverse def create_item(app_name, model_name, title_method='capitalize'): model = get_model(app_name, model_name) return items.MenuItem( getattr(model._meta.verbose_name_plural, title_method)(), reverse('admin:{}_{}_changelist'.format(app_name, model_name.lower())) ) class CustomMenu(Menu): """ Custom Menu for fadm_ts admin site. """ def __init__(self, **kwargs): Menu.__init__(self, **kwargs) self.children += [ items.MenuItem(u'Главная', reverse('admin:index')), items.Bookmarks(), items.ModelList(u'Администрирование', ( 'django.contrib.sites.*', 'apps.core.config.models.SiteConfiguration', )), # items.MenuItem(u'Приложения', children=[ # create_item('persons', 'Person'), # create_item('banners', 'Banner'), # create_item('places', 'Place'), # create_item('holydays', 'Holyday'), # ]), ] def init_with_context(self, context): """ Use this method if you need to access the request context. """ return super(CustomMenu, self).init_with_context(context) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import filebrowser.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Slide', fields=[ ('id', models.AutoField(serialize=False, auto_created=True, primary_key=True, verbose_name='ID')), ('photo', filebrowser.fields.FileBrowseField(max_length=255, verbose_name='Графический файл')), ('photo_order', models.IntegerField(verbose_name='Индекс сортировки')), ], options={ }, bases=(models.Model,), ), ] <file_sep># coding: utf-8 import mock import json import random import unittest from django.test import TestCase as BaseTestCase from django.conf import settings from django.contrib.auth import get_user_model from django.core.urlresolvers import reverse from autofixture import AutoFixture from core.utils import make_random_string User = get_user_model() class TestCase(BaseTestCase): """ Общий класс для тесткейсов. Реализует создание и авторизацию пользователя. """ def create_user(self, **kwargs): self.params = params = dict( useraname='<EMAIL>', email='<EMAIL>', password='<PASSWORD>', phone='79807431721', birthdate='1988-02-13', is_active=True) self.params.update(kwargs) self.user = AutoFixture(User, field_values=self.params).create_one() self.user.set_password(self.params['password']) self.user.save() return params def create_and_login_user(self, **kwargs): params = self.create_user(**kwargs) return self.client.login(**params) def json(self, response): return json.loads(response.content) def defaultdb_is_pg(): return 'postgresql' in settings.DATABASES['default']['ENGINE'] skip_if_not_pg = unittest.skipUnless( defaultdb_is_pg(), u'Тест только для postgresql') def patch_or_pg(*args, **kwargs): def wrap(func): def tmp(self): if defaultdb_is_pg(): return func(self) else: return mock.patch(*args, **kwargs)(func)(self) return tmp return wrap <file_sep>from django.test import TestCase from ..validators import re_phone class PhoneTest(TestCase): def test_1(self): self.assertIsNotNone(re_phone.match('+7 (123) 456-78-90')) def test_2(self): self.assertIsNotNone(re_phone.match('+7(123) 456-78-90')) def test_3(self): self.assertIsNotNone(re_phone.match('+7 123 456-78-90')) def test_4(self): self.assertIsNotNone(re_phone.match('+7 123 456 78 90')) def test_5(self): self.assertIsNotNone(re_phone.match('+71234567890')) def test_6(self): self.assertIsNotNone(re_phone.match('8 123 456-78-90')) <file_sep>from django.shortcuts import render import event.models from . import models def main_list(request): an = event.models.Event.objects.all() return render(request, 'main_site.jade', { 'announces': an, 'slider': models.Slide.objects.all(), }) <file_sep># coding: utf-8 import uuid import random import string from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ def make_random_string(length, delim=''): return delim.join(random.sample(string.letters*length, length)) NULLABLE = dict(blank=True, null=True) phone_validator = RegexValidator( r'7[\d+]{10}', _(u'Введите телефонный номер в формате: 79001231212')) def upload_to(instance, filename): """ Common uploaded file path generator. """ h = str(uuid.uuid4().hex) folder = str(instance.__class__.__name__).lower() return u'{}/{}/{}/{}.{}'.format(folder, h[:2], h[2:4], h, filename.split('.')[-1].lower()) def to_int(val, default=0): """ Silence convert to int. """ try: return int(val) except (TypeError, ValueError): return default def get_filetype(fname): """ Получение нормализованного расширения файла из его имени. Параметры: - fname: имя файла в виде сторки Возвращает: - строку с расширением """ return (fname.split('.') or [''])[-1].lower() <file_sep>""" Configuration of project. """ from .base import * from .logging import * from .bootstrap import * from .celery import * from .app import * from .grappelli_settings import * try: from ..settings_local import * except ImportError: pass <file_sep># coding: utf-8 from funcy import split from django import forms from django.forms.widgets import ( CheckboxFieldRenderer as _CheckboxFieldRenderer) from django.utils.html import format_html from django.utils.encoding import force_text from django.utils.safestring import mark_safe class CheckboxFieldRenderer(_CheckboxFieldRenderer): def render(self): """ Outputs a <ul> for this set of choice fields. If an id was given to the field, it is applied to the <ul> (each item in the list will get an id of `$id_$i`). """ id_ = self.attrs.get('id', None) class_ = self.attrs.get('class', '') columns = split(lambda row: row[0] % 2, enumerate(self)) output = ['<div class="row">'] for c in reversed(columns): if id_: start_tag = format_html( u'<div id="{0}" class="col-md-6 {1}">', id_, class_) else: start_tag = u'<div class="col-md-6">' output.append(start_tag) for i, w in c: output.append(format_html( u"""<div class="checkbox"> <label> <input name="{0.name}" {1} value="{0.choice_value}" type="checkbox"> {0.choice_label} </label> </div>""".format(w, ['', 'checked'][w.is_checked()]))) output.append(u'</div>') output.append(u'</div>') return mark_safe(u'\n'.join(output)) # BASED ON: https://djangosnippets.org/snippets/2860/ class CheckboxSelectMultiple(forms.CheckboxSelectMultiple): renderer = CheckboxFieldRenderer class MultipleChoiceField(forms.MultipleChoiceField): widget = CheckboxSelectMultiple <file_sep># coding: utf-8 from django.conf.urls import patterns, url from django.views.generic import DetailView from . import models urlpatterns = patterns( 'event.views', url(r'^announce/(?P<pk>\d+)/', DetailView.as_view( model=models.Event, template_name='event/announce.jade'), name='announce'), url(r'^photo/(?P<pk>\d+)/', DetailView.as_view( model=models.Event, template_name='event/photo.jade'), name='photo'), url(r'^old_event.json$', 'old_event_json', name='old_event_json'), url(r'^announce.json$', 'announce_json', name='announce_json'), url(r'^$', 'event_lists', name='list'), ) <file_sep>from settings import * IS_PRODUCTION = True DOMAIN = 'erwin.moscow' ALLOWED_HOSTS = ( '127.0.0.1', 'localhost', 'erwin.prod.dvhb.ru', DOMAIN, ) DEBUG = False TEMPLATE_DEBUG = False SITE_ID = 2 <file_sep> from .test_suggest_base_view import * from .utils import *<file_sep># coding: utf-8 from django.template import Context from django.template.loader import get_template from bootstrap3.renderers import FieldRenderer as BaseFieldRenderer # Список именованныз параметров, которые следует исключить из # списка аттрибутов exclude = set(('layout', 'form_group_class', 'field_class', 'label_class', 'show_help', 'show_label', 'exclude', 'set_required', 'size', 'horizontal_label_class', 'horizontal_field_class', 'addon_before', 'addon_after', 'error_css_class', 'required_css_class', 'bound_css_class')) convert_ng = lambda value: value.replace('ng_', 'ng-') class FieldRenderer(BaseFieldRenderer): def __init__(self, field, *args, **kwargs): super(FieldRenderer, self).__init__(field, *args, **kwargs) self.show_required = field.field.required self.tabindex = kwargs.pop('tabindex', None) self.help_on_top = kwargs.pop('help_on_top', False) self.placeholder = kwargs.pop('placeholder', None) self._extra_attrs = {convert_ng(k): v for k, v in kwargs.items() if k not in exclude and v} def add_widget_attrs(self): super(FieldRenderer, self).add_widget_attrs() self.widget.attrs.update(self._extra_attrs) if self.tabindex: self.widget.attrs['tabindex'] = self.tabindex def append_to_field(self, html): help_text_and_errors = [self.field_help] + self.field_errors \ if self.field_help else self.field_errors if not help_text_and_errors: return html help_html = get_template( 'bootstrap3/field_help_text_and_errors.html' ).render(Context({ 'field': self.field, 'help_text_and_errors': help_text_and_errors, 'layout': self.layout, })) if self.help_on_top: html = u'<span class="help-block">{help}</span>'.format( help=help_html) + html else: html += u'<span class="help-block">{help}</span>'.format( help=help_html) return html def add_help_attrs(self): return def get_label(self): label = super(FieldRenderer, self).get_label() if not label: return label return u'{}{}'.format(label, ['', ' *'][self.show_required]) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib.auth.hashers import make_password from django.db import migrations, IntegrityError from django.conf import settings from django.utils import termcolors from django.utils import timezone def create_data(apps, *args, **kwargs): # 1. Переименуем текущий сайт, на текущий домен. from django.contrib.sites.models import Site site = Site.objects.get_or_create(pk=settings.SITE_ID)[0] site.name = site.domain = settings.DOMAIN site.save() def drop_data(apps, *args, **kwargs): pass def create_default_admin(apps, *args, **kwargs): """ Make default admin user. IMPORTANT: change password after done this in production server. """ User = apps.get_model('auth', 'User') email = '<EMAIL>' user = User(username=email, email=email, password=make_password('123'), is_staff=True, is_active=True, is_superuser=True, last_login=timezone.now()) try: user.save() except IntegrityError: print(termcolors.colorize('User admin already created', fg='red')) class Migration(migrations.Migration): dependencies = [ ('auth', '0001_initial'), ('sites', '0001_initial'), ('flatpages', '0001_initial'), ] operations = [ migrations.RunPython(create_data, drop_data), migrations.RunPython(create_default_admin), ] <file_sep>Django==1.7.7 psycopg2==2.5.4 mock==1.0.1 pyjade==3.0.0 CoffeeScript==1.1.0 Fabric==1.10.1 Pillow==2.7.0 django-imagekit==3.2.5 pytils==0.3 django-autofixture==0.9.2 dealer==2.0.4 django-solo==1.1.0 django-ordered-model==0.3.0 dateutils==0.6.6 django-registration-redux==1.1 django-bootstrap3==5.1.1 django-password-reset==0.7 funcy==1.4 redis==2.10.3 django-celery-email==1.0.4 celery==3.1.17 django-celery==3.1.16 django-admin-tools==0.5.2 django-admin-enhancer==1.0.0 raven<5.2.0 django-filebrowser==3.5.7 django-grappelli==2.6.4 django-mptt==0.7.0 sass==2.3 <file_sep>__author__ = 'yttrium' <file_sep># coding: utf-8 import unittest import time import re import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException sys.path.append('./core') import base class TestCase9(base.TestCase): """ В поле "Сколько будет человек" вводится отрицательное число """ def test_9(self): driver = self.driver driver.get('http://erwin:404@erwin.dev.dvhb.ru/') driver.find_element_by_xpath( "//a[contains(@href, '/reservation/add/')]").click() driver.find_element_by_id("id_guest_name").clear() driver.find_element_by_id("id_guest_name").send_keys("test") driver.find_element_by_id("id_guest_count").clear() driver.find_element_by_id("id_guest_count").send_keys("-1") driver.find_element_by_id("datepicker").click() driver.find_element_by_css_selector("div.pmu-next.pmu-button").click() driver.find_element_by_css_selector("div.pmu-next.pmu-button").click() driver.find_element_by_xpath("//div[37]").click() driver.find_element_by_id("timepicker").clear() driver.find_element_by_id("timepicker").send_keys("13:00") driver.find_element_by_id("id_phone").clear() driver.find_element_by_id("id_phone").send_keys("8(111)111-11-11") driver.find_element_by_id("id_comment").clear() driver.find_element_by_id("id_comment").send_keys("test") driver.find_element_by_id("btn_reserv").click() try: self.assertEqual( u"Введите число больше нуля", driver.find_element_by_id("errorCount").text) except AssertionError as e: self.verificationErrors.append(str(e)) try: self.assertEqual( u"Необходимо заполнить все поля,\nкроме поля комментария.", driver.find_element_by_id("errorAll").text) except AssertionError as e: self.verificationErrors.append(str(e)) if __name__ == "__main__": print __file__ print u"В поле \"Сколько будет человек\" вводится отрицательное число" unittest.main() <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('reservation', '0002_2'), ] operations = [ migrations.RemoveField( model_name='changestatus', name='action_char', ), migrations.AddField( model_name='reservation', name='source', field=models.PositiveSmallIntegerField(default=1, blank=True, choices=[(1, 'Сайт'), (2, 'Звонок'), (3, 'Устно')], verbose_name='Источник'), preserve_default=True, ), migrations.AlterField( model_name='reservation', name='status', field=models.PositiveSmallIntegerField(db_index=True, default=1, blank=True, choices=[(1, 'Заявка'), (3, 'Бронь подтверждена'), (4, 'Гость отказался')], verbose_name='Статус'), preserve_default=True, ), ] <file_sep># coding: utf-8 from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from filebrowser.fields import FileBrowseField @python_2_unicode_compatible class Event(models.Model): BUTTON_LOOK = 1 BUTTON_EXT = 2 BUTTON_RESERV = 3 BUTTON_CHOICE = ( (BUTTON_LOOK, ("посмотреть")), (BUTTON_EXT, ("подробнее")), (BUTTON_RESERV, ("забронировать столик")), ) edate = models.DateTimeField(_('Дата события'), help_text=_('Поле сортировки')) title_small = models.CharField( _('Титул (мелкий шрифт)'), max_length=255, blank=True, help_text=_('В титулах возможно вставлять <br />')) title = models.CharField(_('Титул'), max_length=255) button = models.PositiveSmallIntegerField(_('Кнопка'), choices=BUTTON_CHOICE, default=BUTTON_EXT) content = models.TextField(_('Контент')) announce = models.TextField(_('Анонс')) photo = FileBrowseField( _('Графический файл'), max_length=255, directory="event/", extensions=['.jpg', '.jpeg', '.gif', '.png']) class Meta: verbose_name = _('событие') verbose_name_plural = _('события') ordering = ['-edate'] def __str__(self): return self.title def url(self): if self.button == self.BUTTON_LOOK: return reverse('event:photo', kwargs={'pk': self.pk}) elif self.button == self.BUTTON_EXT: return reverse('event:announce', kwargs={'pk': self.pk}) else: return reverse('reservation:add') @property def photo_big(self): return self.photo.version_generate('event_big') @property def photo_mini(self): return self.photo.version_generate('event_mini') @python_2_unicode_compatible class Photo(models.Model): name = models.CharField(_('Название фото'), max_length=255, blank=True) event = models.ForeignKey(Event, verbose_name=_('Событие'), related_name='photos') photo = FileBrowseField(_('Графический файл'), max_length=255, directory="event/", extensions=['.jpg', '.jpeg', '.gif', '.png']) photo_order = models.IntegerField(_('Индекс сортировки')) class Meta: verbose_name = _('фотографии') verbose_name_plural = _('фотографии') ordering = ['photo_order'] def __str__(self): if self.name: return self.name return 'Photo#{0}'.format(self.pk) @property def photo_big(self): return self.photo.version_generate('event_big') @property def photo_mini(self): return self.photo.version_generate('event_mini') <file_sep>from django.contrib import admin from . import models @admin.register(models.Slide) class SlideAdmin(admin.ModelAdmin): list_display = ('__str__', 'photo_order') <file_sep># coding: utf-8 from django.conf.urls import patterns, include, url from django.views.generic import TemplateView, DetailView urlpatterns = patterns( 'restaurant_menu.views', url(r'^$', 'menu_list', name='list'), ) <file_sep># coding=utf-8 from __future__ import unicode_literals from django.apps import AppConfig import os class EventConfig(AppConfig): name = 'event' def ready(self): from django.conf import settings try: os.makedirs( os.path.join( settings.MEDIA_ROOT, 'uploads', 'event' ) ) except OSError: pass <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('event', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='event', options={'ordering': ['-edate'], 'verbose_name_plural': 'события', 'verbose_name': 'событие'}, ), migrations.RemoveField( model_name='event', name='event_order', ), migrations.AddField( model_name='event', name='title_after', field=models.CharField(max_length=255, blank=True, verbose_name='Титул после'), preserve_default=True, ), migrations.AddField( model_name='event', name='title_before', field=models.CharField(max_length=255, blank=True, verbose_name='Титул до'), preserve_default=True, ), ] <file_sep># coding: utf-8 import os import urllib2 import json from datetime import datetime from fabric.api import * import sys sys.path.append(os.path.realpath(os.path.dirname(__file__))) env.slack_url = "https://hooks.slack.com/services/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" env.slack_channel = "#erwin" env.slack_username = "webhookbot" env.env_python = 'python' # Default local development settings env.target_domain = 'localhost:8000' env.logs_dir = env.target_domain + '/logs' env.branch = 'development' class BrokenRelease(Exception): pass def is_local(): return 'localhost' in env.target_domain @task def dev(): env.branch = 'development' env.target_domain = 'erwin.dev.dvhb.ru' env.logs_dir = env.target_domain + '/logs' env.env_python = '/w/erwin/env/bin/python' @task def prod(): env.branch = 'production' @task def test(): """ Run tests. """ m = local('{} manage.py test apps/ --noinput; exit 0;'.format(env.env_python), capture=True) message = m.stderr if is_local(): print(message) return if 'OK' in message: return from fabric.contrib import django django.settings_module('project.settings') from django.conf import settings fname = 'tests.log' log_file = os.path.join(settings.LOG_DIR, fname) with open(log_file, 'w') as f: f.write('[{}]\n\n'.format(datetime.now())) f.write(message) slack_message = u"> Tests failed. Log: <http://{0}{1}{2}>".format( env.target_domain, settings.LOG_URL, fname) payload = { "channel": env.slack_channel, "username": env.slack_username, "text": slack_message } request = urllib2.Request(url=env.slack_url, data=json.dumps(payload)) urllib2.urlopen(request) raise BrokenRelease(slack_message) @task def gtask(task_num): """ Create new branch for task. Based on production. Use: $: fab gtask:ERW-33 """ local('git checkout production') local('git pull origin production') local('git checkout -b {}'.format(task_num)) @task def merge(task_num): """ Merge task into release branch. Use: $: fab dev merge:ERW-33 """ local('git checkout {}'.format(env.branch)) local('git pull origin {}'.format(env.branch)) local('git merge {}'.format(task_num)) local('git push origin {}'.format(env.branch)) @task def new_app(app_name): """ Make structure for new app Use: $: fab new_app:sponsors """ dir_name = os.path.join('apps', app_name) files = ' '.join(os.path.join(dir_name, f) for f in ('__init__.py', 'models.py', 'views.py', 'admin.py', 'urls.py')) cmd = 'mkdir {0} && touch {1}' local(cmd.format(dir_name, files)) test_dir = os.path.join(dir_name, 'tests') local(cmd.format(test_dir, os.path.join(test_dir, '__init__.py'))) <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import reservation.validators class Migration(migrations.Migration): dependencies = [ ('reservation', '0003_auto_20150330_1329'), ] operations = [ migrations.AlterField( model_name='changestatus', name='action', field=models.PositiveSmallIntegerField(default=1, choices=[(1, 'Заявка'), (2, 'Редактирование'), (3, 'Бронь подтвержена'), (4, 'Бронь отклонена'), (6, 'Невозможно связаться'), (5, 'Выбран столик')]), preserve_default=True, ), migrations.AlterField( model_name='reservation', name='reservation_date', field=models.DateTimeField(verbose_name='Дата брони', db_index=True, validators=[reservation.validators.validate_future, reservation.validators.validate_workhours], blank=True, help_text='На какую дату и время забронировать? (Мы работаем с 11:00 до 00:00)', null=True), preserve_default=True, ), migrations.AlterField( model_name='reservation', name='status', field=models.PositiveSmallIntegerField(verbose_name='Статус', db_index=True, choices=[(1, 'Заявка'), (3, 'Бронь подтверждена'), (4, 'Гость отказался'), (6, 'Невозможно связаться')], default=1, blank=True), preserve_default=True, ), ] <file_sep># coding: utf-8 BOOTSTRAP3 = { 'field_renderers': { 'default': 'core.bootstrap.FieldRenderer', 'inline': 'bootstrap3.renderers.InlineFieldRenderer', } } <file_sep># coding: utf-8 from functools import wraps from django.shortcuts import redirect def redirect_after(): """ Декоратор на вьюху, который в конце работы запроса возвращает редирект по рефереру или параметру next. """ def decorator(f): @wraps(f) def decorated_function(request, *args, **kwargs): url = ( request.GET.get('next', None) or request.META.get('HTTP_REFERER') ) result = f(request, *args, **kwargs) or url return redirect(result) return decorated_function return decorator <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.test import RequestFactory from core.tests.utils import TestCase, User from .. import models, views, consts class ReservationTestCase(TestCase): """ Тестирование брони """ phone = '+7(123)123-56-78' params = { 'guest_name': 'vasya', 'guest_count': '1', 'phone': phone, 'reservation_date': '2159-11-11 18:50:00', 'source': consts.SOURCE_PHONE, } def setUp(self): self.factory = RequestFactory() self.user = User.objects.create_user( username='jacob', email='jacob@…', password='<PASSWORD>') def test_add_reservation(self): """ Добавление брони """ url = reverse('reservation:add') view = views.ReservationAddView.as_view() request = self.factory.post(url, self.params) request.user = self.user response = view(request) self.assertEqual(response.status_code, 302) reserv = models.Reservation.objects.filter(phone=self.phone).first() self.assertIsNotNone(reserv) statuses = [s.action for s in reserv.statuses.all()] self.assertEqual(len(statuses), 2) self.assertIn(consts.ACTION_CREATE, statuses) self.assertIn(consts.ACTION_APPROVE, statuses) def test_edit_reservation(self): """ Редактирование брони """ reserv = models.Reservation.objects.create(**self.params) self.assertIsNotNone(reserv) url = reverse('reservation:edit', kwargs={'pk': reserv.pk}) view = views.ReservationUpdateView.as_view() request = self.factory.post(url, self.params) request.user = self.user response = view(request, pk=reserv.pk) self.assertEqual(response.status_code, 302) statuses = [ s.action for s in reserv.statuses.all() ] self.assertEqual(len(statuses), 1) self.assertIn(consts.ACTION_EDIT, statuses) def action_reservation(self, view, url_name, action): reserv = models.Reservation.objects.create(**self.params) self.assertIsNotNone(reserv) url = reverse(url_name, kwargs={'pk': reserv.pk}) request = self.factory.get(url) request.user = self.user response = view(request, pk=reserv.pk) self.assertEqual(response.status_code, 302) statuses = [ s.action for s in reserv.statuses.all() ] self.assertEqual(len(statuses), 1) self.assertIn(action, statuses) def test_approve_reservation(self): """ Подтверждение брони """ self.action_reservation( views.ReservationApproveView.as_view(), 'reservation:approve', consts.ACTION_APPROVE ) def test_reject_reservation(self): """ Отмена брони """ self.action_reservation( views.ReservationRejectView.as_view(), 'reservation:reject', consts.ACTION_REJECT ) <file_sep># coding: utf-8 """ Django settings for project. For more information on this file, see https://docs.djangoproject.com/en/1.7/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.7/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os import sys import tempfile from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP BASE_DIR = os.path.dirname(os.path.dirname(os.path.join(os.path.dirname(__file__)))) sys.path.append(os.path.join(BASE_DIR, 'apps')) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'qojewoifjpofki39hdf83k9387%e3v&di6@@c&(xkbomxwlyfv' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False TEMPLATE_DEBUG = False TEST_MODE = False ADMINS = ( ('Vlaimidr', '<EMAIL>'), ('Alexander', '<EMAIL>'), ) DOMAIN = 'erwin.dev.dvhb.ru' ALLOWED_HOSTS = ( '127.0.0.1', 'localhost', DOMAIN, ) # Application definition INSTALLED_APPS = ( 'grappelli.dashboard', 'grappelli', 'filebrowser', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', # Ours apps 'core', 'first_page.apps.MainConfig', 'restaurant_menu.apps.MenuConfig', 'photogalery.apps.PhotoGaleryConfig', 'event.apps.EventConfig', 'site_conf', 'reservation', # 3rd apps 'pytils', 'ordered_model', 'solo', 'mptt', 'registration', 'bootstrap3', 'password_reset', 'djcelery', 'djcelery_email', 'admin_enhancer', 'raven.contrib.django.raven_compat', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware', ) ROOT_URLCONF = 'project.urls' WSGI_APPLICATION = 'project.wsgi.application' # Database # https://docs.djangoproject.com/en/1.7/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.7/topics/i18n/ LANGUAGE_CODE = 'ru-RU' TIME_ZONE = 'Europe/Moscow' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.7/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = os.path.realpath(os.path.join(BASE_DIR, '..', 'static')) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.realpath(os.path.join(BASE_DIR, '..', 'media')) TEMPLATE_DIRS = ( os.path.join(BASE_DIR, 'templates'), ) TEMPLATE_LOADERS = ( ('pyjade.ext.django.Loader', ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', )), ) TEMPLATE_CONTEXT_PROCESSORS = TCP + ( 'django.core.context_processors.request', 'core.context_processors.is_production', 'core.context_processors.some_settings', 'dealer.contrib.django.context_processor', ) IS_PRODUCTION = False SITE_ID = 1 ACCOUNT_ACTIVATION_DAYS = 7 AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': tempfile.gettempdir(), 'TIMEOUT': 60, 'OPTIONS': { 'MAX_ENTRIES': 1000 } } } EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = '<EMAIL>' EMAIL_HOST_PASSWORD = '<PASSWORD>' SERVER_EMAIL = DEFAULT_FROM_EMAIL = \ 'Erwin <<EMAIL>>' EMAIL_USE_TLS = True <file_sep><!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Erwin</title> <link rel="stylesheet" href="/static/css/style.css"> <script src="/static/js/app-common.js"></script> <script src="/static/js/app.js"></script> </head> <body> <header class="header"> <div class="section_wide"><a href="#" class="header__logo"></a> <div class="header-menuSidebar"><a href="#" class="header-burger"></a> <div class="header-menu"><a href="#" class="header-menu__item">Меню</a><a href="#" class="header-menu__item _active">События</a><a href="#" class="header-menu__item">Фотогалерея</a><a href="#" class="header-menu__item sm-hidden">3D-тур</a><a href="#" class="header-menu__item sm-showed">План ресторана</a><a href="#" class="header-menu__item">Контакты</a></div> <div class="header-menuSidebar__footer"><a href="#" class="btn header__request">Забронировать </a> <div class="header__phone">+7 495 785 02 22<b>C 12:00 до последнего гостя</b></div> </div> </div><a href="#" class="btn header__request sm-showed">Забронировать </a> </div> </header> <div class="page pageService"> <div class="section"> <h1>Страница не найдена</h1> <p> Почему там могло произойти?<br /> Вот самые распространённые причины: </p> <div class="pageService__triple justifyed"> <div class="span3"> <h2>Страница была перемещена</h2> <p> Страница может ещё существует, но находится по другомуадресу. Попробуйте найти её в других разделах. </p> </div> <div class="span3"> <h2>Страница была удалена</h2> <p> Страницы на сайте больше нет по каким-то внутренним причинам. Попасть на неё уже не получится. </p> </div> <div class="span3"> <h2>В адрес закралась ошибка</h2> <p> Попробуйте проверить адрес этой страницы, возможно где-то там закралась опечатка, которую можно исправить </p> </div> </div> <div class="sm-hidden"> <p>Или позвоните нам по телефону</p> <div class="pageService-phone"> <div class="pageService-phone__item">+7 495 785 02 22</div> <div class="pageService-phone__item">+7 495 785 02 22</div> </div> </div> </div> </div> <div class="footer-holder"></div> <div class="footer"> <div class="section_wide"> <div class="footer-menu"><a href="#" class="footer-menu__item">Бронирование</a><a href="#" class="footer-menu__item">Меню</a><a href="#" class="footer-menu__item">Фотогалерея</a><a href="#" class="footer-menu__item">События</a><a href="#" class="footer-menu__item"><NAME></a><a href="#" class="footer-menu__item">Контакты</a></div> <div class="footer-phone"> <div class="footer-phone__item">+7 495 785 02 22</div> <div class="footer-phone__item">+7 495 785 02 22</div> </div> <div class="footer-socials"><a href="#" class="footer-socials__item footer-socials__item_fb"></a><a href="#" class="footer-socials__item footer-socials__item_ig"></a><a href="#" class="footer-socials__item footer-socials__item_vk"></a><a href="#" class="footer-socials__item footer-socials__item_tw"></a></div> <div class="footer__copy">© 2015 Ресторан «Erwin»</div> <div class="footer__dev">Сделано в <a href="#">ДевХаб</a></div> </div> </div> </body> </html><file_sep>from django.conf.urls import patterns, url from django.contrib.auth.decorators import permission_required from django.shortcuts import redirect from . import views prequired = permission_required('add_reservation') urlpatterns = patterns( '', url(r'^request/$', prequired(views.RequestView.as_view()), name='requests'), url(r'^actual/$', prequired(views.ActualView.as_view()), name='actuals'), url(r'^notactual/$', prequired(views.NotActualView.as_view()), name='notactuals'), url(r'^all/$', prequired(views.ReservationListView.as_view()), name='all'), url(r'^add/$', views.ReservationAddView.as_view(), name='add'), url(r'^detail/(?P<pk>\d+)/$', prequired(views.ReservationDetailView.as_view()), name='detail'), url(r'^approve/(?P<pk>\d+)/$', prequired(views.ReservationApproveView.as_view()), name='approve'), url(r'^reject/(?P<pk>\d+)/$', prequired(views.ReservationRejectView.as_view()), name='reject'), url(r'^impossible_to_phone/(?P<pk>\d+)/$', prequired(views.ReservationImpossibleToPhoneView.as_view()), name='impossible_to_phone'), url(r'^table/(?P<pk>\d+)/$', prequired(views.ReservationTableListView.as_view()), name='table_list'), url(r'^table/(?P<pk>\d+)/(?P<table_pk>\d+)/$', prequired(views.ReservationTableView.as_view()), name='table'), url(r'^(?P<pk>\d+)/$', prequired(views.ReservationUpdateView.as_view()), name='edit'), url(r'^$', lambda x: redirect('reservation:add'), name='index'), ) <file_sep># coding: utf-8 from __future__ import unicode_literals from django.utils.encoding import force_text from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from django.db import models from solo.models import SingletonModel @python_2_unicode_compatible class Contacts(SingletonModel): phone1 = models.CharField(_('Телефон-1'), max_length=25) phone2 = models.CharField(_('Телефон-2'), max_length=25, blank=True) address = models.TextField(_('Адрес'), blank=True) email = models.EmailField(_('Адрес электронной почты'), blank=True) def __str__(self): return force_text(_("Контакты")) class Meta: verbose_name = _("Контакты") <file_sep># coding: utf-8 import djcelery djcelery.setup_loader() BROKER_URL = 'redis://127.0.0.1:6379/1' CELERY_EMAIL_TASK_CONFIG = { 'name': 'djcelery_email_send', 'ignore_result': True, } EMAIL_BACKEND = 'djcelery_email.backends.CeleryEmailBackend' <file_sep># coding: utf-8 from __future__ import unicode_literals from django.db import models from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from filebrowser.fields import FileBrowseField @python_2_unicode_compatible class Slide(models.Model): photo = FileBrowseField(_('Графический файл'), max_length=255, directory="event/", extensions=['.jpg', '.jpeg', '.gif', '.png']) photo_order = models.IntegerField(_('Индекс сортировки')) def __str__(self): return 'Photo #%s' % self.pk <file_sep>from django.contrib import admin from . import models class PhotoInline(admin.TabularInline): model = models.Photo sortable_field_name = 'file_order' @admin.register(models.Album) class AlbumAdmin(admin.ModelAdmin): inlines = [PhotoInline] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import filebrowser.fields class Migration(migrations.Migration): dependencies = [ ('event', '0002_auto_20150406_0231'), ] operations = [ migrations.AlterModelOptions( name='photo', options={'ordering': ['photo_order'], 'verbose_name_plural': 'фотографии', 'verbose_name': 'фотографии'}, ), migrations.RemoveField( model_name='event', name='announce_photo', ), migrations.RemoveField( model_name='event', name='title_after', ), migrations.RemoveField( model_name='event', name='title_before', ), migrations.AddField( model_name='event', name='button', field=models.PositiveSmallIntegerField(choices=[(1, 'посмотреть'), (2, 'подробнее'), (3, 'забронировать столик')], verbose_name='Кнопка', default=2), preserve_default=True, ), migrations.AddField( model_name='event', name='photo', field=filebrowser.fields.FileBrowseField(max_length=255, default='', verbose_name='Графический файл'), preserve_default=False, ), migrations.AddField( model_name='event', name='title_small', field=models.CharField(blank=True, max_length=255, verbose_name='Титул (мелкий шрифт)', help_text='В титулах возможно вставлять <br />'), preserve_default=True, ), migrations.AlterField( model_name='event', name='edate', field=models.DateTimeField(verbose_name='Дата события', help_text='Поле сортировки'), preserve_default=True, ), ] <file_sep># coding: utf-8 from django.conf.urls import patterns, include, url from django.views.generic import TemplateView, DetailView urlpatterns = patterns( 'photogalery.views', url(r'^album/(?P<album>\d+)/photo.json$', 'photo_json', name='photo_json'), url(r'^$', 'album_list', name='list'), ) <file_sep># coding: utf-8 import os from datetime import datetime from django import template from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.conf import settings from pytils import dt register = template.Library() @register.filter def human_date_format(date, format='%d %B %Y'): now = datetime.now().date() if date.date() == now: return _(u'Сегодня') return dt.ru_strftime(format, date, inflected=True, inflected_day=False, preposition=False) @register.inclusion_tag('core/form_group_title.jade', takes_context=True) def form_group_title(context, title='', icon=None): if icon: icon = 'img/{}.png'.format(icon) return locals() <file_sep>GRAPPELLI_ADMIN_TITLE ='Erwin' GRAPPELLI_INDEX_DASHBOARD = 'erwin_dashboard.grappelli_dashboard.ErwinIndexDashboard' FILEBROWSER_MAX_UPLOAD_SIZE = 50*1024**2 FILEBROWSER_VERSIONS = { 'admin_thumbnail': {'verbose_name': 'Admin Thumbnail', 'width': 60, 'height': 60, 'opts': 'crop'}, 'thumbnail': {'verbose_name': 'Thumbnail (1 col)', 'width': 60, 'height': 60, 'opts': 'crop'}, 'small': {'verbose_name': 'Small (2 col)', 'width': 140, 'height': '', 'opts': ''}, 'medium': {'verbose_name': 'Medium (4col )', 'width': 300, 'height': '', 'opts': ''}, 'big': {'verbose_name': 'Big (6 col)', 'width': 460, 'height': '', 'opts': ''}, 'large': {'verbose_name': 'Large (8 col)', 'width': 680, 'height': '', 'opts': ''}, 'event_mini': {'verbose_name': 'EventMini', 'width': 590, 'height': '', 'opts': ''}, 'event_big': {'verbose_name': 'EventBig', 'width': 1180, 'height': '', 'opts': ''}, 'menu': {'verbose_name': 'Menu', 'width': '', 'height': 788, 'opts': ''}, } <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import filebrowser.fields class Migration(migrations.Migration): dependencies = [ ('restaurant_menu', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='pdffile', name='parent', ), migrations.DeleteModel( name='PdfFile', ), migrations.AlterModelOptions( name='menu', options={'verbose_name_plural': 'меню', 'verbose_name': 'пункт меню', 'ordering': ['menu_order']}, ), migrations.RemoveField( model_name='menu', name='level', ), migrations.RemoveField( model_name='menu', name='lft', ), migrations.RemoveField( model_name='menu', name='parent', ), migrations.RemoveField( model_name='menu', name='rght', ), migrations.RemoveField( model_name='menu', name='tree_id', ), migrations.AddField( model_name='menu', name='pdf', field=filebrowser.fields.FileBrowseField(verbose_name='PDF-файл', max_length=255, default=''), preserve_default=False, ), migrations.AddField( model_name='menu', name='photo', field=filebrowser.fields.FileBrowseField(verbose_name='Графический файл', max_length=255, default=''), preserve_default=False, ), ] <file_sep>$(function(){ var $gallery = $('.pageGallery-item'); if( $gallery.length ){ var $link = $gallery.find('.pageGallery-item__link'); $link.click(function(){ $gallery.find('.pageGallery-item__slider').hide().prev('.blockPromo').show(); var currentSlider = $(this).closest('.blockPromo').hide().next('.pageGallery-item__slider').fadeIn(); if( !!$('.flexslider').removeData("flexslider") ){ $('.flexslider').removeData("flexslider"); } $('[galleryFlexslider_nav]', currentSlider).flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, itemWidth: 150, itemMargin: 1, asNavFor: $('[galleryFlexslider]', currentSlider), minItems: 4, maxItems: 8 }); $('[galleryFlexslider]', currentSlider).flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, sync: $('[galleryFlexslider_nav]', currentSlider) }); $(window).resize(); return false; }); } });<file_sep>$(function(){ var $contactsMap = $('[contactsMap]'); if( $contactsMap.length ){ function initialize() { var map_styles = [ { "featureType": "water", "elementType": "geometry.fill", "stylers": [ { "color": "#b1c3d0" } ] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [ { "color": "#E6E6E6" } ] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [ { "color": "#677079" } ] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [ { "color": "#000000" } ] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [ { "saturation": -70 }, { "gamma": 1.1 }, { "lightness": -20 }, { "hue": "#677079"} ] }, { "featureType": "poi", "elementType": "geometry", "stylers": [ { "saturation": -80 }, { "gamma": 1.1 }, { "lightness": -20 }, { "hue": "#677079"} ] }, { "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [ { "color": "#ffffff" } ] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [ { "color": "#000000" } ] } ] var styledMap = new google.maps.StyledMapType(map_styles,{name: "Styled Map"}); var myLatlng = new google.maps.LatLng(55.752038, 37.568861); var mapOptions = { scrollwheel: false, zoom: 16, center: myLatlng, mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'] } } var map = new google.maps.Map($contactsMap.get(0), mapOptions); map.mapTypes.set('map_style', styledMap); map.setMapTypeId('map_style'); var markerIcon = new google.maps.MarkerImage( "/static/img/mapMarker.png", null, null, null, new google.maps.Size(63,96) ); var marker = new google.maps.Marker({ position: myLatlng, map: map, icon: markerIcon }); } google.maps.event.addDomListener(window, 'load', initialize); } })<file_sep>/** * appName - http://dvhb.ru * @version v0.1.0 * @author <EMAIL> */ $(function(){ var $footer_holder = $('.footer-holder'); var $footer = $('.footer'); var $menuBurger = $('.header-burger'); if( $menuBurger.length ){ var $menuSidebar = $menuBurger.parent(); $menuBurger.click(function(){ if( $menuSidebar.hasClass('_expanded') ){ $menuSidebar.removeClass('_expanded'); }else{ $menuSidebar.addClass('_expanded'); } return false; }) $(window).resize(function(){ $menuSidebar.removeClass('_expanded'); }); } if( $footer.length ){ $(window).resize(function(){ $footer_holder.height( $footer.height() + 80 ); }).resize(); } }); (function() { }).call(this); $(function(){ var $contactsMap = $('[contactsMap]'); if( $contactsMap.length ){ function initialize() { var map_styles = [ { "featureType": "water", "elementType": "geometry.fill", "stylers": [ { "color": "#b1c3d0" } ] }, { "featureType": "road", "elementType": "geometry.fill", "stylers": [ { "color": "#E6E6E6" } ] }, { "featureType": "road", "elementType": "geometry.stroke", "stylers": [ { "color": "#677079" } ] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [ { "color": "#000000" } ] }, { "featureType": "landscape", "elementType": "geometry", "stylers": [ { "saturation": -70 }, { "gamma": 1.1 }, { "lightness": -20 }, { "hue": "#677079"} ] }, { "featureType": "poi", "elementType": "geometry", "stylers": [ { "saturation": -80 }, { "gamma": 1.1 }, { "lightness": -20 }, { "hue": "#677079"} ] }, { "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [ { "color": "#ffffff" } ] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [ { "color": "#000000" } ] } ] var styledMap = new google.maps.StyledMapType(map_styles,{name: "Styled Map"}); var myLatlng = new google.maps.LatLng(55.752038, 37.568861); var mapOptions = { scrollwheel: false, zoom: 16, center: myLatlng, mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style'] } } var map = new google.maps.Map($contactsMap.get(0), mapOptions); map.mapTypes.set('map_style', styledMap); map.setMapTypeId('map_style'); var markerIcon = new google.maps.MarkerImage( "/static/img/mapMarker.png", null, null, null, new google.maps.Size(63,96) ); var marker = new google.maps.Marker({ position: myLatlng, map: map, icon: markerIcon }); } google.maps.event.addDomListener(window, 'load', initialize); } }) $(function(){ $('[flexslider_nav]').flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, itemWidth: 150, itemMargin: 1, asNavFor: '[flexslider]', minItems: 4, maxItems: 8 }); $('[flexslider]').flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, sync: "[flexslider_nav]" }); }); $(function(){ var $frontSlider = $('.pageFront-firstScreen-slider'); if( $frontSlider.length ){ if ( $('.pageFront-firstScreen-slider__item', $frontSlider).length > 1 ){ $frontSlider.responsiveSlides({ timeout: 7000 }); } } }); $(function(){ var $gallery = $('.pageGallery-item'); if( $gallery.length ){ var $link = $gallery.find('.pageGallery-item__link'); $link.click(function(){ $gallery.find('.pageGallery-item__slider').hide().prev('.blockPromo').show(); var currentSlider = $(this).closest('.blockPromo').hide().next('.pageGallery-item__slider').fadeIn(); if( !!$('.flexslider').removeData("flexslider") ){ $('.flexslider').removeData("flexslider"); } $('[galleryFlexslider_nav]', currentSlider).flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, itemWidth: 150, itemMargin: 1, asNavFor: $('[galleryFlexslider]', currentSlider), minItems: 4, maxItems: 8 }); $('[galleryFlexslider]', currentSlider).flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, sync: $('[galleryFlexslider_nav]', currentSlider) }); $(window).resize(); return false; }); } }); (function() { $(function() { var count, errors, form, phone, rdate, rdatetime, re_count, re_date, re_phone, re_time, rtime, vali_date, vali_phone, vali_time; form = $('#formReservation'); if (form.length) { rdate = $('#datepicker'); rtime = $('#timepicker'); rdatetime = $('#id_reservation_date'); phone = $('#id_phone'); count = $('#id_guest_count'); re_count = /^\d+$/; re_date = /^(\d\d)\/(\d\d)\/(\d\d\d\d)$/; re_time = /^(\d{1,2}):?(\d\d)?$/; re_phone = /^(\+?\d{1,2})\s?\(?(\d{3})\)?\s?(\d{3})[\-\s]?(\d{2})[\-\s]?(\d{2})$/; errors = $('form .form-descr_error'); vali_date = function(d) { var da; da = new Date(d.replace(' ', 'T')); if (da >= new Date()) { return true; } $('#errorFuture').show(); return false; }; vali_time = function(t) { var hour; hour = parseInt(t[0]); if (hour > 23) { t[0] = '23'; t[1] = '59'; return true; } else if (hour >= 12) { return true; } else if (hour < 10) { t[0] = '0' + hour; } $('#errorTime').show(); return false; }; vali_phone = function(ph) { if (ph) { ph.shift(); phone.val(ph[0] + ' (' + ph[1] + ') ' + ph[2] + '-' + ph[3] + '-' + ph[4]); return true; } $('#errorPhone').show(); return false; }; return form.submit(function(e) { var c, d, ph, t; d = re_date.exec(rdate.val()); t = re_time.exec(rtime.val()); ph = re_phone.exec(phone.val()); c = re_count.exec(count.val()); errors.hide(); if (!c || c < 1) { $('#errorCount').show(); e.preventDefault(); } else if (c > 1000) { $('#errorCountBig').show(); e.preventDefault(); } if (!vali_phone(ph)) { e.preventDefault(); } if (d || t) { if (d) { d.shift(); d.reverse(); d = d.join('-'); } else { $('#errorNoDate').show(); e.preventDefault(); } if (t) { t.shift(); if (!vali_time(t)) { e.preventDefault(); } if (!t[1]) { t[1] = '00'; } t = t.join(':'); rtime.val(t); } d += ' ' + t; if (!vali_date(d)) { e.preventDefault(); } else { rdatetime.val(d); } } if (!d && !t) { rdate.focus(); $('#errorNoDate').show(); e.preventDefault(); } $('#errorAll').show(); }); } }); }).call(this); $(function(){ var $datepicker = $('[datepicker]'); var $time = $('.pageRequest-frm__time input'); var $phone = $('.pageRequest-frm__phone input'); $time.mask('99:99'); $phone.mask('8(999)999-99-99'); if( $datepicker.length ){ $datepicker.pickmeup({ position : 'bottom', hide_on_select : true, format: 'd/m/Y', locale : { days : ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота', 'Воскресенье'], daysShort : ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'], daysMin : ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс'], months : ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'], monthsShort : ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'] } }); } }); <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations, DatabaseError from django.conf import settings from django.utils import termcolors def update_action(apps, *args, **kwargs): CS = apps.get_model('reservation', 'changestatus') for cs in CS.objects.all(): cs.action = int(cs.action_char) try: cs.save(update_fields=['action']) except DatabaseError: print(termcolors.colorize('ChangeStatus save error', fg='red')) class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('reservation', '0001_initial'), ] operations = [ migrations.AlterField( model_name='changestatus', name='action', field=models.CharField(null=True, max_length=1), preserve_default=True, ), migrations.RenameField( model_name='changestatus', old_name='action', new_name='action_char' ), migrations.AddField( model_name='changestatus', name='action', field=models.PositiveSmallIntegerField(default=1, choices=[(1, 'Заявка'), (2, 'Редактирование'), (3, 'Бронь подтвержена'), (4, 'Бронь отклонена')]), preserve_default=True, ), migrations.RunPython(update_action), migrations.AddField( model_name='reservation', name='user', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, blank=True, verbose_name='Автор', null=True), preserve_default=True, ), migrations.AlterField( model_name='reservation', name='status', field=models.PositiveSmallIntegerField(choices=[(1, 'Заявка'), (3, 'Бронь подтверждена'), (4, 'Гость отказался')], default=1, db_index=True, verbose_name='Статус'), preserve_default=True, ), ] <file_sep># coding: utf-8 import unittest import time import re import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException sys.path.append('./core') import base class TestCase2(base.TestCase): """ Ни одно из полей формы не заполнено """ def test_2(self): driver = self.driver driver.get('http://erwin:404@erwin.dev.dvhb.ru/') driver.find_element_by_xpath( "//a[contains(@href, '/reservation/add/')]").click() self.assertEqual("true", driver.find_element_by_id( "id_guest_count").get_attribute("required")) if __name__ == "__main__": print __file__ print u"Ни одно из полей формы не заполнено" unittest.main() <file_sep>from django.contrib import admin from . import models class PhotoInline(admin.TabularInline): model = models.Photo sortable_field_name = 'photo_order' @admin.register(models.Event) class EventAdmin(admin.ModelAdmin): list_display = ('title', 'edate') inlines = [PhotoInline] class Media: js = [ '/static/grappelli/tinymce/jscripts/tiny_mce/tiny_mce.js', '/static/grappelli/tinymce_setup/tinymce_setup.js', ] <file_sep># coding=utf-8 from __future__ import unicode_literals from django.shortcuts import redirect from django.template.response import TemplateResponse from django.utils import timezone from functools import update_wrapper from django.contrib import admin from django.core.urlresolvers import reverse from django.utils.translation.trans_null import gettext_lazy as _ from . import models from . import consts class BaseModel(admin.ModelAdmin): date_hierarchy = 'reservation_date' list_filter = ( 'reservation_date', 'request_date', 'change_date', ) def save_model(self, request, obj, form, change): created = not obj.pk if created: obj.status = consts.STATUS_APPROVE obj.save() if created: models.ChangeStatus.objects.create( user=request.user, reservation=obj, action=consts.ACTION_CREATE ) models.ChangeStatus.objects.create( user=request.user, reservation=obj, action=consts.ACTION_APPROVE ) else: models.ChangeStatus.objects.create( user=request.user, reservation=obj, action=consts.ACTION_EDIT ) def get_urls(self): from django.conf.urls import patterns, url def wrap(view): def wrapper(*args, **kwargs): return self.admin_site.admin_view(view)(*args, **kwargs) return update_wrapper(wrapper, view) info = self.model._meta.app_label, self.model._meta.model_name urlpatterns = patterns( '', url(r'^(.+)/approve$', wrap(self.approve_view), name='%s_%s_approve' % info), url(r'^(.+)/reject', wrap(self.reject_view), name='%s_%s_reject' % info), ) + super(BaseModel, self).get_urls() return urlpatterns def approve_view(self, request, object_id, form_url='', extra_context=None): obj = self.get_object(request, object_id) obj.approve(None) models.ChangeStatus.objects.create( user=request.user, reservation=obj, action=consts.ACTION_APPROVE ) return redirect('..') def reject_view(self, request, object_id, form_url='', extra_context=None): obj = self.get_object(request, object_id) obj.reject() models.ChangeStatus.objects.create( user=request.user, reservation=obj, action=consts.ACTION_REJECT ) return redirect('..') @admin.register(models.Request) class RequestAdmin(BaseModel): list_display = ( 'request_date', 'reservation_date', 'guest_count', 'guest_name', 'phone', 'status_request', ) fields = ( 'guest_name', 'guest_count', 'reservation_date', 'phone', 'comment', ) list_display_links = None def status_request(self, obj): info = self.model._meta.app_label, self.model._meta.model_name if obj.status == consts.STATUS_REQUEST: return ''' <a href='{approve_link}'>Подтвердить</a>, <a href='{edit_link}'>Редактировать</a>, <a href='{reject_link}'>Отклонить</a> '''.format( edit_link=reverse('admin:%s_%s_change' % info, args=(obj.id,)), approve_link=reverse('admin:%s_%s_approve' % info, args=(obj.id,)), reject_link=reverse('admin:%s_%s_reject' % info, args=(obj.id,)), ) elif obj.status == consts.STATUS_APPROVE: status = _('Подтверждено') table = 'выбрать столик' if obj.table_id: table = obj.table.name table = '<span class=table-suggest><a href="#">{0} &#9660;</a></span>' \ ''.format(table) elif obj.status == consts.STATUS_REJECT: status = _('Отклонено') table = '' else: status = _('Заявка') table = '' tz = timezone.get_current_timezone() cdate = obj.change_date.astimezone(tz) result = [ status, '{:%H:%M %d.%m}'.format(cdate), ] if table: result.append(table) return ', '.join(result) status_request.short_description = _('Статус') status_request.allow_tags = True class ReservationAdmin(BaseModel): list_display = ( 'request_date', 'reservation_date', 'guest_count', 'table', 'guest_name', 'phone', 'status', ) fields = ( 'guest_name', 'guest_count', 'reservation_date', 'phone', 'table', 'comment', ) raw_id_fields = ('table', ) autocomplete_lookup_fields = { 'fk': ['table'], } class AReservationAdmin(ReservationAdmin): list_display_links = None admin.register(models.Reservation)(ReservationAdmin) admin.register(models.ActualReservation)(AReservationAdmin) admin.register(models.NotActualReservation)(AReservationAdmin) class TableInline(admin.TabularInline): model = models.Table fields = ['name', 'description', 'table_order'] sortable_field_name = 'table_order' @admin.register(models.Zone) class ZoneAdmin(admin.ModelAdmin): inlines = [TableInline] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import filebrowser.fields class Migration(migrations.Migration): dependencies = [ ('photogalery', '0001_initial'), ] operations = [ migrations.AlterModelOptions( name='photo', options={'verbose_name': 'фотографии', 'ordering': ['file_order'], 'verbose_name_plural': 'фотографии'}, ), migrations.RemoveField( model_name='photo', name='name', ), migrations.AddField( model_name='album', name='photo', field=filebrowser.fields.FileBrowseField(max_length=255, verbose_name='Графический файл', default=''), preserve_default=False, ), migrations.AlterField( model_name='photo', name='album', field=models.ForeignKey(related_name='photos', to='photogalery.Album', verbose_name='Альбом'), preserve_default=True, ), ] <file_sep>ADMIN_TOOLS_MENU = 'erwin_dashboard.menu.CustomMenu' ADMIN_TOOLS_INDEX_DASHBOARD = 'erwin_dashboard.dashboard.CustomIndexDashboard' ADMIN_TOOLS_APP_INDEX_DASHBOARD = 'erwin_dashboard.dashboard.CustomAppIndexDashboard' # ADMIN_TOOLS_THEMING_CSS = <file_sep># coding: utf-8 import unittest import time import re import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException sys.path.append('./core') import base class TestCase5(base.TestCase): """ Не заполнено поле "Ваш контактный номер" """ def test_5(self): driver = self.driver driver.get("http://erwin:404@erwin.dev.dvhb.ru/") driver.find_element_by_xpath( "//a[contains(@href, '/reservation/add/')]").click() driver.find_element_by_id("id_guest_name").clear() driver.find_element_by_id("id_guest_name").send_keys("test") driver.find_element_by_id("id_guest_count").clear() driver.find_element_by_id("id_guest_count").send_keys("2") driver.find_element_by_id("datepicker").click() driver.find_element_by_css_selector("div.pmu-next.pmu-button").click() driver.find_element_by_css_selector("div.pmu-next.pmu-button").click() driver.find_element_by_xpath("//div[34]").click() driver.find_element_by_id("id_comment").clear() driver.find_element_by_id("id_comment").send_keys("test") driver.find_element_by_id("btn_reserv").click() self.assertEqual( "true", driver.find_element_by_id("id_phone").get_attribute("required")) if __name__ == "__main__": print __file__ print u"Не заполнено поле \"Ваш контактный номер\"" unittest.main() <file_sep># coding: utf-8 from __future__ import unicode_literals from django.db import models from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from filebrowser.fields import FileBrowseField @python_2_unicode_compatible class Album(models.Model): name = models.CharField(_('Название альбома'), max_length=255) photo = FileBrowseField(_('Графический файл'), max_length=255, directory="albums/", extensions=['.jpg', '.jpeg', '.gif', '.png']) class Meta: verbose_name = _('альбом') verbose_name_plural = _('альбомы') def __str__(self): return self.name @python_2_unicode_compatible class Photo(models.Model): album = models.ForeignKey(Album, verbose_name=_('Альбом'), related_name='photos') photo = FileBrowseField(_('Графический файл'), max_length=255, directory="albums/", extensions=['.jpg', '.jpeg', '.gif', '.png']) file_order = models.IntegerField(_('Индекс сортировки')) class Meta: verbose_name = _('фотографии') verbose_name_plural = _('фотографии') ordering = ['file_order'] def __str__(self): return 'Photo#{0}'.format(self.pk) <file_sep># Erwin Сайт нового ресторана Erwin для компании Soul Kitchen Девелоп версии проекта выкладываются из ветки `development` на: * [erwin.dev.dvhb.ru](http://erwin.dev.dvhb.ru) Production версия выкладывается из ветки `production` на: * [erwin.moscow](http://erwin.moscow) * [erwin.prod.dvhb.ru](http://erwin.prod.dvhb.ru) ## Установка Разворачивание локальной копии сайта: * Клонируем проект: git clone <EMAIL>:soul-kitchen/erwin.git erwin cd erwin * Разворачиваем виртуальное окружение (если вы не пользуетесь таковым, пропускаете этот шаг): virtualenv env . env/bin/activate * Модифицируем локальные настройки для разработки: cp [project/settings_local.example](project/settings_local.example) project/settings_local.py В файле `settings_local.py` можно настроить доступ к своей локальной БД и переопределить другие, необходимые для локальной разработки настройки. По умолчанию проект настроен на использование базы данных sqlite3, для некоторых случаев разработки этого достаточно, соответственно DATABASES можно не переопределять. * Устаналиваем зависимости и конвертируем базу: pip install -r project/requirements.txt ./manage.py migrate После выполнения команды `migrate` в базе будет создан администратор `<EMAIL>:123`. Авторизоваться под ним можно по адресу [http://localhost:8000/admin/](http://localhost:8000/admin/) ## Разработка Разработка каждой задачи происходит в специально созданой ветке для задачи ### Создание ветки с задачей fab gtask:ERW-999 ### Слияние разрабатываемой ветки в development fab dev merge:ERW-XXXX ### Слияние разрабатываемой ветки в production fab prod merge:ERW-XXXX ### Frontend Детальный порядок разработки frontend изложен в [static/README.md](static/README.md) <file_sep># coding: utf-8 """ Общие настройки приложений проекта. """ LOGIN_URL = 'admin:login' <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import re import django.core.validators import reservation.validators from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='ChangeStatus', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)), ('action', models.CharField(choices=[(1, 'Заявка'), (2, 'Редактирование'), (3, 'Бронь подтвержена'), (4, 'Бронь отклонена')], max_length=1)), ('cdate', models.DateTimeField(auto_now_add=True)), ], options={ 'ordering': ['-cdate'], }, bases=(models.Model,), ), migrations.CreateModel( name='Reservation', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)), ('request_date', models.DateTimeField(verbose_name='Дата заявки', auto_now_add=True)), ('change_date', models.DateTimeField(verbose_name='Дата изменения статуса', auto_now=True)), ('reservation_date', models.DateTimeField(verbose_name='Дата брони', validators=[reservation.validators.validate_future], db_index=True, help_text='На какую дату и время забронировать? (Мы работаем с 11:00 до 00:00)')), ('guest_count', models.PositiveSmallIntegerField(verbose_name='Гостей', help_text='Сколько будет человек?')), ('guest_name', models.CharField(verbose_name='Имя гостя', max_length=255)), ('phone', models.CharField(verbose_name='Телефон', validators=[django.core.validators.RegexValidator(re.compile('^(\\+?\\d{1,2})\\s?\\(?(\\d{3})\\)?\\s?(\\d{3})[\\-\\s]?(\\d{2})[\\-\\s]?(\\d{2})$', 32), message='Номер телефона должен быть в формате (84951234567 или +7 495 123-45-67)')], max_length=16)), ('comment', models.TextField(verbose_name='Коментарий', null=True, blank=True)), ('status', models.PositiveSmallIntegerField(verbose_name='Статус', choices=[(1, 'Заявка'), (3, 'Бронь подтверждена'), (4, 'Гость отклонил')], db_index=True, default=1)), ], options={ 'verbose_name': 'бронь', 'verbose_name_plural': 'брони', }, bases=(models.Model,), ), migrations.CreateModel( name='Table', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True, serialize=False)), ('name', models.CharField(verbose_name='Наименование столика', max_length=255)), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='reservation', name='table', field=models.ForeignKey(verbose_name='Столик', to='reservation.Table', null=True, blank=True, help_text='Выбор столика'), preserve_default=True, ), migrations.AddField( model_name='changestatus', name='reservation', field=models.ForeignKey(to='reservation.Reservation', related_name='statuses'), preserve_default=True, ), migrations.AddField( model_name='changestatus', name='user', field=models.ForeignKey(to=settings.AUTH_USER_MODEL, null=True, blank=True), preserve_default=True, ), migrations.CreateModel( name='ActualReservation', fields=[ ], options={ 'ordering': ['reservation_date'], 'verbose_name': 'бронь', 'proxy': True, 'verbose_name_plural': 'актуальные брони', }, bases=('reservation.reservation',), ), migrations.CreateModel( name='NotActualReservation', fields=[ ], options={ 'ordering': ['-reservation_date'], 'verbose_name': 'бронь', 'proxy': True, 'verbose_name_plural': 'предыдущие брони', }, bases=('reservation.reservation',), ), migrations.CreateModel( name='Request', fields=[ ], options={ 'ordering': ['reservation_date'], 'verbose_name': 'заявку', 'proxy': True, 'verbose_name_plural': 'заявки', }, bases=('reservation.reservation',), ), ] <file_sep> STATUS_REQUEST = 1 STATUS_APPROVE = 3 STATUS_REJECT = 4 STATUS_IMPOSSIBLE_TO_PHONE = 6 ACTION_CREATE = 1 ACTION_EDIT = 2 ACTION_APPROVE = 3 ACTION_REJECT = 4 ACTION_TABLE = 5 ACTION_IMPOSSIBLE_TO_PHONE = 6 SOURCE_SITE = 1 SOURCE_PHONE = 2 SOURCE_VERBALLY = 3 <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import mptt.fields import filebrowser.fields class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Menu', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)), ('name', models.CharField(verbose_name='Наименование', max_length=250)), ('menu_order', models.IntegerField(verbose_name='Индекс сортировки')), ('lft', models.PositiveIntegerField(editable=False, db_index=True)), ('rght', models.PositiveIntegerField(editable=False, db_index=True)), ('tree_id', models.PositiveIntegerField(editable=False, db_index=True)), ('level', models.PositiveIntegerField(editable=False, db_index=True)), ('parent', mptt.fields.TreeForeignKey(to='restaurant_menu.Menu', blank=True, null=True, verbose_name='Родитель', related_name='children')), ], options={ 'verbose_name': 'пункт меню', 'verbose_name_plural': 'меню', }, bases=(models.Model,), ), migrations.CreateModel( name='PdfFile', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, verbose_name='ID', serialize=False)), ('name', models.CharField(verbose_name='Наименование', max_length=250, blank=True)), ('pdf', filebrowser.fields.FileBrowseField(verbose_name='PDF-файл', max_length=255)), ('file_order', models.IntegerField(verbose_name='Индекс сортировки')), ('lft', models.PositiveIntegerField(editable=False, db_index=True)), ('rght', models.PositiveIntegerField(editable=False, db_index=True)), ('tree_id', models.PositiveIntegerField(editable=False, db_index=True)), ('level', models.PositiveIntegerField(editable=False, db_index=True)), ('parent', models.ForeignKey(to='restaurant_menu.Menu', verbose_name='Меню', related_name='pdffiles')), ], options={ 'verbose_name': 'PDF-файл', 'verbose_name_plural': 'PDF-файлы', }, bases=(models.Model,), ), ] <file_sep># coding: utf-8 import json from string import lowercase class BaseObjectType(object): """ Базовый класс для реалиации типов. """ def __init__(self, *args, **kwargs): if not kwargs: kwargs = dict(zip(lowercase, args)) self.kwargs = kwargs self.fields = sorted(kwargs.keys()) for k, v in kwargs.items(): setattr(self, k, v) @property def empty(self): return {k: None for k in self.fields} @classmethod def from_string(cls, json_string): data = json.loads(json_string) return cls(**data) @classmethod def from_list(cls, args): return cls(*args) def __eq__(self, other): if not isinstance(other, self.__class__): return False return (tuple(getattr(self, f) for f in self.fields) == tuple(getattr(other, f) for f in self.fields)) def __ne__(self, other): return not self == other def __str__(self): return json.dumps({f: getattr(self, f, None) for f in self.fields}) def __repr__(self): return '{0}({0})'.format( self.__class__.__name__, ', '.join('{}={}'.format(k, getattr(self, k, None)) for k in self.fields)) def decompress(self): return [getattr(self, k, None) for k in self.fields] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Contacts', fields=[ ('id', models.AutoField(auto_created=True, verbose_name='ID', serialize=False, primary_key=True)), ('phone1', models.CharField(verbose_name='Телефон-1', max_length=25)), ('phone2', models.CharField(verbose_name='Телефон-2', max_length=25, blank=True)), ('address', models.TextField(verbose_name='Адрес', blank=True)), ('email', models.EmailField(verbose_name='Адрес электронной почты', max_length=75, blank=True)), ], options={ 'verbose_name': 'Контакты', }, bases=(models.Model,), ), ] <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import reservation.validators import django.core.validators import re class Migration(migrations.Migration): dependencies = [ ('reservation', '0004_auto_20150409_1334'), ] operations = [ migrations.AlterField( model_name='reservation', name='guest_count', field=models.PositiveSmallIntegerField(verbose_name='Гостей', validators=[reservation.validators.validate_count], help_text='Сколько будет человек?'), preserve_default=True, ), migrations.AlterField( model_name='reservation', name='phone', field=models.CharField(validators=[django.core.validators.RegexValidator(re.compile('^(\\+?\\d{1,2})\\s?\\(?(\\d{3})\\)?\\s?(\\d{3})[\\-\\s]?(\\d{2})[\\-\\s]?(\\d{2})$', 32), message='Номер телефона должен быть в формате (84951234567 или 8 (495) 123-45-67)')], max_length=20, verbose_name='Телефон'), preserve_default=True, ), migrations.AlterField( model_name='reservation', name='reservation_date', field=models.DateTimeField(help_text='На какую дату и время забронировать?', verbose_name='Дата брони', blank=True, validators=[reservation.validators.validate_future, reservation.validators.validate_workhours], null=True, db_index=True), preserve_default=True, ), ] <file_sep># coding: utf-8 import json from django import forms from django.core.validators import RegexValidator from django.utils.safestring import mark_safe from django.utils.translation import ugettext as _ from core.fields.types import BaseObjectType class BaseMutliWidget(forms.MultiWidget): """ Base class for making ours multi values widgets. """ type_class = BaseObjectType def render(self, name, value, attrs=None): if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list of values, each corresponding to a widget # in self.widgets. if not isinstance(value, list): value = self.decompress(value) output = [] final_attrs = self.build_attrs(attrs) id_ = final_attrs.get('id', None) for i, widget in enumerate(self.widgets): try: widget_value = value[i] except IndexError: widget_value = None if id_: final_attrs = dict(final_attrs, id='%s_%s' % (id_, i)) output.append(self.render_widget( widget, name + '_%s' % i, widget_value, final_attrs)) return mark_safe(self.format_output(output)) def decompress(self, value): if value and isinstance(value, basestring): return self.type_class.from_string(value).decompress() elif isinstance(value, self.type_class): return value.decompress() return self.type_class.empty def render_widget(self, widget, name, value, attrs): if isinstance(widget, (forms.widgets.TextInput, forms.widgets.Select, forms.widgets.DateInput)): attrs = dict( attrs, **{'class': 'form-control'}) return widget.render(name, value, attrs) def format_output(self, rendered_widgets): raise NotImplemented <file_sep>from core.views import JSONListView from django.shortcuts import render from django.utils import timezone from . import models def event_lists(request): an = models.Event.objects\ .filter(edate__gte=timezone.now()) old = models.Event.objects.\ filter(edate__lt=timezone.now()) return render(request, 'event/list.jade', { 'announces': an, 'olds': old }) class AnnounceListView(JSONListView): model = models.Event fields = [ 'edate', 'title_before', 'title', 'title_after', 'content', 'announce_photo', ] def get_queryset(self): return self.model.objects \ .filter(edate__gte=timezone.now()) announce_json = AnnounceListView.as_view() class OldEventListView(JSONListView): model = models.Event fields = [ 'edate', 'title_before', 'title', 'title_after', 'announce', 'announce_photo', ] def get_queryset(self): return self.model.objects \ .filter(edate__lt=timezone.now()) old_event_json = OldEventListView.as_view() <file_sep>from django.contrib import admin from . import models @admin.register(models.Menu) class MenuModelAdmin(admin.ModelAdmin): list_display = ('name',) <file_sep># coding: utf-8 from __future__ import unicode_literals import json import re from django.core import serializers from django.conf import settings from django.contrib import messages from django.db import ProgrammingError, connection from django.http import HttpResponse from django.views.generic import View from django.views.generic.list import BaseListView from django.utils.encoding import force_text from django.utils.translation import ugettext_lazy as _ class AttrsToContext(object): """ Добавляет в контекст значение аттрибутов класса, начинающихся на `context__` """ page_title = None def get_context_data(self, *args, **kwargs): context = super(AttrsToContext, self).get_context_data(*args, **kwargs) prefix = 'context__' for a in (a for a in dir(self) if a.startswith(prefix)): context[a.replace(prefix, '')] = getattr(self, a) return context class MessagesFormMixin(object): """ Миксин для добавления сообщений успеха / ошибки с использованием стандартного `django.contrib.messages` при обработке форм через `FormView`. """ success_message = None error_message = None def form_valid(self, *args, **kwargs): if self.success_message: messages.success(self.request, self.success_message) return super(MessagesFormMixin, self).form_valid(*args, **kwargs) def form_invalid(self, *args, **kwargs): if self.error_message: messages.error(self.request, self.error_message) return super(MessagesFormMixin, self).form_invalid(*args, **kwargs) class JSONResponse(HttpResponse): """ Response сериализующий python-объект в json """ def __init__(self, data=None, status=200, message=None, **kwargs): if not data: data = {} if message: data['message'] = force_text(message) data['status'] = status data.update(kwargs) data = json.dumps(data, ensure_ascii=False) super(JSONResponse, self).__init__(data, status=status, content_type="application/json; " "charset=utf-8") class SuggestBaseView(View): """ Базовый класс для подсказок """ re_query = re.compile(r'[а-яёй\-\s\.]+', re.IGNORECASE | re.UNICODE) error_programming = '' class QueryError(RuntimeError): def __init__(self, **kwargs): self.kwargs = kwargs def post(self, request): try: return self.search(self.clean(request.POST)) except self.QueryError as e: return self.render(**e.kwargs) def clean(self, query_dict): query = query_dict.get('query') query_dict._mutable = True query = self.re_query.match(query) if not query: raise self.QueryError(status=404, message=_('В запросе должны быть только русские буквы')) query_dict['query'] = query.group(0) return query_dict def get_result(self, query_dict): raise NotImplementedError() def fetchall(self, sql, params=[]): with connection.cursor() as cur: cur.execute(sql, params) return list(cur.fetchall()) def search(self, query_dict): try: result = self.get_result(query_dict) except ProgrammingError as e: if settings.DEBUG: msg = str(e.message) else: msg = str(self.error_programming) return self.render(status=500, message=msg) if not result: return self.render(status=404, message=_('Ничего не найдено')) return self.render(result=result) def render(self, **kwargs): return JSONResponse(**kwargs) class JSONListView(BaseListView): paginate_by = 20 fields = [] def render_to_response(self, context, **response_kwargs): return HttpResponse( serializers.serialize('json', context['object_list'], fields=self.fields), content_type='application/json' ) <file_sep># coding: utf8 import csv from datetime import datetime from itertools import chain from django.shortcuts import redirect, render_to_response from django.utils import six from django.http import StreamingHttpResponse from django.views.generic import DetailView, CreateView, UpdateView, View, TemplateView, ListView from django.views.generic.dates import DateMixin from django.views.generic.detail import SingleObjectMixin from pyjade import register_filter import sass from . import consts from . import models @register_filter('scss') def scss_filter(x, y): if isinstance(x, six.text_type): x = x.encode('utf-8') return '<style>%s</style>' % sass.compile_string(x) class ReservationListView(DateMixin, ListView): model = models.Reservation template_name = 'reservation/notactual_list.jade' date_field = 'reservation_date' paginate_by = 20 def get(self, request, *args, **kwargs): filter_date = request.GET.get(self.date_field) is_csv = request.GET.get('csv') try: filter_date = datetime.utcfromtimestamp(int(filter_date)) lookups = self._make_single_date_lookup(filter_date) self.queryset = self.model.objects.filter(**lookups) self.paginate_by = None except: pass if is_csv: if not self.queryset: self.queryset = self.model.objects.select_related('table').extra( select={'sort_field': 'COALESCE(reservation_date, NOW())'} ).order_by('sort_field') return self.export() return super(ReservationListView, self).get(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(ReservationListView, self).get_context_data(**kwargs) context['date_filter'] = self.request.GET.get(self.date_field) return context def export(self): class Echo: def write(self, v): return v.decode('utf8').encode('cp1251') pseudo_buffer = Echo() filter_date = self.request.GET.get(self.date_field) writer = csv.writer(pseudo_buffer, delimiter=';') head = (writer.writerow(tr) for tr in [ [ "Дата заявки", "Дата брони", "Имя гостя", "Гостей", "Телефон", "Столик", "Статус", ]]) body = (writer.writerow([ obj.request_date.strftime("%d.%m.%y %H:%M"), obj.reservation_date and obj.reservation_date.strftime("%d.%m.%y %H:%M") or '', obj.guest_name.encode('utf8'), obj.guest_count, obj.phone, (obj.table and obj.table.name or '').encode('utf8'), obj.get_status_display().encode('utf8'), ]) for obj in self.get_queryset()) response = StreamingHttpResponse(chain(head, body), content_type="text/csv") response['Content-Disposition'] = ('attachment; filename="archive{}.csv"' ''.format(filter_date or '')) return response class RequestView(ReservationListView): model = models.Request template_name = 'reservation/request_list.jade' def get_context_data(self, **kwargs): context = super(RequestView, self).get_context_data(**kwargs) context['table_list'] = models.Table.objects.all() context['requests'] = 'active' context['consts'] = consts context['printable'] = True context['btn_export'] = True context['btn_filter'] = True return context class ActualView(ReservationListView): model = models.ActualReservation template_name = 'reservation/actual_list.jade' def get_context_data(self, **kwargs): context = super(ActualView, self).get_context_data(**kwargs) context['actuals'] = 'active' context['printable'] = True context['btn_export'] = True context['btn_filter'] = True return context class NotActualView(ReservationListView): model = models.NotActualReservation template_name = 'reservation/notactual_list.jade' def get_context_data(self, **kwargs): context = super(NotActualView, self).get_context_data(**kwargs) context['notactuals'] = 'active' context['printable'] = True context['btn_export'] = True context['btn_filter'] = True return context class ReservationDetailView(DetailView): model = models.Reservation queryset = models.Reservation.objects.select_related('table') template_name = 'reservation/reservation_detail.jade' def get_context_data(self, **kwargs): context = super(ReservationDetailView, self).get_context_data(**kwargs) context['statuses'] = models.ChangeStatus.objects \ .filter(reservation_id=self.object.pk).select_related('user') context['printable'] = True return context class ReservationAddView(CreateView): model = models.Reservation def get_form_class(self): user = self.request.user if not user.has_perms('add_reservation'): self.fields = ['reservation_date', 'guest_count', 'guest_name', 'phone', 'comment'] return super(ReservationAddView, self).get_form_class() def form_valid(self, form): self.object = form.save(commit=False) user = self.request.user if not user.has_perms('add_reservation'): user = None self.object.status = consts.STATUS_REQUEST self.object.source = consts.SOURCE_SITE else: self.object.user = user self.object.status = consts.STATUS_APPROVE self.object.save() models.ChangeStatus.objects.create( user=user, reservation=self.object, action=consts.ACTION_CREATE ) if user: models.ChangeStatus.objects.create( user=user, reservation=self.object, action=consts.ACTION_APPROVE ) return redirect('reservation:detail', pk=self.object.pk) return render_to_response('reservation/site_thanks.jade', { 'reservation': self.object }) def get_template_names(self): user = self.request.user if user.has_perms('add_reservation'): return ['reservation/reservation_form.jade'] return ['reservation/site_form.jade'] class ReservationUpdateView(UpdateView): model = models.Reservation template_name = 'reservation/reservation_edit.jade' fields = ( 'guest_name', 'guest_count', 'reservation_date', 'phone', 'table', 'source', 'comment', ) def form_valid(self, form): self.object = form.save() models.ChangeStatus.objects.create( user=self.request.user, reservation=self.object, action=consts.ACTION_EDIT ) return redirect('reservation:detail', pk=self.object.pk) class ReservationActionView(SingleObjectMixin, View): model = models.Reservation def get(self, request, *args, **kwargs): self.object = self.get_object() next_url = request.GET.get('next', 'reservation:detail') self.object.status = self.status self.object.save(update_fields=['status', 'change_date']) models.ChangeStatus.objects.create( user=self.request.user, reservation=self.object, action=self.action ) return redirect(next_url, pk=self.object.pk) class ReservationApproveView(ReservationActionView): status = consts.STATUS_APPROVE action = consts.ACTION_APPROVE class ReservationRejectView(ReservationActionView): status = consts.STATUS_REJECT action = consts.ACTION_REJECT def get(self, request, *args, **kwargs): response = super(ReservationRejectView, self).get(request, *args, **kwargs) self.object.reservation_date = self.object.change_date self.object.save(update_fields=['reservation_date']) return response class ReservationImpossibleToPhoneView(ReservationRejectView): status = consts.STATUS_IMPOSSIBLE_TO_PHONE action = consts.ACTION_IMPOSSIBLE_TO_PHONE class ReservationTableListView(TemplateView): template_name = 'reservation/table_menu.jade' def get_context_data(self, **kwargs): context = super(ReservationTableListView, self).get_context_data(**kwargs) context['table_list'] = models.Table.objects.all() context['object'] = {'pk': kwargs.get('pk')} return context class ReservationTableView(SingleObjectMixin, View): model = models.Reservation def get(self, request, pk, table_pk, *args, **kwargs): self.object = self.get_object() self.object.table_id = table_pk self.object.save(update_fields=['table_id', 'change_date']) models.ChangeStatus.objects.create( user=self.request.user, reservation=self.object, action=consts.ACTION_TABLE ) return redirect('reservation:requests') <file_sep># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.utils import six def make_zone(apps, schema_editor): Zone = apps.get_model("reservation", "Zone") Zone.objects.create(pk=1, name="Системная") Zone.objects.create(pk=2, name="Основная") def make_table(apps, schema_editor): Table = apps.get_model("reservation", "Table") defaults={ 'name': "Ближайший", 'zone_id': 1, 'table_order': 0 } obj, created = Table.objects.get_or_create(pk=1, defaults=defaults) if not created: for k,v in six.iteritems(defaults): setattr(obj, k, v) obj.save() class Migration(migrations.Migration): dependencies = [ ('reservation', '0004_auto_20150409_1334'), ] operations = [ migrations.CreateModel( name='Zone', fields=[ ('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)), ('name', models.CharField(verbose_name='Наименование зоны', max_length=255)), ], options={ 'verbose_name_plural': 'зоны', 'verbose_name': 'зону', }, bases=(models.Model,), ), migrations.RunPython(make_zone), migrations.AlterModelOptions( name='table', options={'verbose_name_plural': 'столики', 'verbose_name': 'столик', 'ordering': ['zone', 'table_order']}, ), migrations.AddField( model_name='table', name='description', field=models.CharField(verbose_name='Примечание', blank=True, max_length=255), preserve_default=True, ), migrations.AddField( model_name='table', name='table_order', field=models.IntegerField(default=0, verbose_name='Индекс сортировки'), preserve_default=False, ), migrations.AddField( model_name='table', name='zone', field=models.ForeignKey(default=2, to='reservation.Zone', verbose_name='Зона'), preserve_default=False, ), migrations.RunPython(make_table), ] <file_sep># coding: utf-8 from __future__ import unicode_literals from django.db import models from django.utils.six import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ from filebrowser.fields import FileBrowseField @python_2_unicode_compatible class Menu(models.Model): name = models.CharField(_('Наименование'), max_length=250) photo = FileBrowseField(_('Графический файл'), max_length=255, directory="menu/", extensions=['.jpg', '.jpeg', '.gif', '.png']) pdf = FileBrowseField(_('PDF-файл'), max_length=255, directory="menu/", extensions=[".pdf"]) menu_order = models.IntegerField(_('Индекс сортировки')) class Meta: verbose_name = _('пункт меню') verbose_name_plural = _('меню') ordering = ['menu_order'] def __str__(self): return self.name <file_sep># coding=utf-8 from __future__ import unicode_literals from functools import partial import re from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.utils import timezone from django.utils.translation.trans_null import gettext_lazy as _ re_phone = re.compile(r'^(\+?\d{1,2})\s?' r'\(?(\d{3})\)?\s?' r'(\d{3})[\-\s]?' r'(\d{2})[\-\s]?' r'(\d{2})$') phone_validator = RegexValidator( re_phone, message=_('Номер телефона должен быть в формате' ' (84951234567 или 8 (495) 123-45-67)') ) def validate_future(vdate): if vdate <= timezone.now(): raise ValidationError( _('Дата {0:%d.%m.%Y %H:%M} уже прошла' ).format(vdate)) def validate_workhours(vdate): if vdate.hour < 12: raise ValidationError( _('Время {0:%H:%M} не соответствует режиму работы с 12:00 до 00:00' ).format(vdate)) def validate_count(count): if count > 1000: raise ValidationError(_('Количество гостей слишком велико')) <file_sep># coding: utf-8 from django.http import HttpResponseRedirect from django.shortcuts import redirect from django.contrib.auth import logout from subdomains.utils import reverse from rest_framework.status import HTTP_403_FORBIDDEN class MobileRedirectMiddleware(object): def process_request(self, request): request.device = None if 'HTTP_USER_AGENT' not in request.META: return user_agent = request.META['HTTP_USER_AGENT'] or '' devices = ('iPhone', 'Windows Phone', 'Android') for device in devices: if device in user_agent: request.device = device.replace(' ', '') break <file_sep>$(function(){ $('[flexslider_nav]').flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, itemWidth: 150, itemMargin: 1, asNavFor: '[flexslider]', minItems: 4, maxItems: 8 }); $('[flexslider]').flexslider({ animation: "slide", controlNav: false, animationLoop: false, slideshow: false, sync: "[flexslider_nav]" }); });<file_sep># coding: utf-8 """ Logging configuration part. """ import os LOG_LEVEL = "ERROR" LOG_DIR = os.path.join('/', 'l', 'erwin') LOG_URL = '/logs/' LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue' }, }, 'formatters': { 'verbose': { 'format': '[%(asctime)s] %(levelname)s: %(name)s: %(message)s' }, }, 'handlers': { 'console': { 'level': LOG_LEVEL, 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'console_debug': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, 'flight_recorder': { 'level': 'INFO', 'class': 'logging.handlers.WatchedFileHandler', 'formatter': 'verbose', 'filename': os.path.join(LOG_DIR, 'fadm_ts.log') }, 'sentry': { 'level': 'ERROR', 'class': 'raven.contrib.django.handlers.SentryHandler', }, }, 'loggers': { '': { 'handlers': ['flight_recorder', 'console', 'sentry'], 'level': LOG_LEVEL, 'propagate': True, }, 'core.api.request': { 'handlers': ['console_debug'], 'propagate': True, 'filters': ['require_debug_true'], 'level': 'INFO', }, 'core.api.response': { 'handlers': ['console_debug'], 'propagate': True, 'filters': ['require_debug_true'], 'level': 'INFO', }, 'core.loader': { 'handlers': ['console_debug'], 'propagate': True, 'filters': ['require_debug_true'], 'level': 'INFO', }, 'points.signals': { 'handlers': ['console_debug'], 'propagate': True, 'filters': ['require_debug_true'], 'level': 'INFO', }, 'django.request': { 'handlers': ['flight_recorder', 'console'], 'level': LOG_LEVEL, 'propagate': True, }, } } <file_sep># coding: utf-8 from __future__ import unicode_literals from __future__ import absolute_import from django import template from django.utils import six from reservation.validators import re_phone register = template.Library() @register.filter def phone(value, format='%s (%s) %s-%s-%s'): if not isinstance(value, six.text_type): return '' m = re_phone.match(value) if m: return format % m.groups() return value <file_sep># coding: utf-8 import unittest import time import re import sys from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import NoAlertPresentException sys.path.append('./core') import base class TestCase6(base.TestCase): """ Заполнены только поля "Ваше имя", "Сколько будет человек", "Ваш контактный\ номер" """ def test_6(self): driver = self.driver driver.get('http://erwin:404@erwin.dev.dvhb.ru/') driver.find_element_by_xpath( "//a[contains(@href, '/reservation/add/')]").click() driver.find_element_by_id("id_guest_name").clear() driver.find_element_by_id("id_guest_name").send_keys("test") driver.find_element_by_id("id_guest_count").clear() driver.find_element_by_id("id_guest_count").send_keys("2") driver.find_element_by_id("id_phone").clear() driver.find_element_by_id("id_phone").send_keys("8(111)111-11-11") driver.find_element_by_id("btn_reserv").click() try: self.assertEqual(u"Мы приняли вашу заявку на бронирование \ столика:\ntest,\n2 человек,\n8 (811) 111-11-11", driver.find_element_by_css_selector("p").text) except AssertionError as e: self.verificationErrors.append(str(e)) if __name__ == "__main__": print __file__ print u"Заполнены только поля \"Ваше имя\", \"Сколько будет человек\",\ \"Ваш контактный номер\"" unittest.main() <file_sep># coding: utf-8 from django.db import models from django.forms import ValidationError from core.fields.types import BaseObjectType from core.utils import get_filetype class BaseTypedField(models.Field): """ Базовый класс поля для сложных полей. """ __metaclass__ = models.SubfieldBase # Класс, реализующий логику объекта type_class = BaseObjectType # Класс поля формы, для отображения и валидации в ModelForms form_class = None def __init__(self, *args, **kwargs): kwargs.setdefault('default', self.type_class()) super(BaseTypedField, self).__init__(*args, **kwargs) def to_python(self, value): if isinstance(value, self.type_class): return value return self.type_class.from_string(value) if value else self.default def get_prep_value(self, value): return str(value or self.default) def deconstruct(self): name, path, args, kwargs = super(BaseTypedField, self).deconstruct() del kwargs['default'] return name, path, args, kwargs def formfield(self, **kwargs): kwargs['form_class'] = self.form_class return super(BaseTypedField, self).formfield(**kwargs) def get_internal_type(self): return 'TextField' def check_filetype(filetypes): """ Валидатор на проверку соовтветствия расширения файла Параметры: - filetypes: массив допустимых для загрузки расширений файлов """ def _validator(f): filetype = get_filetype(f.file.name) if filetype not in filetypes: raise ValidationError( u'Недопустимое расширение файла: {}'.format(filetype)) return _validator class FileField(models.FileField): """ Поле с проверкой расширения файла. """ def __init__(self, *args, **kwargs): allowed = kwargs.pop('allowed', None) super(FileField, self).__init__(*args, **kwargs) if allowed: self.validators.append(check_filetype(allowed)) <file_sep>from django.contrib import admin from solo.admin import SingletonModelAdmin from .models import Contacts admin.site.register(Contacts, SingletonModelAdmin) <file_sep># coding: utf-8 from django.conf import settings def is_production(request): return {'IS_PRODUCTION': settings.IS_PRODUCTION} def some_settings(request): return {'VK_APPID': getattr(settings, 'VK_APPID', None)} <file_sep># coding=utf-8 from __future__ import unicode_literals from django.apps import AppConfig import os class MenuConfig(AppConfig): name = 'restaurant_menu' def ready(self): from django.conf import settings try: os.makedirs( os.path.join( settings.MEDIA_ROOT, 'uploads', 'menu' ) ) except OSError: pass <file_sep># coding: utf-8 from functools import partial from django.conf.urls import patterns, include, url from django.conf.urls.static import static from django.contrib import admin from django.contrib.auth.decorators import login_required from django.views import defaults from django.views.generic import TemplateView from django.conf import settings from filebrowser.sites import site urlpatterns = patterns( '', url(r'^reservation/', include('reservation.urls', namespace='reservation')), url(r'^contacts/', TemplateView.as_view(template_name='contacts.jade'), name='contacts'), url(r'^old/browser/', TemplateView.as_view(template_name='old_browser.jade'), name='old_browser'), url(r'^tour3d/', TemplateView.as_view(template_name='3d.jade'), name='tour3d'), url(r'^event/', include('event.urls', namespace='event')), url(r'^galery/', include('photogalery.urls', namespace='photogalery')), url(r'^menu/', include('restaurant_menu.urls', namespace='restaurant_menu')), url(r'^$', 'first_page.views.main_list', name='main_site'), url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/filebrowser/', include(site.urls)), url(r'^admin/', include(admin.site.urls)), ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) handler404 = partial(defaults.page_not_found, template_name='404.jade') handler500 = partial(defaults.server_error, template_name='500.jade') <file_sep># coding=utf-8 from __future__ import unicode_literals from django.conf import settings from django.db import models from django.utils import timezone from django.utils.six import python_2_unicode_compatible from django.utils.translation.trans_null import gettext_lazy as _ from core.utils import NULLABLE from .managers import ActualReservationManager, NotActualReservationManager, ActualRequestManager from .validators import validate_future, validate_workhours, phone_validator, validate_count from . import consts @python_2_unicode_compatible class Zone(models.Model): name = models.CharField(_('Наименование зоны'), max_length=255) def __str__(self): return self.name class Meta: verbose_name_plural = _('зоны') verbose_name = _('зону') @python_2_unicode_compatible class Table(models.Model): name = models.CharField(_('Наименование столика'), max_length=255) description = models.CharField(_('Примечание'), max_length=255, blank=True) zone = models.ForeignKey(Zone, verbose_name=_('Зона')) table_order = models.IntegerField(_('Индекс сортировки')) def __str__(self): return self.name @staticmethod def autocomplete_search_fields(): return "name__icontains", class Meta: verbose_name_plural = _('столики') verbose_name = _('столик') ordering = ['zone', 'table_order'] class AuthorMixin(object): def get_user_display(self): if not self.user_id: return 'Online' elif not self.user.last_name: return self.user.username return '{0.last_name} {0.first_name}'.format(self.user) @python_2_unicode_compatible class Reservation(AuthorMixin, models.Model): """ Бронь """ CHOICE_STATUS = ( (consts.STATUS_REQUEST, _('Заявка')), (consts.STATUS_APPROVE, _('Бронь подтверждена')), (consts.STATUS_REJECT, _('Гость отказался')), (consts.STATUS_IMPOSSIBLE_TO_PHONE, _('Невозможно связаться')), ) CHOICE_SOURCE = ( (consts.SOURCE_SITE, _('Сайт')), (consts.SOURCE_PHONE, _('Звонок')), (consts.SOURCE_VERBALLY, _('Устно')), ) request_date = models.DateTimeField(_('Дата заявки'), auto_now_add=True) change_date = models.DateTimeField(_('Дата изменения статуса'), auto_now=True) reservation_date = models.DateTimeField( _('Дата брони'), help_text=_('На какую дату и время забронировать?'), db_index=True, validators=[validate_future, validate_workhours], **NULLABLE ) guest_count = models.PositiveSmallIntegerField( _('Гостей'), validators=[validate_count], help_text=_('Сколько будет человек?')) guest_name = models.CharField(_('Имя гостя'), max_length=255) phone = models.CharField(_('Телефон'), max_length=20, validators=[phone_validator]) comment = models.TextField(_('Коментарий'), **NULLABLE) table = models.ForeignKey(Table, verbose_name=_('Столик'), help_text=_('Выбор столика'), **NULLABLE) status = models.PositiveSmallIntegerField( _('Статус'), choices=CHOICE_STATUS, default=consts.STATUS_REQUEST, db_index=True, blank=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, verbose_name=_('Автор'), **NULLABLE) source = models.PositiveSmallIntegerField( _('Источник'), choices=CHOICE_SOURCE, default=consts.SOURCE_SITE, blank=True ) def __str__(self): tz = timezone.get_current_timezone() self.request_date = self.request_date.astimezone(tz) return _('Бронь от {0.request_date:%d.%m.%Y %H:%M} на имя {0.guest_name}').format(self) class Meta: verbose_name_plural = _('брони') verbose_name = _('бронь') class ActualReservation(Reservation): objects = ActualReservationManager() class Meta: proxy = True ordering = ['reservation_date'] verbose_name_plural = _('актуальные брони') verbose_name = _('бронь') class NotActualReservation(Reservation): objects = NotActualReservationManager() class Meta: proxy = True ordering = ['-reservation_date'] verbose_name_plural = _('предыдущие брони') verbose_name = _('бронь') @python_2_unicode_compatible class Request(Reservation): """ Заявка """ objects = ActualRequestManager() class Meta: proxy = True ordering = ['reservation_date'] verbose_name_plural = _('заявки') verbose_name = _('заявку') def __str__(self): tz = timezone.get_current_timezone() self.request_date = self.request_date.astimezone(tz) return _('Заявка от {0.request_date:%d.%m.%Y %H:%M} на имя {0.guest_name}').format(self) def approve(self, table): self.status = consts.STATUS_APPROVE self.table = table if isinstance(table, Table) or table is None: self.table = table elif isinstance(table, int): self.table_id = table else: raise Table.DoesNotExist() self.save(update_fields=['table_id', 'status', 'change_date']) def reject(self): self.status = consts.STATUS_REJECT self.table = None self.save(update_fields=['table_id', 'status', 'change_date']) class ChangeStatus(AuthorMixin, models.Model): CHOICE_ACTIONS = ( (consts.ACTION_CREATE, _('Заявка')), (consts.ACTION_EDIT, _('Редактирование')), (consts.ACTION_APPROVE, _('Бронь подтвержена')), (consts.ACTION_REJECT, _('Бронь отклонена')), (consts.ACTION_IMPOSSIBLE_TO_PHONE, _('Невозможно связаться')), (consts.ACTION_TABLE, _('Выбран столик')), ) user = models.ForeignKey(getattr(settings, 'AUTH_USER_MODEL'), **NULLABLE) reservation = models.ForeignKey(Reservation, related_name='statuses') action = models.PositiveSmallIntegerField(choices=CHOICE_ACTIONS, default=consts.ACTION_CREATE) cdate = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-cdate']
7773bc89edd3260edf22b38e50d94bdab1022b84
[ "HTML", "JavaScript", "Markdown", "Python", "Text", "Shell" ]
89
Python
mitrey/erwin
3ec37c1fe31a1c8b8dd3dafc5662920dbfc64f61
a7415cba5f1eb66a29b0bbc8891fbd1b7d1a6241