branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep># IABSample In-app Billing Sample for Android app <file_sep>package com.nfujii.iabsample; import android.app.PendingIntent; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentSender; import android.content.ServiceConnection; import android.os.IBinder; import android.os.RemoteException; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.android.vending.billing.IInAppBillingService; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.Arrays; /** * http://developer.android.com/google/play/billing/billing_integrate.html */ public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); private static final int BILLING_RESPONSE_RESULT_OK = 0; private String mPremium1MonthPrice = ""; private String mPremium1MonthTitle = ""; private TextView mPremium1MonthPriceView; private TextView mPremium1MonthTitleView; private Button mBuyButton; private View.OnClickListener mBuyButtonListener = new View.OnClickListener() { @Override public void onClick(View v) { buy(PRODUCT_ID_PREMIUM_1MONTH); } }; private static final String PRODUCT_ID_PREMIUM_1MONTH = "premium_1month"; private static final String[] SKU_LIST = { PRODUCT_ID_PREMIUM_1MONTH, }; private IInAppBillingService mService; private ServiceConnection mServiceConn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { mService = null; } @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = IInAppBillingService.Stub.asInterface(service); new Thread(new Runnable() { @Override public void run() { } }); try { ArrayList<String> skuList = new ArrayList<>(Arrays.asList(SKU_LIST)); Bundle querySkus = new Bundle(); querySkus.putStringArrayList("ITEM_ID_LIST", skuList); int apiVersion = 3; String type = "subs"; // 購読の場合は"subs", 消費アイテムは"inapp" Bundle skuDetails = mService.getSkuDetails(apiVersion, getPackageName(), type, querySkus); int response = skuDetails.getInt("RESPONSE_CODE"); if (response == BILLING_RESPONSE_RESULT_OK) { ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); if (responseList != null) { for (String thisResponse : responseList) { JSONObject object = new JSONObject(thisResponse); String sku = object.getString("productId"); if (sku.equals(PRODUCT_ID_PREMIUM_1MONTH)) { String description = object.getString("description"); mPremium1MonthPrice = object.getString("price"); mPremium1MonthTitle = object.getString("title"); mPremium1MonthPriceView.setText(mPremium1MonthPrice); mPremium1MonthTitleView.setText(mPremium1MonthTitle); mBuyButton.setEnabled(true); } } } } } catch (RemoteException | JSONException e) { Log.e(TAG, "error", e); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(com.nfujii.iabsample.R.layout.activity_main); mBuyButton = (Button)findViewById(com.nfujii.iabsample.R.id.buy_button); mBuyButton.setOnClickListener(mBuyButtonListener); mBuyButton.setEnabled(false); mPremium1MonthPriceView = (TextView)findViewById(com.nfujii.iabsample.R.id.premium_price_text); mPremium1MonthTitleView = (TextView)findViewById(com.nfujii.iabsample.R.id.premium_title_text); Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); // To protect the security of billing transactions, always make sure to explicitly set the intent's target package name to com.android.vending, using setPackage() serviceIntent.setPackage("com.android.vending"); getApplicationContext().bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE); } /** * Remember to unbind from the In-app Billing service when you are done with your Activity. * If you don’t unbind, the open service connection could cause your device’s performance to degrade. */ @Override public void onDestroy() { super.onDestroy(); if (mService != null) { unbindService(mServiceConn); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(com.nfujii.iabsample.R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == com.nfujii.iabsample.R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onActivityResult (int requestCode, int resultCode, Intent data) { if (requestCode == 1001) { if (resultCode == RESULT_OK) { String json = data.getStringExtra("INAPP_PURCHASE_DATA"); Log.d(TAG, json); } } } private void buy(String sku) { try { Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "subs", ""); int response = buyIntentBundle.getInt("RESPONSE_CODE"); if (response == BILLING_RESPONSE_RESULT_OK) { } else { Log.e(TAG, "購入に失敗"); } PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); if (pendingIntent != null) { // 購入トランザクションを終了するために以下を呼ぶ // 1001はリクエストコード startIntentSenderForResult(pendingIntent.getIntentSender(), 1001, new Intent(), 0, 0, 0); // onActivityResultが呼ばれる } } catch (RemoteException | IntentSender.SendIntentException e) { Log.d(TAG, "error", e); } } }
9ee6a7174329bf0d28593f2c4de927e370662076
[ "Markdown", "Java" ]
2
Markdown
naokinkfj/IABSample
b9c9364f96b13ea254e319328f2fc7d972438edc
9285150cea84741d5d9e5199a9ee0edb66f0b782
refs/heads/master
<file_sep>// // BreakingBad.swift // Breaking_bad // // Created by <NAME> on 28/6/20. // Copyright © 2020 <NAME>. All rights reserved. // import Foundation struct Character: Codable { let name: String let char_id: Int let nickname: String let img: String } struct CharacterQuotes: Codable { let quote: String } <file_sep>// // BBViewController.swift // Breaking_bad // // Created by <NAME> on 29/6/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class BBViewController: UIViewController { //create IBOutlets and link it up to the labels in view controller var url: String! @IBOutlet var nameLabel: UILabel! @IBOutlet var nicknameLabel: UILabel! @IBOutlet var char_idLabel: UILabel! @IBOutlet var characterImage: UIImageView! @IBOutlet var characterquote: UITextView! var character: Character! override func viewDidLoad() { super.viewDidLoad() nameLabel.text = character.name nicknameLabel.text = "Nickname: " + character.nickname char_idLabel.text = String(format: "#%03d",character.char_id) characterquote.text = "" loadImage() loadQuotes() } func loadImage() { do { let imageData = try Data(contentsOf: URL(string: character.img)!) self.characterImage.image = UIImage(data: imageData) } catch { print(error) } } func loadQuotes() { let name_url = character.name.replacingOccurrences(of: " ", with: "+") let url = "https://www.breakingbadapi.com/api/quote/random?author=" + name_url URLSession.shared.dataTask(with: URL(string: url)!) { (data, response, error) in guard let data = data else { return } do { let quotes = try JSONDecoder().decode([CharacterQuotes].self, from: data) DispatchQueue.main.async { for q in quotes { self.characterquote.text = q.quote } } } catch let error { print(error) } }.resume() //self.characterquote.text = url } } <file_sep># Breaking-Bad-iOS-app A simple breaking bad iOS app Information of each character is retrieved from the [Breaking Bad API](https://breakingbadapi.com) - [GitHub](https://github.com/timbiles/Breaking-Bad--API). Users can search for character's name in the search bar, information of their name, nickname and their corresponding random memorable quote is generated everytime a character is selected. [App preview here](https://youtu.be/mEzd_8z8BNs) <file_sep>// // ViewController.swift // Breaking_bad // // Created by <NAME> on 28/6/20. // Copyright © 2020 <NAME>. All rights reserved. // import UIKit class ViewController: UITableViewController, UISearchBarDelegate { var characters: [Character] = [] @IBOutlet var searchcharacter: UISearchBar! var filteredCharacters = [Character]() override func viewDidLoad() { tableView.dataSource = self super.viewDidLoad() /*let searchBar:UISearchBar = UISearchBar() searchcharacter.searchBarStyle = UISearchBar.Style.prominent searchcharacter.placeholder = " Search..." searchcharacter.sizeToFit() searchcharacter.isTranslucent = false searchcharacter.backgroundImage = UIImage()*/ searchcharacter.delegate = self //delegate searchbar to viewDidLoad //filteredCharacters = characters guard let url = URL(string: "https://www.breakingbadapi.com/api/characters") else { return } URLSession.shared.dataTask(with: url){(data, response, error) in guard let data = data else { return } do { let characterList = try JSONDecoder().decode([Character].self, from: data) self.characters = characterList self.filteredCharacters = self.characters DispatchQueue.main.async { self.tableView.reloadData() } } catch let error { print("\(error)") } }.resume() } override func numberOfSections(in tableView: UITableView) -> Int { return 1 //1 section } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { /*if searchcharacter.text!.isEmpty { return characters.count }*/ return filteredCharacters.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CharacterCell", for: indexPath) cell.textLabel?.text = filteredCharacters[indexPath.row].name //?->if nil, dont crash, carry on return cell } //segue to transition between view controllers override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "CharacterSegue", //when u click on a row it should link to next page->PokemonViewController let destination = segue.destination as? BBViewController , //index of pokemon will correspond to the row number let index = tableView.indexPathForSelectedRow?.row { destination.character = filteredCharacters[index] } /*if segue.identifier == "CharacterSegue" { //destination is of type BBViewController if let destination = segue.destination as? BBViewController { //index into list, getting item that corresponds to row that user, selected, passing it to view controller destination.character = filteredCharacters[tableView.indexPathForSelectedRow!.row] } }*/ } func searchBar(_ searchBar: UISearchBar, textDidChange textSearched: String) { filteredCharacters = textSearched.isEmpty ? characters : characters.filter{(characters: Character) -> Bool in return characters.name.lowercased().contains(textSearched.lowercased()) } tableView.reloadData() } }
c99c09a0ca7083bb4967d2fe1f9d50cfc1e65dc8
[ "Swift", "Markdown" ]
4
Swift
pakhuiying/Breaking-Bad-iOS-app
400c6df2cacbc70f9426efcdf4b83d8246d8a62c
136d383129a1bc5e0ed23244c484bebc6e4cb26a
refs/heads/master
<file_sep>class Api::V1::TagsController < ApplicationController def index tags = Tag.all render json: tags end def create tag = Tag.create(tag_params) render json: tag end private def tag_params params.require(:tag).permit(:title, :hostname, :frame, :order, :remoteip) end end
2d4bbfbabb8b23225a910fd83945937d6a2ada44
[ "Ruby" ]
1
Ruby
chrnobyl/sk-api
abc8b8b203611d812c993324f9fcae0a66c7df30
cce4892f85c9588aa54c64f4f5a66fc63228ada8
refs/heads/master
<file_sep>/*! * Servomotor sprinkler. * @author <NAME> * @version 0.1 */ #include <SimpleServo.h> // Input & Output pins. const int servoPinId = 0; const int statePinId = 1; const int sensorPinId = 2; // Determines whether or not the servomotor was activated. bool activated = false; // Servomotor controller. SimpleServo servo; /** * Loader setup. */ void setup() { servo.attach(servoPinId); pinMode(statePinId, OUTPUT); pinMode(sensorPinId, INPUT); } /** * Loader loop. */ void loop() { if (!isActive()) { activated = false; moveFastTo(0); } else if (!activated) { activated = true; moveSmoothTo(90, 5); moveFastTo(0); } delay(100); } /** * Determines whether or not the infra-red sensor is obstructed. * @return Returns true when the sensor is obstructed, false otherwise. */ bool isActive() { const int state = digitalRead(sensorPinId); digitalWrite(statePinId, state); return state == LOW; } /** * Move the servomotor to the designated position in one step. * @param degree Final position. */ void moveFastTo(const unsigned int degree) { servo.write(degree); delay(15); } /** * Move the servomotor to the designated position step by step. * @param degree Final position. * @param increment Step increment. */ void moveSmoothTo(const unsigned int degree, const unsigned int increment) { for (unsigned int current = 0; current <= degree; current += increment) { moveFastTo(current); } } <file_sep># Servomotor Sprinkler This is a prototype for an autonomous sprinkler, the project uses an infra-red sensor, a servomotor and a Digispark board. Please follow the tutorial [here](https://digistump.com/wiki/digispark/tutorials/connecting) for connecting your environment. ## Dependencies - [Arduino IDE](https://www.arduino.cc/en/software) - [Digispark Drivers](https://github.com/digistump/DigistumpArduino/releases) ## License [MIT &copy; <NAME>](https://balmante.eti.br)
7990299aa4eb29581522db06b126d0f7eb3576fb
[ "Markdown", "C++" ]
2
C++
balmanth/servo-sprinkler
ff062e8397ff70e8105048a712e0b6a13ace8eb0
509676b52556881a9ce13acaa40a177450eb2f3b
refs/heads/main
<repo_name>Karan-Munjani/Cryptography_Using_Python<file_sep>/Playfair Cipher.py def generateKeyMatrix (key): # Create 5X5 matrix with all values as 0 # [ # [0, 0, 0, 0, 0], # [0, 0, 0, 0, 0], # [0, 0, 0, 0, 0], # [0, 0, 0, 0, 0], # [0, 0, 0, 0, 0] # ] matrix_5x5 = [[0 for i in range (5)] for j in range(5)] simpleKeyArr = [] """ Generate SimpleKeyArray with key from user Input with following below condition: 1. Character Should not be repeated again 2. Replacing J as I (as per rule of playfair cypher) """ for c in key: if c not in simpleKeyArr: if c == 'J': simpleKeyArr.append('I') else: simpleKeyArr.append(c) """ Fill the remaining SimpleKeyArray with rest of unused letters from english alphabets """ is_I_exist = "I" in simpleKeyArr # A-Z's ASCII Value lies between 65 to 90 but as range's second parameter excludes that value we will use 65 to 91 for i in range(65,91): if chr(i) not in simpleKeyArr: # I = 73 # J = 74 # We want I in simpleKeyArr not J if i==73 and not is_I_exist: simpleKeyArr.append("I") is_I_exist = True elif i==73 or i==74 and is_I_exist: pass else: simpleKeyArr.append(chr(i)) """ Now map simpleKeyArr to matrix_5x5 """ index = 0 for i in range(0,5): for j in range(0,5): matrix_5x5[i][j] = simpleKeyArr[index] index+=1 return matrix_5x5 def indexLocator (char,cipherKeyMatrix): indexOfChar = [] # convert the character value from J to I if char=="J": char = "I" for i,j in enumerate(cipherKeyMatrix): # [ # (0, ['K', 'A', 'R', 'E', 'N']), # (1, ['D', 'B', 'C', 'F', 'G']), # (2, ['H', 'I', 'L', 'M', 'O']), # (3, ['P', 'Q', 'S', 'T', 'U']), # (4, ['V', 'W', 'X', 'Y', 'Z']) # ] # j refers to inside matrix => ['K', 'A', 'R', 'E', 'N'], for k,l in enumerate(j): # [(0,'K'),(1,'A'),(2,'R'),(3,'E'),(4,'N')] if char == l: indexOfChar.append(i) indexOfChar.append(k) return indexOfChar def encryption (plainText,key): cipherText = [] # 1. Generate Key Matrix keyMatrix = generateKeyMatrix(key) # 2. Encrypt According to Rules of playfair cipher i = 0 while i < len(plainText): # 2.1 calculate two grouped characters indexes from keyMatrix n1 = indexLocator(plainText[i],keyMatrix) n2 = indexLocator(plainText[i+1],keyMatrix) # 2.2 if same column then look in below row so # format is [row,col] # now to see below row => increase the row in both item # (n1[0]+1,n1[1]) => (3+1,1) => (4,1) # (n2[0]+1,n2[1]) => (4+1,1) => (5,1) # but in our matrix we have 0 to 4 indexes only # so to make value bound under 0 to 4 we will do %5 # i.e., # (n1[0]+1 % 5,n1[1]) # (n2[0]+1 % 5,n2[1]) if n1[1] == n2[1]: i1 = (n1[0] + 1) % 5 j1 = n1[1] i2 = (n2[0] + 1) % 5 j2 = n2[1] cipherText.append(keyMatrix[i1][j1]) cipherText.append(keyMatrix[i2][j2]) cipherText.append(", ") # same row elif n1[0]==n2[0]: i1= n1[0] j1= (n1[1] + 1) % 5 i2= n2[0] j2= (n2[1] + 1) % 5 cipherText.append(keyMatrix[i1][j1]) cipherText.append(keyMatrix[i2][j2]) cipherText.append(", ") # if making rectangle then # [4,3] [1,2] => [4,2] [3,1] # exchange columns of both value else: i1 = n1[0] j1 = n1[1] i2 = n2[0] j2 = n2[1] cipherText.append(keyMatrix[i1][j2]) cipherText.append(keyMatrix[i2][j1]) cipherText.append(", ") i += 2 return cipherText def convertPlainTextToDiagraphs (plainText): # add X if Two letters are being repeated for s in range(0,len(plainText)+1,2): if s<len(plainText)-1: if plainText[s]==plainText[s+1]: plainText=plainText[:s+1]+'X'+plainText[s+1:] # append X if the total letters are odd, to make plaintext even if len(plainText)%2 != 0: plainText = plainText[:]+'X' return plainText def main(): #Getting user inputs Key (to make the 5x5 char matrix) and Plain Text (Message that is to be encripted) key = input("Enter key: ").replace(" ","").upper() plainText =input("Plain Text: ").replace(" ","").upper() convertedPlainText = convertPlainTextToDiagraphs(plainText) print(convertedPlainText) keyMatrix = generateKeyMatrix(key) cipherText = " ".join(encryption(convertedPlainText,key)) print(cipherText) # print(len(keyMatrix)) => 5 print(keyMatrix) if __name__ == "__main__": main()
69515fe7b876984201e6b85349b6f62fe906612b
[ "Python" ]
1
Python
Karan-Munjani/Cryptography_Using_Python
fd1615cc33c7902c2c4445a41676ce0d2a731a83
575b7cc902a89fb84975ddf428659ea0acba60f7
refs/heads/master
<repo_name>zebramobile/easy_ddns<file_sep>/easy_ddns.gemspec Gem::Specification.new do |s| s.name = "easy_ddns" s.version = "0.0.3" s.author = "<NAME>" s.email = "<EMAIL>" s.homepage = "http://code.dusty.name" s.platform = Gem::Platform::RUBY s.summary = "DDNS Updater for dnsmadeeasy.com" s.has_rdoc = true s.files = %w[ README.txt lib/easy_ddns.rb bin/easy_ddns bin/easy_ips test/test_easy_ddns.rb ] s.extra_rdoc_files = ["README.txt"] s.executables = ['easy_ddns','easy_ips'] s.rubyforge_project = "none" end<file_sep>/lib/easy_ddns.rb require 'net/http' require 'open-uri' require 'yaml' class EasyDdns VERSION = '0.0.3' attr_reader :config def self.update ddns = EasyDdns.new ddns.update end def initialize check_config @config = YAML::load(File.open('/etc/ddns.yml')) end def private_ip self.send_request('http://169.254.169.254/latest/meta-data/local-ipv4') end def public_ip self.send_request('http://169.254.169.254/latest/meta-data/public-ipv4') end def update self.config['hosts'].each do |host| self.update_host( host['name'], host['id'], host['username'], host['password'], get_ip(host) ) end true end def update_host(name,id,user,pass,ip) url = 'http://www.dnsmadeeasy.com/servlet/updateip' url += "?username=#{user}&password=#{pass}" url += "&id=#{id}&ip=#{ip}" begin response = self.send_request(url) puts "#{name} : #{response}" rescue Exception => e puts "#{name} : #{e.message}" end end protected def get_ip(host) ip = case host['type'] when 'private' self.private_ip when 'public' self.public_ip end end def send_request(url) ip = Net::HTTP.get_response(URI.parse(url)) ip.value ip.body end def check_config unless File.exists?('/etc/ddns.yml') puts <<-EOD \n\n** Configuration file /etc/ddns.yml does not exist ** Please create a file named ddns.yml in /etc, and include ** your DDNS settings for dnsmadeeasy. # example /etc/ddns.yml hosts: - name: tmp1.yourhost.net id: 3333333 password: <PASSWORD> username: xxxxx type: public - name: tmp1.int.yourhost.net id: 4444444 password: <PASSWORD> username: xxxxx type: private\n\n EOD exit(1) end end end<file_sep>/bin/easy_ips #!/usr/bin/env ruby require 'rubygems' require 'easy_ddns' easy = EasyDdns.new puts <<-EOD Private IP : #{easy.private_ip} Public IP : #{easy.public_ip} EOD
1a5ef74ddf3c7441cbdf1fd0eb42cf967666f0b5
[ "Ruby" ]
3
Ruby
zebramobile/easy_ddns
cd724260483c81045d3a6af671551bee5ed27261
639f12f1724a33a6b43cffb8bc14b20f87701e7f
refs/heads/main
<file_sep># Imprimir para cada numero de 1 ate 100 em uma nova linha for item in range(99): if (((item + 1) % 3) + (((item + 1) % 5)) == 0) and item > 0: print ( "FooBaa") else: if (((item + 1) % 3) == 0): print ("Foo") else: if (((item + 1) % 5) == 0): print ("Baa") else: print ((item + 1)) <file_sep>Resposta 2 Programa que imprime cada numero de 1 ate 100 em uma nova linha Para multiplo de 3 imprime "Foo" ao inves do numero Para multipos de 5 imprime "Baa" ao inves do numero Para multiplos de 3 e 5 imprime "FooBaa" Utilizie a linguagem Python , pois as ferramentas que tenho hoje w estao voltadas para esta linguagem. Para executar , clonar o repositorio . Executar com o comando python3 main.py
1a767068ecdf58b622a5f17a146ab427839b8be9
[ "Markdown", "Python" ]
2
Python
tkrzesinski/Resposta2
d1a042ee1cc1257b287d5e68cf4ea8e4294252c3
6fe36029b5d35220f0742826cb04187cff4b01a5
refs/heads/master
<repo_name>larakit/lk-auth-simple<file_sep>/boot/routes.php <?php Route::group(['middleware' => 'web'], function () { Route::get('login', function () { return view('login'); }) ->name('login'); Route::post('login', function () { $login_field = config('auth-simple.login_field', 'email'); $login = Request::input($login_field); $remember = ('on' == Request::input('remember')); $password = Request::input('password'); $error = ''; $exist = \App\User::where($login_field, $login) ->count(); if (!$exist) { $error = 'Пользователь отсутствует на проекте'; } else { if (!Auth::attempt(compact([$login_field, 'password']), $remember)) { $error = 'Введите корректные данные для входа'; } } return view('login', compact('error', 'login')); }) ->name('login'); Route::get('logout', function () { Auth::logout(); Session::put('cas_logout', true); if (Request::ajax()) { return [ 'result' => 'success', 'message' => 'Вы успешно вышли', ]; } else { return Redirect::to('/logout-cas?123'); } }) ->name('logout'); Route::get('logout-cas', function () { \Larakit\Auth\LkCas::init(); \phpCAS::handleLogoutRequests(true, config('larakit.lk-auth-cas.allowed_clients')); \phpCAS::logout(); Session::forget('cas_logout'); return Redirect::to('/?logout_cas'); }); }); <file_sep>/config/auth-simple.php <?php return [ 'login_field' => 'email', 'login_title' => 'E-mail', ];<file_sep>/init.php <?php \Larakit\Boot::register_boot(__DIR__ . '/boot'); \Larakit\Boot::register_provider(\Larakit\Auth\LkAuthSimpleServiceProvider::class);
b92dd7e243abdb36debd05b216c09b472752c3c6
[ "PHP" ]
3
PHP
larakit/lk-auth-simple
ebe75ec48edce19e4782ba34c74560220443ebab
8fd41dd822022720c1e3ab8b01f376b08504d1e3
refs/heads/master
<file_sep>## 安装 ``` npm init -y npm install vue vue-router axios bootstrap // axios@0.17.1 //bootstrap@3.3.7 //vue-router@3.0.1 //vue@2.5.3 ``` ## 路由 - 访问不同的路径,就可以返回不同的结果 ## 多页面 与 SPA - single page application <file_sep>## vue-cli - 下载一个全局生成 vue 项目的脚手架 ``` npm install vue-cli -g vue init webpack <项目名字> cd 项目名字 npm install npm run dev ``` ## 模块, 定义,使用,导出 - node 模块的规范 commonjs - cmd seajs ,amd require - umd 为了做兼容处理的 - esmodule - 如何定义模块 (一个 js 就是一个模块) - 如何导出模块 (export) - 如何使用模块 (import) ## 先下载 webpack ``` npm iniy -y npm install webpack -g ``` > 安装 webpack 或者 less 最好不要安装全局的,否则可能导致 webpack 的版本差异 - 在 package.json 中配置一个脚本,这个脚本用的命令是 webpack,会去当前的 node_modules 下找 bin 对应的webpack名字,让其执行,执行的就是 bin/webpack.js, webpack.js 需要当前目录下有个名字叫 webpack.config.js 的文件,我们通过 npm run build 执行的是当前目录的,所以会在当前目录查找. ## babel 转义 es6- es5 - 安装 babel ``` npm install babel-core --save-dev npm install babel-loader --save-dev ``` ## babel-preset-es2015 - 让翻译官拥有解析 es6 语法的功能 ``` npm install babel-preset-es2015 --save-dev ``` ## babel-preset-stage-0 - 解析 es7 语法的 ``` npm install babel-preset-stage-0 --save-dev ``` ## 解析样式 直接 import css 文件是无法识别的。 - css-loader 将 css 解析成模块, 将解析的内容插入到 style 标签内(style-loader) ``` npm install css-loader style-loader --save-dev ``` ## less, sass, stylus(预处理语言) - less-loader - sass-loader - stylus-loader ``` npm install less less-loader --save-dev ``` ## 解析图片 - file-loader url-loader(url-loader 是依赖于 file-loader 的) ``` npm install file-loader url-loader --save-dev ``` ## 需要解析 html 的插件 - 插件的作用是以我们自己的html为模板,将打包后的结果自动引入到 html 中产出到 dist 目录下 ``` npm install html-webpack-plugin --save-dev ``` ## webpack-dev-server - 这里面内置了一个服务,可以帮我们启动一个端口号,当代码更新时,可以自动打包(内存中打包),代码有变化,就重新执行 ``` npm install webpack-dev-server --save-dev ``` ## 安装 vue-loader vue-template-compiler - vue-loader 解析 vue 文件的, vue 会自动调用 vue-template-compiler - vue-template-compiler 用来解析 vue 模板的 <file_sep>import * as Types from './mutations-type'; const mutations = { //add(state, count) {// state 是自动放入的,默认指的就是当前的 state [Types.INCREMENT](state, count) {// state 是自动放入的,默认指的就是当前的 state state.count += count; }, //minus(state) { [Types.DECREMENT](state) { state.count -=1; } }; export default mutations; <file_sep>let str = require('./a.js'); import xxx from './b.js'; console.log(str); console.log(xxx); let a = b => c=> d=> b + c +d; let obj = {school: 'zfpx'}; let obj1 = {age:8}; let newObj = {...obj, ...obj1}; //es7语法 console.log(newObj); import './index.css'; //引入 css import './style.less'; //引入 less 文件 //在js中引入图片需要 import , 或者 写一个线上路径。 import page from './1.jpg' let img = new Image(); //img.src = './2.jpg'; //写了一个字符串,webpack 不会进行查找 img.src = page; //page 就是打包后图片的路径 document.body.appendChild(img);<file_sep>// 加入购物车的功能 //添加购物车(添加的商品) export const ADD_CART = 'ADD_CART'; //删除购物车(要求传入 ID) export const REMOVE_CART = 'REMOVE_CART'; //更改商品数量({id, 1/-1}) export const CHANGE_COUNT = 'CHANGE_CART'; //清空购物车 export const CLEAR_CART = 'CLEAR_CART'; <file_sep>my js practice code <file_sep>let vm = new Vue({ el:'#app', directives:{ focus(el,bindings){ //当点击当前 li 的时候,让内部的输入框获取焦点 if(bindings.value){ el.focus();//获取焦点 } }, }, data:{ todos:[ {isSelected:false,title:'睡觉'}, {isSelected:false,title:'吃饭'}, ], new_todo: '', title: '', cur:'', hash:'', }, created(){//ajax获取,初始化数据 //如果 localStorage 中有数据,就用有的数据, 没有就用默认的 this.todos = JSON.parse(localStorage.getItem('data')) || this.todos; //监控 hash 值的变化,如果页面已经有 hash 了,重新刷新页面也要获取 hash 值 // this.hash = window.location.hash.slice(2) || 'all' window.addEventListener('hashchange',()=>{ //当 hash 值变化,重新操作记录的数据 this.hash = window.location.hash.slice(2); },false) }, watch:{ //todos(){ //watch 默认只监听一层的数据变化,如何深度监控? todos:{ handler(){ //默认写成函数就相当于默认写了个handler // localStorage 默认存的是字符串 localStorage.setItem('data',JSON.stringify(this.todos)); console.log("haha"); }, deep:true, }, }, methods:{ remove(p){//拿到当前点击的和数据中的进行比对,相等返回false即可 this.todos = this.todos.filter(item=>item!=p); //console.log('deleteOne'); }, add(){//keydown/keyup 差一个单词,keydown的时候内容没有进入到输入框内 //let tmp_todo={isSelected: false,title:this.new_todo}; //this.todos.push(tmp_todo); //this.new_todo=''; this.todos.push({ isSelected: false, title: this.title }); this.title = ''; }, remember(todo){//todo是当前点击的这一项 this.cur = todo; }, cancel(){ this.cur = ''; }, }, computed:{ filterTodos(){//只用 get 方法可以写成 函数, if(this.hash === 'all') return this.todos; if(this.hash === 'finish') return this.todos.filter(item=>item.isSelected); if(this.hash === 'unfinish') return this.todos.filter(item=>!item.isSelected); return this.todos; }, all_todo:{ get(){ return this.todos.filter(item=>!item.isSelected).length; }, set(){}, }, }, }); //1. 将数据循环到页面上 //2. 敲回车时添加新数据(需要加入isSelected属性) //3. 删除功能 //4. 计算一下当前没有被选中的个数 <file_sep>import Vue from 'vue'; import Vuex from 'vuex'; import logger from 'vuex/dist/logger'; Vue.use(Vuex); // 容器是唯一的 const state = { count:0, }; const getters = { val:(state)=>state.count%2?'奇数':'偶数' }; import mutations from './mutations'; export default new Vuex.Store({ state, mutations, getters, plugins:[logger()], strict: true, //只能通过 mutation (管理员)来改变状态, mutation 不支持异步 }); // 计数器 <file_sep>import axios from 'axios'; axios.defaults.baseURL = 'http://localhost:3000'; // 增加默认的请求路径 //拦截器 axios.interceptors.response.use((res)=>{ return res.data; //在这里统一拦截结果,把结果处理成 res.data; }) // 获取轮播图数据,返回的是一个 promise 对象 export let getSliders= () => { return axios.get('/sliders'); }; //获取热门图书接口 export let getHotBook = ()=>{ return axios.get('/hot'); }; //获取全部图书 export let getBooks = ()=>{ return axios.get('/book'); }; // 删除某一杯图书 export let removeBook = (id)=>{ return axios.delete(`/book?id=${id}`); }; // 获取某一本书 export let findOneBook = (id)=>{ return axios.get(`/book?id=${id}`); }; // 修改图书 /** * * @param id * @param data * @returns {AxiosPromise<any>} */ export let updateBook = (id, data)=>{ return axios.put(`book?id=${id}`,data); }; export let addBook = (data)=>{ return axios.post('/book', data); }; export let getAll = () =>{ return axios.all([getSliders(), getHotBook()]); }; //根据偏移量返回对应的数据 export let pagination = (offset)=>{ return axios.get(`/page?offset=${offset}`); }; <file_sep>## 项目用到 less ``` npm install less less-loader axios vuex bootstrap ``` - mock 模拟数据 - api 代表的是所有的接口 - base 基础组件 - components 页面组件 ## 热门图书的功能 - 先写服务端, 确保数据能正常返回 - 增加 API 方法,实现调取数据的功能 - 在哪个组件中应用这个API,如果是一个基础组件需要用这些数据,在使用这个组件的父级中调用这个方法,将数据传递给基础组件 - 写一个基础组件 - 1. 创建一个 .vue 文件 - 2. 在需要使用这个组件的父级中引用这个组件 - 3. 在组件中注册 - 4. 以标签的形式引入 ## 路由元信息 ## 下拉加载 /page - 默认每次给5条,前端告诉后台现在要从第几条开始给我 - /page?offset=5 - 后台返回还要告诉前端是否有更多的数据 hasMore:true ## coding split 代码分割 官方文档中的懒加载 > https://router.vuejs.org/zh-cn/advanced/lazy-loading.html <file_sep>// resolve 代表的是转向成功态 // reject 代表的是转向失败态 resolve 和 reject 均是函数 // promise 的实例就一个 then 方法, then 方法中有两个参数 let p = new Promise((resolve, reject)=>{ setTimeout(function(){ let a = '蘑菇'; resolve(a); },2000) }); p.then( (data)=>{console.log(data)}, (err)=>{console.log('err')} ); console.log(2);<file_sep>//发布 emit 订阅 on function Girl() { this._events = {} } Girl.prototype.on = function (eventName,callback){ if(this._events[eventName]){ this._events[eventName].push(callback); }else{ this._events[eventName] = [callback]; } }; Girl.prototype.emit =function (eventName, ...args){ // [].slice.call(arguments,1); // Array.from(arguments).slice(1); if(this._events[eventName]){ this._events[eventName].forEach(cb=>cb(...args)); } }; let girl = new Girl(); let cry = (who)=>{ console.log(who+' cry...'); }; let shopping = (who)=>{ console.log(who+' shopping...'); }; let eat = (who)=>{ console.log(who+' eating...'); }; girl.on('失恋',cry); girl.on('失恋',shopping); girl.on('失恋',eat); girl.emit('失恋','我','你'); <file_sep>export let str = '我很帅'; export let str2 = '我很英俊'; export let a = ()=>{ alert(1); } // 会将 str 和 str2 放到一个对象内导出 {str: '' ,str2:''} <file_sep>//如果是第三方模块,不需要加 ./ , 如果是文件模块需要加 ./ //在另一个文件中将内容解构出来即可使用 //import 拥有声明功能 //import 放到页面的顶部 //import {str, str2} from './a.js'; import * as b from './a.js'; console.log(b.str,b.str2); b.a(); // xxx代表的是 default 后的结果 import xxx from './b.js'; console.log(xxx);
e1c8652e963747d7bc2e3bddb94f46243cbc466f
[ "Markdown", "JavaScript" ]
14
Markdown
gitbeyond/gitskills
8b429c30ffbdbc8c9c01f7895f63d913dfc437d4
c0682b19a0938bafd24460f6a3f68f2efc8b7114
refs/heads/master
<file_sep><?php /** * Template Name: Services */ $container_class = "js-container"; get_header(); ?> <div class="sp-sm-4 sp-xs-6"></div> <section class="block"> <div class="container"> <h2 class="block__title"> Wedding Photoshoot </h2> <div class="sp-sm-5 sp-xs-4"></div> <div class="packages"> <?php echo do_shortcode('[bw-packages]'); ?> </div> </div> </section> <div class="sp-sm-6 sp-xs-4"></div> <section class="block"> <div class="container"> <h2 class="block__title"> <?php echo get_post_meta(get_the_ID(), "services_special_proposition_header", true); ?> </h2> <div class="sp-sm-4 sp-xs-4"></div> <div class="row"> <div class="col-md-3"></div> <div class="col-md-6"> <div class="special-package text-center"> <ul class="packages-list"> <?php $items = get_post_meta(get_the_ID(), "services_special_proposition_items", true); if ($items && sizeof($items) > 0): foreach ($items as $item): ?> <li> <span> <?php echo $item[0]; ?> </span> </li> <?php endforeach; endif; ?> </ul> <div class="sp-sm-8 sp-xs-8"></div> <div> <a href="#" target="_blank" class="button-medium"> Get price </a> </div> </div> </div> </div> </div> </section> <div class="sp-sm-6 sp-xs-4"></div> <section class="block block--with-background"> <div class="block__header_background"> <div class="sp-sm-6 sp-xs-4"></div> <h5 class="block__title block__title--small"> Feedbacks </h5> <div class="sp-sm-5 sp-xs-3"></div> <h2 class="block__title"> Answers to common questions </h2> <div class="sp-sm-6 sp-xs-6"></div> </div> <div class="container"> <div class="sp-sm-8"></div> <div class="row"> <div class="col-md-12"> <div class="tabs"> <?php $tabs = get_post_meta(get_the_ID(), 'services_tabs', true); if ($tabs && sizeof($tabs)): foreach ($tabs as $tab): ?> <h3><?php echo $tab[0]; ?></h3> <div><?php echo $tab[1]; ?></div> <?php endforeach; endif; ?> </div> </div> </div> </div> </section> <div class="sp-sm-6"></div> <?php get_footer(); ?><file_sep><?php register_nav_menus(array( 'menu-left' => __('Left Navigation', 'brainworks'), 'menu-right' => __('Right Navigation', 'brainworks'), 'second-menu' => __('Second Menu', 'brainworks'), )); <file_sep><!DOCTYPE html> <html <?php language_attributes(); ?> class="no-js"> <head> <meta charset="<?php bloginfo('charset'); ?>"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-mobile-web-app-title" content="<?php bloginfo('name'); ?> - <?php bloginfo('description'); ?>"> <link rel="shortcut icon" href="<?php echo esc_url(get_template_directory_uri() . '/assets/img/favicon.ico'); ?>" type="image/x-icon"> <link rel="icon" href="<?php echo esc_url(get_template_directory_uri() . '/assets/img/favicon.ico'); ?>" type="image/x-icon"> <?php wp_head(); ?> </head> <body <?php body_class(); ?> id="top"> <?php wp_body(); ?> <div class="wrapper"> <header class="header bebas"> <div class="container"> <div class="header-row d-flex align-items-center"> <?php if ( has_nav_menu( 'menu-left' ) ) { ?> <div class="header-item header-menu"> <nav class="menu menu-left"> <?php wp_nav_menu( array( 'theme_location' => 'menu-left', 'container' => false, 'menu_class' => 'menu-list', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 ) ); ?> </nav> </div> <?php } ?> <div class="header-item header-logo mx-auto"><?php get_default_logo_link(); ?></div> <?php if ( has_nav_menu( 'menu-right' ) ) { ?> <div class="header-item header-menu"> <nav class="menu menu-right"> <?php wp_nav_menu( array( 'theme_location' => 'menu-right', 'container' => false, 'menu_class' => 'menu-list', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 ) ); ?> </nav> </div> <?php } ?> </div> </div> </header> <?php if (has_nav_menu('menu-left') || has_nav_menu('menu-right')) { ?> <nav class="nav js-menu bebas"> <button type="button" tabindex="0" class="menu-item-close menu-close js-menu-close"></button> <?php wp_nav_menu(array( 'theme_location' => 'menu-left', 'container' => false, 'menu_class' => 'menu-container', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 )); wp_nav_menu(array( 'theme_location' => 'menu-right', 'container' => false, 'menu_class' => 'menu-container', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 )); ?> </nav> <?php } ?> <?php global $container_class; if (!isset($container_class) || empty($container_class) || !$container_class) { $container_class = "container js-container"; } ?> <div class="<?php echo $container_class; ?>"> <div class="nav-mobile-header"> <button class="hamburger js-hamburger" type="button" tabindex="0"> <span class="hamburger-box"> <span class="hamburger-inner"></span> </span> </button> <div class="logo"><?php get_default_logo_link(); ?></div> </div> <?php /* <button class="button-large">Test</button> <button class="button-medium">Test</button> <button class="button-small">Test</button> <button class="button-large button-inverse">Test</button> <button class="button-medium button-inverse">Test</button> <button class="button-small button-inverse">Test</button> <div style="background-color: #000"> <button class="button-large button-outline">Test</button> <button class="button-medium button-outline">Test</button> <button class="button-small button-outline">Test</button> </div> */ ?> <file_sep><?php /** * Template Name: Landing **/ ?> <!DOCTYPE html> <html <?php language_attributes(); ?> class="no-js"> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, user-scalable=no"> <meta name="apple-mobile-web-app-capable" content="yes" /> <meta name="apple-mobile-web-app-title" content="<?php bloginfo( 'name' ); ?> - <?php bloginfo( 'description' ); ?>"> <title><?php wp_title(); ?></title> <link rel="shortcut icon" href="<?php echo esc_url( get_template_directory_uri() ); ?>/assets/img/favicon.ico" type="image/x-icon" /> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <header class="header bebas"> <div class="container"> <div class="header-row d-flex align-items-center"> <?php if ( has_nav_menu( 'menu-left' ) ) { ?> <div class="header-item header-menu"> <nav class="menu menu-left"> <?php wp_nav_menu( array( 'theme_location' => 'menu-left', 'container' => false, 'menu_class' => 'menu-list', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 ) ); ?> </nav> </div> <?php } ?> <div class="header-item header-logo mx-auto"><?php get_default_logo_link(); ?></div> <?php if ( has_nav_menu( 'menu-right' ) ) { ?> <div class="header-item header-menu"> <nav class="menu menu-right"> <?php wp_nav_menu( array( 'theme_location' => 'menu-right', 'container' => false, 'menu_class' => 'menu-list', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 ) ); ?> </nav> </div> <?php } ?> </div> </div> </header> <?php if (has_nav_menu('menu-left') || has_nav_menu('menu-right')) { ?> <nav class="nav js-menu bebas"> <button type="button" tabindex="0" class="menu-item-close menu-close js-menu-close"></button> <?php wp_nav_menu(array( 'theme_location' => 'menu-left', 'container' => false, 'menu_class' => 'menu-container', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 )); wp_nav_menu(array( 'theme_location' => 'menu-right', 'container' => false, 'menu_class' => 'menu-container', 'menu_id' => '', 'fallback_cb' => 'wp_page_menu', 'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>', 'depth' => 3 )); ?> </nav> <?php } ?> <div class="home"> <div class="home__block"> <div class="home__block_content"> <h4> Semptember 2018 </h4> <h1> Alina + Maxim </h1> <div class="sp-md-6 sp-sm-6 sp-xs-6"></div> <a href="#" class="button-large button-outline"> View </a> </div> </div> </div> <?php wp_footer(); ?> </body> </html> <file_sep><?php /** * Template Name: Page Without Title **/ get_header(); if (have_posts()) : while (have_posts()) : the_post(); ?> <div class="sp-xs-10 sp-sm-10 sp-md-1 sp-lg-1 sp-xl-1"></div> <?php the_content(); wp_link_pages(); endwhile; else: get_template_part('loops/content', 'none'); endif; get_footer();<file_sep></div><!-- .page-wrapper end--> <?php if ( ! is_front_page() ) { ?> <footer class="footer js-footer"> <?php if (is_active_sidebar('footer-widget-area')) : ?> <div class="pre-footer"> <div class="container"> <div class="row"> <?php dynamic_sidebar('footer-widget-area'); ?> </div> </div> </div><!-- .pre-footer end--> <?php endif; ?> <div class="container"> <div class="row footer-row d-flex align-items-center justify-content-center text-center playfair"> <div class="col-md-4 footer-item"> <?php if (has_phones()) { ?> <ul class="phone mb-15"> <?php foreach (get_phones() as $phone) { ?> <li class="phone-item"> <a href="tel:<?php echo esc_attr(get_phone_number($phone)); ?>" class="phone-number text-size-20"> <?php echo esc_html($phone); ?> </a> </li> <?php } ?> </ul> <?php } $email = get_theme_mod( 'bw_additional_email' ); if ( ! empty( $email ) ) { ?> <div> <a class="text-size-20" href="mailto:<?php echo esc_attr( $email ); ?>"> <em><b><?php echo esc_html( $email ); ?></b></em> </a> </div> <?php } ?> </div> <div class="col-md-4 footer-social footer-item"> <p class="mb-15"><em><?php _e('Follow', 'brainworks'); ?> @zhuralvova_photo</em></p> <?php if (has_social()) { ?> <ul class="social"> <?php foreach (get_social() as $name => $social) { ?> <li class="social-item"> <a href="<?php echo esc_attr(esc_url($social['url'])); ?>" class="social-link social-<?php echo esc_attr($name); ?>" target="_blank"> <?php if (!empty($social['icon-html'])) { echo strip_tags($social['icon-html'], '<i>'); } else { ?> <i class="<?php echo esc_attr($social['icon']); ?>" aria-hidden="true" aria-label="<?php echo esc_attr($social['text']); ?>"></i> <?php } ?> </a> </li> <?php } ?> </ul> <?php } ?> </div> <div class="col-md-4 footer-item"> <button type="button" class="button-medium button-outline <?php the_lang_class('js-contact'); ?>"> <?php _e('Contact me', 'brainworks'); ?> </button> </div> </div> </div> </footer> <?php } ?> </div><!-- .wrapper end--> <?php scroll_top(); ?> <?php if (is_customize_preview()) { ?> <button class="button-small customizer-edit" data-control='{ "name":"bw_scroll_top_display" }'> <?php esc_html_e('Edit Scroll Top', 'brainworks'); ?> </button> <button class="button-small customizer-edit" data-control='{ "name":"bw_analytics_google_placed" }'> <?php esc_html_e('Edit Analytics Tracking Code', 'brainworks'); ?> </button> <button class="button-small customizer-edit" data-control='{ "name":"bw_login_logo" }'> <?php esc_html_e('Edit Login Logo', 'brainworks'); ?> </button> <?php } ?> <div class="is-hide"><?php svg_sprite(); ?></div> <?php wp_footer(); ?> </body> </html> <file_sep><?php /** * Template Name: About page */ ?> <?php get_header(); ?> <div class="sp-sm-6 sp-xs-6 sp-md-6"></div> <section class="block"> <div class="container"> <div class="block__row"> <div class="block__item"> <img src="<?php echo get_template_directory_uri() ?>/assets/img/about.png" /> </div> <div class="block__item"> <div class="roboto block__item_content block__item_content--translated"> <h2 class="playfair"> <?php echo get_post_meta(get_the_ID(), "about_header", true); ?> </h2> <?php echo get_post_meta(get_the_ID(), "about_content", true); ?> </div> </div> </div> </div> </section> <?php $cols = get_post_meta(get_the_ID(), 'about_columns', true); if ($cols && sizeof($cols) > 0): ?> <div class="sp-sm-6 sp-xs-6 sp-md-6"></div> <section class="block block--bordered-top text-center" id="stats"> <div class="sp-sm-3"></div> <div class="container"> <div class="row"> <?php foreach($cols as $col): ?> <div class="col-md-3"> <h3 class="playfair block__header block__header--pink counter" style="opacity: 0;"><?php echo $col[0]; ?></h3> <div class="sp-sm-2"></div> <p class="bebas"><?php echo $col[1]; ?></p> </div> <?php endforeach; ?> </div> </div> <div class="sp-sm-3"></div> </section> <?php endif; ?> <div class="sp-sm-6 sp-xs-6 sp-md-6"></div> <section class="block text-center"> <div class="container"> <h5 class="block__title block__title--small"> Feedbacks </h5> <div class="sp-sm-2 sp-xs-2 sp-md-2"></div> <h2 class="block__title"> What clients are saying ? </h2> <div class="sp-sm-2 sp-xs-4 sp-md-4"></div> <?php echo do_shortcode('[bw-static-reviews]'); ?> <div class="sp-sm-4 sp-xs-4 sp-md-4"></div> <div> <a href="/blog" class="button-large"> More testimonials </a> </div> </div> </section> <div class="sp-sm-6 sp-xs-6 sp-md-6"></div> <?php get_footer(); ?>
10aaaabed6133095f660bbab85f32c5c8720dbf1
[ "PHP" ]
7
PHP
kudinovfedor/marina-zhuravlova
198e25677269fee1058e88df43d0bd0f89648c7e
8a77f2aa4f587a9a74babc576ff0e52bd0d612d8
refs/heads/main
<file_sep># Battleship-Website ### Created by <NAME> & <NAME> Currently a functional Battleship game but unfunctional back-end as it needs to be hosted and ran locally. Description: A two team partner project for Web Development class intentionally made in LAMP stack with each team member utlizing full-stack development by using HTML, CSS, PHP, JavaScript, and SQL. A Battleship Game website with a database through an open-source cross-platform web server solution stack package (XAMPP) using an Apache HTTP Server and with an open source administration tool MariaDB. # Running Environment: XAMPP - For Database, local hosting Notepad or Sublime Text for CSS/HTML/PHP/JavaScript files. A README.txt with instructrions on how to run these files are included in the battleship folder. All File names are named accordingly, and are made to be self explanatory to the user. <file_sep><?php include "config.php"; ?> <!-- login.php --> <!DOCTYPE html> <html lang= "en"> <head> <meta charset="utf 8"> <title> Sign Up Page </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css"/> </head> <!-- Background Gradient--> <body> <header> <div class = "title"> BATTLESHIP <img src = "images/red.png" style = "width:50px; height 55px;"> <a href="userAccount.php" style="text-align:right"> <?php if (!isset($_SESSION["userid"])) { echo "Guest"; } else { echo "Welcome " . $_SESSION["userid"]; } ?> </a> </div> </header> <div class = "bgGradient"> <br> <!-- Register logo title --> <div class="title2" alt="Register logo"> REGISTER </div> <!-- left indent in margins --> <div class="leftMargins"> <form class="arialChange" method="POST" action="userRegistration.php"> USERNAME : <input type="text" name="username" class="formBox"><br> PASSWORD : <input type="<PASSWORD>" name="<PASSWORD>" class="formBox"><br> FIRST NAME : <input type="text" name="first_name" class="formBox"><br> LAST NAME : <input type="text" name="last_name" class="formBox"><br> AGE : <input type="number" name="age" class="formBox"><br> GENDER: <input type="text" name="gender" class="formBox"><br> LOCATION : <input type="text" name="location" class="formBox"><br><br> <input class= "myButton" type="submit" value="SUBMIT" > </form> <br> <br> <!-- Go back to homepage --> <a class = "myButton" href="login.php"> ← BACK </a> <br><br><br><br><br><br><br><br><br><br><br><br> </div> </div> <footer> <address style = "font-family:Arial; size: 1rem; color: #c6cbcf;"> © 2020 <NAME> & ROSELLYN VICENTE SOME RIGHTS RESERVED <br><br> CONTACT INFORMATION: <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> </a> <a>/</a> <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> <br> </a> </address> <!-- <address class="arialChange" > CONTACT INFORMATION: <a class="noLink" href=""> </address> --> </footer> </body> </html> <file_sep><?php include "config.php"; ?> <!-- home.php --> <html lang = "en"> <head> <meta charset="UTF-8"> <title> CSCI 130 Battleship Project </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css" media="all" /> </head> <body> <!-- Main title --> <header> <div class = "title"> BATTLESHIP <img src = "images/red.png" style = "width:50px; height 55px;"> <a href="userAccount.php" style="text-align:right"> <?php if (!isset($_SESSION["userid"])) { echo "Guest"; } else { echo "Welcome " . $_SESSION["userid"]; } ?> </a> </div> </header> <!-- Main content --> <div class = "bgGradient"> <!-- left indent in margins --> <div class="leftMargins"> <h3 class="arialChange leftMargins" style = "text-align:right;"> Created by using HTML, CSS, Javascript, and PHP </h3> <br> <div class="title2" alt="About Us Logo"> LEADERBOARD </div> <div class="table arialChange leftMargins"> <form method = "post" action=""> <label for="sort">Sort By: </label> <select name="sort" id = "sort"> <option name="games_won" value = "games_won">Won Games</option> <option name="time_played" value = "time_played">Time Played</option> <option name="games_played" value = "games_played"># of Games Played</option> </select> <br> <input type = "submit" value = "Submit"> </form> <?php if ('POST' === $_SERVER['REQUEST_METHOD']) { $sql = "SELECT * FROM players ORDER BY games_won DESC"; $result = $conn->query($sql); $count = 1; $option = $_POST["sort"]; echo "<table>"; echo "<thead> <tr> <th> Rank </th> <th>Username</th> <th>" . $option . "</th> </tr> </thead>"; if ($result->num_rows > 0) { echo "<tbody>"; while ($row = $result->fetch_assoc()) { if ($row["games_won"] == NULL) { continue; } else { echo "<tr>"; echo "<td>" . $count . "</td>" . "<td>" . $row["username"] . "</td>" . "<td>" . $row[$option] . "</td>"; echo "</tr>"; $count += 1; } } echo "</tbody>"; } else { echo "error"; } echo "</table> <br>"; $conn->close(); } ?> </div> </div> <a class = "leftMargins myButton" href="index.php"> ← BACK </a> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> </div> <!-- Footer containing copyright and email adress --> <footer> <address style = "font-family:Arial; size: 1rem; color: #c6cbcf;"> © 2020 <NAME> & ROSELLYN VICENTE SOME RIGHTS RESERVED <br><br> CONTACT INFORMATION: <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> </a> <a>/</a> <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> <br> </a> </address> <!-- <address class="arialChange" > CONTACT INFORMATION: <a class="noLink" href=""> </address> --> </footer> </body> </html><file_sep><?php include "config.php"; ?> <!-- about.php --> <!DOCTYPE html> <html lang= "en"> <head> <meta charset="utf 8"> <title> About Us </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css" media="all" /> </head> <!-- Blue to Black Gradient--> <body> <header> <div class = "title"> BATTLESHIP <img src = "images/red.png" style = "width:50px; height 55px;"> <a href="userAccount.php" style="text-align:right"> <?php if (!isset($_SESSION["userid"])) { echo "Guest"; } else { echo "Welcome " . $_SESSION["userid"]; } ?> </a> </div> </header> <div class = "bgGradient"> <br> <!-- About us Logo title --> <div class="title2" alt="About Us Logo"> ABOUT US </div> <!-- Joshua's mini CV --> <ul style = "list-style-image: url('images/paw.png')"> <!-- Joshua Francisco title --> <div class="title3" alt="Joshua Francisco Title"> <NAME>CISCO </div> <div class="leftMargins"> <img src="images/joshua_francisco.jpg" style= "width:200px; height:200px;" alt="<NAME>"> <br> </div> <div class="leftMargins arialChange"> <strong> Web Developer </strong> <br> <br> <i> Undergraduate Software Developer looking for entry level opportunities </i> <br> <br> <strong> EDUCATION: </strong> <li> Fresno State senior undergrad </li> <br> <strong> SKILLS: </strong> <li> PHP, SQL, HTML, CSS, JS, Haskell, C++, C#, Python, LaTeX, Github, Agile Programming </li> <br> <strong> EXPERIENCE: </strong> <li> Undergrad programmer of 5 years </li> <br> </div> </ul> <!-- Ros's mini CV --> <ul style = "list-style-image: url('images/paw.png')"> <!-- Rosellyn Vicente title --> <div class="title3" alt="<NAME>ente Title"> ROSELLYN VICENTE </div> <div class="leftMargins"> <img src="images/rosellyn_vicente.jpg" style= "width:200px" "height:40px" alt="rosellyn vicente"> <br> </div> <div class="leftMargins arialChange"> <strong> Web Developer </strong> <br> <br> <i> Undergraduate Software Developer looking for entry level opportunities </i> <br> <br> <strong> EDUCATION: </strong> <li> Fresno State senior undergrad </li> <br> <strong> SKILLS: </strong> <li> PHP, SQL, HTML, CSS, JS, Haskell, C++, Python, LaTeX </li> <br> <strong> EXPERIENCE: </strong> <li> Undergrad programmer of 4 years </li> <br> </div> </ul> <br> <br> <!-- Go back to homepage --> <a class = "leftMargins myButton" href="index.php"> ← BACK </a> <br><br><br><br><br><br><br><br><br> </div> <footer> <address style = "font-family:Arial; size: 1rem; color: #c6cbcf;"> © 2020 JO<NAME> & ROSELLYN VICENTE SOME RIGHTS RESERVED <br><br> CONTACT INFORMATION: <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> </a> <a>/</a> <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> <br> </a> </address> <!-- <address class="arialChange" > CONTACT INFORMATION: <a class="noLink" href=""> </address> --> </footer> </body> </html><file_sep><?php include "config.php"; $user = $_SESSION["userid"]; $sql = "UPDATE players SET games_played = games_played + 1,games_won = games_won + 1 WHERE username = '$user';"; $result = $conn->query($sql); $conn->close(); ?><file_sep>CREATE TABLE IF NOT EXISTS `players` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `first_name` varchar(255) NOT NULL, `last_name` varchar(255) NOT NULL, `age` varchar(255) NOT NULL, `gender` varchar(255) NOT NULL, `location` varchar(255) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `username` (`username`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;<file_sep><?php include "config.php"; ?> <!-- login.php --> <!DOCTYPE html> <html lang= "en"> <head> <meta charset="utf 8"> <title> Login Page </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css" media="all" /> </head> <!-- Background Gradient--> <body> <header> <div class = "title"> BATTLESHIP <img src = "images/red.png" style = "width:50px; height 55px;"> <a href="userAccount.php" style="text-align:right"> <?php if (!isset($_SESSION["userid"])) { echo "Guest"; } else { echo "Welcome " . $_SESSION["userid"]; } ?> </a> </div> </header> <div class = "bgGradient"> <!-- Login logo title --> <div class="title2" alt="Login logo"> LOGIN </div> <!-- left indent in margins --> <div class="leftMargins arialChange"> <h3> Welcome to Online Web Battleship Game! </h3> <form method="POST" action="userLogin.php" class="arialChange"> <!--Username and Password input --> USERNAME: <input type="text" name="username" class="formBox"><br><br> PASSWORD: <input type="<PASSWORD>" name="<PASSWORD>" class="formBox"><br><br> <!--Login and Register Buttons --> <input type="submit" name="submit" class= "myButton" value="Login"> <a class = "myButton" href="register.php"> Register </a> </form> </div> <br> <br> <!-- Go back to homepage --> <a class = "leftMargins myButton" href="index.php"> ← BACK </a> <br><br><br><br><br><br><br><br><br><br><br><br> </div> <footer> <address style = "font-family:Arial; size: 1rem; color: #c6cbcf;"> © 2020 JO<NAME> & ROSELLYN VICENTE SOME RIGHTS RESERVED <br><br> CONTACT INFORMATION: <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> </a> <a>/</a> <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> <br> </a> </address> <!-- <address class="arialChange" > CONTACT INFORMATION: <a class="noLink" href=""> </address> --> </footer> </body> </html><file_sep><?php include "config.php"; ?> <!-- howtoplay.php --> <!DOCTYPE html> <html lang= "en"> <head> <meta charset="utf 8"> <title> How to Play </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css" media="all" /> </head> <!-- Green to black gradient background CHANGE LATER--> <body> <header> <div class = "title"> BATTLESHIP <img src = "images/red.png" style = "width:50px; height 55px;"> <a href="userAccount.php" style="text-align:right"> <?php if (!isset($_SESSION["userid"])) { echo "Guest"; } else { echo "Welcome " . $_SESSION["userid"]; } ?> </a> </div> </header> <div class = "bgGradient"> <!-- How to Play PNG logo title --> <br> <div class="title2" alt="How to Play"> HOW TO PLAY </div> <!-- left indent in margins and font change--> <div class="leftMargins"> <span class="arialChange"> <!-- "Meat" of the page --> <h3> INTRODUCTION </h3> <p> Hello! and Welcome to the How-to-Play page. This page includes the history of Battleshiop and provides a description of the game with the purpose of teaching newcomers how to play the game. </p> <h3> ORIGIN </h3> <p> Battleship is known worldwide as a pencil and paper game which dates from World War I. It was published by various companies as a pad-and-pencil game in the 1930s, and was released as a plastic board game by <NAME> in 1967. The game has spawned various electronic versions, video games, smart device apps and a film. </p> <img src = "images/old_battleship.jpg" alt = "old battleship game" style="display:block;margin-left:auto;margin-right:auto;"> <h3> DESCRIPTION </h3> <p> Battleship is a strategy type guessing game for two players. It is played on ruled grids (paper or board) on which each player's fleet of ships (including battleships) are marked. The locations of the fleets are concealed from the other player. Players alternate turns calling "shots" at the other player's ships, and the objective of the game is to destroy the opposing player's fleet. </p> <img src="images/grid.gif" alt="battleship grid" style="display:block;margin-left:auto;margin-right:auto"> <h3> RULES </h3> <ul style = "list-style-image: url('images/paw.png')"> <li>Both players must discreetly place ships on their board. </li> <ul> <li> Ships consist of Carriers (5 spaces), Battleships (4 spaces), Cruisers (3 spaces), Submarine (3 spaces), and Destroyer (2 spaces) </li> <li> Ships must be arranged either vertically or horizontally. </li> <li> Ships cannot overlap. </li> </ul> <li>Players each take turns guessing where their opponents' ships are located. The game will respond with a red "hit" or a white "miss" accordingly. </li> <li>Players are allowed the following 2 super powers </li> <ul> <li> Send 3 hits in one turn </li> <li> Send a big hit (hits surrounding area) </li> </ul> <li>Once a player has successfully sunken all of the other players' ships, the game will end.</li> </ul> </span> <br> <br> <!-- Go back to homepage --> <a class="myButton" href="index.php"> ← BACK </a> </div> <br><br><br><br><br><br><br><br><br><br><br><br> </div> <footer> <address style = "font-family:Arial; size: 1rem; color: #c6cbcf;"> © 2020 <NAME> & ROSELLYN VICENTE SOME RIGHTS RESERVED <br><br> CONTACT INFORMATION: <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> </a> <a>/</a> <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> <br> </a> </address> <!-- <address class="arialChange" > CONTACT INFORMATION: <a class="noLink" href=""> </address> --> </footer> </body> </html><file_sep><?php include "config.php"; ?> <!-- home.php --> <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="UTF-8"> <title> CSCI 130 Battleship Project </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css" media="all" /> <link rel="stylesheet" href="CSS/game-style.css"> <!-- Google font API --> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@500&display=swap" rel="stylesheet"> <!-- Select Single Player or Multi Player game modes --> <script> let gameMode = 'singlePlayer' </script> <script src="Javascript/app.js" charset="utf-8"></script> </head> <body> <!-- Main title --> <header> <div class = "title"> BATTLESHIP <img src = "images/red.png" style = "width:50px; height 55px;"> <a href="userAccount.php" style="text-align:right"> <?php if (!isset($_SESSION["userid"])) { echo "Guest"; } else { echo "Welcome " . $_SESSION["userid"]; } ?> </a> </div> </header> <!-- Main content --> <div class = "bgGradient"> <label id="minutes">00</label>:<label id="seconds">00</label> <br> <div class="container hidden-info"> <h2 id="turn" class="info-text"> Player Starts First </h2> <h3 id="turn" class="info-text"> ← Player | Computer → </h3> </div> <!-- Container will hold user and computer grid --> <div class="container"> <div class="battleship-grid grid-player"></div> <div class="battleship-grid grid-computer"></div> </div> <!-- Buttons to start game, rotate, turns, and information for turns --> <div class="container hidden-info"> <div class="setup-buttons" id="setup-buttons"> <br> <br> <button id="start-game" class="btn">Start Game</button> <button id="rotate-ships" class="btn">Rotate Ships</button> <button id="restart" class="btn"> Reset Ships</button> </div> <br> <h2 id="info" class="info-text"></h2> <div id = "playerwin"></div> </div> <!-- User ships--> <div class="container"> <div class="grid-display"> <div class="ship destroyer-container" draggable="true"><div id="destroyer-0"></div><div id="destroyer-1"></div></div> <div class="ship submarine-container" draggable="true"><div id="submarine-0"></div><div id="submarine-1"></div><div id="submarine-2"></div></div> <div class="ship cruiser-container" draggable="true"><div id="cruiser-0"></div><div id="cruiser-1"></div><div id="cruiser-2"></div></div> <div class="ship battleship-container" draggable="true"><div id="battleship-0"></div><div id="battleship-1"></div><div id="battleship-2"></div><div id="battleship-3"></div></div> <div class="ship carrier-container" draggable="true"><div id="carrier-0"></div><div id="carrier-1"></div><div id="carrier-2"></div><div id="carrier-3"></div><div id="carrier-4"></div></div> </div> </div> <!-- Go back to homepage --> <br><br><br><br><br><br><br><br> <a class = "leftMargins myButton" href="index.php"> ← BACK </a> <br><br><br> </div> <!-- Footer containing copyright and email adress --> <footer> <address style = "font-family:Arial; size: 1rem; color: #c6cbcf;"> © 2020 <NAME> & ROSELLYN VICENTE SOME RIGHTS RESERVED <br><br> CONTACT INFORMATION: <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> </a> <a>/</a> <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> <br> </a> </address> </footer> </body> </html><file_sep>-----README----- Created by <NAME> & <NAME> *NOTE:* Currently a functional Battleship game but unfunctional back-end unless locally hosted on your personal computer Running Environment: -XAMPP for database and local hosting -Text Editor of your choice (ex. Notepad++,Sublime) for CSS/HTML/PHP/JavaScript files. Description: A two team partner project for CSCI 130 made purely for full-stack development by using HTML, CSS, PHP, JavaScript, and SQL. A battleship game website with a database through an open-source cross-platform web server solution stack package (XAMPP) using an Apache HTTP Server and with an open source administration tool MariaDB. How to: To run these files XAMPP must de installed on your personal computer. You can find a downloadable version of XAMPP here: https://www.apachefriends.org/download.html These files can also be accessed through any web browser but are not hosted 24/7. With the battleship folder drag and drop your files into htdocs (File path: D:\XAMPP\htdocs\battleship). On the XAMPP Control Panel Start the Apache and MySQL services to run the server and allow for a connection to the database. In the battleship/database a sql folder consisting of the database of player accounts can be found. Import this into your databse on phpMyAdmin. Once imported back-end access is enabled. At this point everything should be working. To access the website directly, in your web browser address type in: localhost/battleship/index.php. You should be able to see the landing page of the website and access every feature of the website from the howto, game, about, login and register pages. <file_sep><?php include "config.php"; ?> <!-- home.php --> <html lang = "en"> <head> <meta charset="UTF-8"> <title> CSCI 130 Battleship Project </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css" media="all" /> </head> <body> <!-- Main title --> <header> <div class = "title"> BATTLESHIP <img src = "images/red.png" style = "width:50px; height 55px;"> <a href="userAccount.php" style="text-align:right"> <?php if (!isset($_SESSION["userid"])) { echo "Guest"; } else { echo "Welcome " . $_SESSION["userid"]; } ?> </a> </div> </header> <!-- Main content --> <div class = "bgGradient"> <!-- left indent in margins --> <div class="leftMargins arialChange"> <br> <div class="title2"> <?php //Login.php //Variables submitted by user $loginUser = $_POST["username"]; $loginPass = $_POST["<PASSWORD>"]; $sql = "SELECT password FROM players WHERE username = '" . $loginUser . "'"; $result = $conn->query($sql); if ($result->num_rows > 0) { //output data of each row while($row = $result->fetch_assoc()) { if($row["password"] == $loginPass) { $_SESSION["userid"] = $loginUser; header("location: index.php"); //Add other functionalities here: //Get user's data here. //Get player info. //Modify player data. } else { echo "Wrong Credentials."; } } } else { echo "Username does not exist."; } //Close connection $conn->close(); ?> </div> <?php echo "Welcome, " . $loginUser . "!<br>"; ?> <a class = "myButton" href="game.php"> Enter Arena </a> <br><br> <a class = "myButton" href="userinfo.php"> Account Information </a> <br><br> <a class = "myButton" href="index.php"> Home </a> <br><br> </div> <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> </div> <!-- Footer containing copyright and email adress --> <footer> <address style = "font-family:Arial; size: 1rem; color: #c6cbcf;"> © 2020 <NAME> & ROSELLYN VICENTE SOME RIGHTS RESERVED <br><br> CONTACT INFORMATION: <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> </a> <a>/</a> <a class="noLink" href="mailto:<EMAIL>?subject=CSCI 130 Project Inquiries"> <EMAIL> <br> </a> </address> <!-- <address class="arialChange" > CONTACT INFORMATION: <a class="noLink" href=""> </address> --> </footer> </body> </html><file_sep><?php //RegisterUser.php $servername = "localhost"; $username = "root"; $password = ""; $dbname = "accounts"; //database name located on mySQL server. //Variables submitted by user $loginUser = $_POST["username"]; $loginPass = $_POST["password"]; $first_name = $_POST["first_name"]; $last_name = $_POST["last_name"]; $age = $_POST["age"]; $gender = $_POST["gender"]; $location = $_POST["location"]; //Create connection to database $conn = new mysqli($servername, $username, $password, $dbname); //Check connection if ($conn->connect_error) { //If connection has connection error php will die (equivalent to exit) with message die("Connection failed: " . $conn->connect_error); } $sql = "SELECT username FROM players WHERE username = '" . $loginUser . "'"; //Open Connection $result = $conn->query($sql); if ($result->num_rows > 0) { //Tells the user that name is already taken echo "Username is already taken."; } else { echo "Creating user..."; //Query to insert the user, password, first_name, last_name, age, gender, and location into the players database $sql2 = "INSERT INTO players (username, password, first_name, last_name, age, gender, location) VALUES ('" . $loginUser . "', '" . $loginPass . "' , '" . $first_name . "' , '" . $last_name . "' , '" . $age . "' , '" . $gender . "' , '" . $location . "')"; if ($conn->query($sql2) === TRUE) { echo "New record created successfully"; //Once user registers redirects to register.php //header("Location: register.php"); } else { echo "Error: " . $sql2 . "<br>" . $conn->error; } } //Close connection $conn->close(); ?> <html lang = "en"> <head> <meta charset="UTF-8"> <title> Registration Complete </title> <!-- CSS elements header file --> <link rel="stylesheet" href="CSS/styles.css" media="all" /> </head> <!-- Gradient background --> <body class = "bgGradient"> <!-- Go back to homepage --> <br> <br> <a class = "leftMargins myButton" href="login.php"> ← BACK </a> </body> </html><file_sep><?php session_start(); $servername = "localhost"; //Hostname $username = "root"; //User $password = ""; //<PASSWORD> $dbname = "accounts"; //database name located on mySQL server. //Create connection $conn = new mysqli($servername, $username, $password, $dbname); //Check connection if ($conn->connect_error) //If connection has connection error php will die (equivalent to exit) with message { die("Connection failed: " . $conn->connect_error); } ?><file_sep>document.addEventListener('DOMContentLoaded', () => { const playerGrid = document.querySelector('.grid-player'); const computerGrid = document.querySelector('.grid-computer'); const displayGrid = document.querySelector('.grid-display'); const ships = document.querySelectorAll('.ship'); const destroyer = document.querySelector('.destroyer-container'); const submarine = document.querySelector('.submarine-container'); const cruiser = document.querySelector('.cruiser-container'); const battleship = document.querySelector('.battleship-container'); const carrier = document.querySelector('.carrier-container'); const startGameButton = document.querySelector('#start-game'); const rotateShipsButton = document.querySelector('#rotate-ships'); const turnDisplay = document.querySelector('#turn'); const infoDisplay = document.querySelector('#info'); const setupButtons = document.getElementById('setup-buttons'); const userSquares = []; const computerSquares = []; const width = 10; let setHorizontal = true; let endGame = false; let currentPlayer = 'player'; let playerNum = 0; let ready = false; let enemyReady = false; let allShipsPlaced = false; let hitsFired = -1; var timer; //ship array, setting size of ships. const arrayShips = [ { name: 'destroyer', positions: [ [0, 1], [0, width] ]}, { name: 'submarine', positions: [ [0, 1, 2], [0, width, width*2] ]}, { name: 'cruiser', positions: [ [0, 1, 2], [0, width, width*2] ]}, { name: 'battleship', positions: [ [0, 1, 2, 3], [0, width, width*2, width*3] ]}, { name: 'carrier', positions: [ [0, 1, 2, 3, 4], [0, width, width*2, width*3, width*4] ]}, ] //Create a 10x10 grid board and gives each square an id function createGameBoard(grid, squares) { for (let i = 0; i < width*width; i++) { const square = document.createElement('div'); square.dataset.id = i; grid.appendChild(square); squares.push(square); } } //Generates user and computer grid createGameBoard(playerGrid, userSquares); createGameBoard(computerGrid, computerSquares); // Selection screen if (gameMode === 'singlePlayer') { startSinglePlayer(); } // Single Player function startSinglePlayer() { var minutesLabel = document.getElementById("minutes"); var secondsLabel = document.getElementById("seconds"); var totalSeconds = 0; timer = setInterval(setTime, 1000); function setTime() { ++totalSeconds; secondsLabel.innerHTML = pad(totalSeconds % 60); minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60)); } function pad(val) { var valString = val + ""; if (valString.length < 2) { return "0" + valString; } else { return valString; } } //Generate player ships generate(arrayShips[0]); generate(arrayShips[1]); generate(arrayShips[2]); generate(arrayShips[3]); generate(arrayShips[4]); startGameButton.addEventListener('click', () => { setupButtons.style.display = 'none'; playGame(); }) } //Draw computer ships on computer grid in random location. function generate(ship) { let randomDirection = Math.floor(Math.random() * ship.positions.length); let current = ship.positions[randomDirection]; if (randomDirection === 0) { direction = 1; } if (randomDirection === 1) { direction = 10; } let randomStart = Math.abs(Math.floor(Math.random() * computerSquares.length - (ship.positions[0].length * direction))); const takenSpace = current.some(index => computerSquares[randomStart + index].classList.contains('taken')); const rightEdge = current.some(index => (randomStart + index) % width === width - 1); const leftEdge = current.some(index => (randomStart + index) % width === 0); //Check to see that any ships do not overlap or protrude off the game grid if (!takenSpace && !rightEdge && !leftEdge) { current.forEach(index => computerSquares[randomStart + index].classList.add('taken', ship.name)); } //else generate if there are no problems else { generate(ship); } } //Rotate the ships function rotate() { //Rotates all ships back to vertical if (setHorizontal) { destroyer.classList.toggle('destroyer-container-vertical'); submarine.classList.toggle('submarine-container-vertical'); cruiser.classList.toggle('cruiser-container-vertical'); battleship.classList.toggle('battleship-container-vertical'); carrier.classList.toggle('carrier-container-vertical'); setHorizontal = false; return; } //Rotates all ships back to horizontal if (!setHorizontal) { destroyer.classList.toggle('destroyer-container-vertical'); submarine.classList.toggle('submarine-container-vertical'); cruiser.classList.toggle('cruiser-container-vertical'); battleship.classList.toggle('battleship-container-vertical'); carrier.classList.toggle('carrier-container-vertical'); setHorizontal = true; return; } } rotateShipsButton.addEventListener('click', rotate); //functions to move around player ship's ships.forEach(ship => ship.addEventListener('dragstart', dragStart)); userSquares.forEach(square => square.addEventListener('dragstart', dragStart)); userSquares.forEach(square => square.addEventListener('dragover', dragOver)); userSquares.forEach(square => square.addEventListener('dragenter', dragEnter)); userSquares.forEach(square => square.addEventListener('drop', dragDrop)); let selectedShipNameWithIndex; let draggedShip; let draggedShipLength; ships.forEach(ship => ship.addEventListener('mousedown', (e) => { selectedShipNameWithIndex = e.target.id; })) function dragStart() { draggedShip = this; draggedShipLength = this.childNodes.length; } function dragOver(e) { e.preventDefault(); } function dragEnter(e) { e.preventDefault(); } //Ship is draggable and will be placed within the grid. function dragDrop() { let shipNameWithLastId = draggedShip.lastChild.id; let shipClass = shipNameWithLastId.slice(0, -2); let lastShipIndex = parseInt(shipNameWithLastId.substr(-1)); let shipLastId = lastShipIndex + parseInt(this.dataset.id); //Do not allow ships to be placed on these specific spaces on the player's grid. const spacesNotAllowedHorizontal = [0,10,20,30,40,50,60,70,80,90,1,11,21,31,41,51,61,71,81,91,2,22,32,42,52,62,72,82,92,3,13,23,33,43,53,63,73,83,93]; const spacesNotAllowedVertical = [99,98,97,96,95,94,93,92,91,90,89,88,87,86,85,84,83,82,81,80,79,78,77,76,75,74,73,72,71,70,69,68,67,66,65,64,63,62,61,60]; let newSpacesNotAllowedHorizontal = spacesNotAllowedHorizontal.splice(0, 10 * lastShipIndex); let newSpacesNotAllowedVertical = spacesNotAllowedVertical.splice(0, 10 * lastShipIndex); selectedShipIndex = parseInt(selectedShipNameWithIndex.substr(-1)); shipLastId = shipLastId - selectedShipIndex; if (setHorizontal && !newSpacesNotAllowedHorizontal.includes(shipLastId)) { for (let i=0; i < draggedShipLength; i++) { let directionClass; if (i === 0) directionClass = 'start'; if (i === draggedShipLength - 1) directionClass = 'end'; userSquares[parseInt(this.dataset.id) - selectedShipIndex + i].classList.add('taken', 'horizontal', directionClass, shipClass); } } //As long as a ship isn't dragged out of bounds, or within any of the spaces not allowed array your ship will be placed on the grid //if they do meet those conditions they will not appear of the grid else if (!setHorizontal && !newSpacesNotAllowedVertical.includes(shipLastId)) { for (let i=0; i < draggedShipLength; i++) { let directionClass; if (i === 0) directionClass = 'start'; if (i === draggedShipLength - 1) directionClass = 'end'; userSquares[parseInt(this.dataset.id) - selectedShipIndex + width*i].classList.add('taken', 'vertical', directionClass, shipClass); } } else { return; } displayGrid.removeChild(draggedShip); if(!displayGrid.querySelector('.ship')) allShipsPlaced = true; } function playerReady(num) { let player = `.p${parseInt(num) + 1}`; document.querySelector(`${player} .ready`).classList.toggle('active'); } //Single Player Mode function playGame() { if (endGame) return; if (currentPlayer === 'player') { turnDisplay.innerHTML = 'Players Turn'; computerSquares.forEach(square => square.addEventListener('click', function(e) { hitsFired = square.dataset.id; revealSquare(square.classList); })) } if (currentPlayer === 'enemy') { turnDisplay.innerHTML = 'Opponents Turn'; setTimeout(computerGo, 700); } } //Player Variables let playerDestroyerCount = 0; let playerSubmarineCount = 0; let playerCruiserCount = 0; let playerBattleshipCount = 0; let playerCarrierCount = 0; function revealSquare(classList) { const enemySquare = computerGrid.querySelector(`div[data-id='${hitsFired}']`); const obj = Object.values(classList); if (!enemySquare.classList.contains('hit') && currentPlayer === 'player' && !endGame) { if (obj.includes('destroyer')) { playerDestroyerCount++; } if (obj.includes('submarine')) { playerSubmarineCount++; } if (obj.includes('cruiser')) { playerCruiserCount++; } if (obj.includes('battleship')) { playerBattleshipCount++; } if (obj.includes('carrier')) { playerCarrierCount++; } } if (obj.includes('taken')) { enemySquare.classList.add('hit'); } else { enemySquare.classList.add('miss'); } winCheck() currentPlayer = 'enemy'; if(gameMode === 'singlePlayer') { playGame(); } } let computerDestroyerCount = 0; let computerSubmarineCount = 0; let computerCruiserCount = 0; let computerBattleshipCount = 0; let computerCarrierCount = 0; function computerGo(square) { if (gameMode === 'singlePlayer') { square = Math.floor(Math.random() * userSquares.length); } if (!userSquares[square].classList.contains('hit')) { const hit = userSquares[square].classList.contains('taken'); userSquares[square].classList.add(hit ? 'hit' : 'miss'); if (userSquares[square].classList.contains('destroyer')) { computerDestroyerCount++ } if (userSquares[square].classList.contains('submarine')) { computerSubmarineCount++ } if (userSquares[square].classList.contains('cruiser')) { computerCruiserCount++ } if (userSquares[square].classList.contains('battleship')) { computerBattleshipCount++ } if (userSquares[square].classList.contains('carrier')) { computerCarrierCount++ } winCheck(); } else if (gameMode === 'singlePlayer') { computerGo(); } currentPlayer = 'player'; turnDisplay.innerHTML = 'Players Turn'; } //Check to see if player has sunken enough spaces on grid. function winCheck() { if (playerDestroyerCount === 2) { infoDisplay.innerHTML = `You've sunk the Opponent destroyer! (2)`; playerDestroyerCount = 10; } if (playerSubmarineCount === 3) { infoDisplay.innerHTML = `You've sunk the Opponent submarine! (3)`; playerSubmarineCount = 10; } if (playerCruiserCount === 3) { infoDisplay.innerHTML = `You've sunk the Opponent cruiser! (3)`; playerCruiserCount = 10; } if (playerBattleshipCount === 4) { infoDisplay.innerHTML = `You've sunk the Opponent battleship! (4)`; playerBattleshipCount = 10; } if (playerCarrierCount === 5) { infoDisplay.innerHTML = `You've sunk the Opponent carrier! (5)`; playerCarrierCount = 10; } if (computerDestroyerCount === 2) { infoDisplay.innerHTML = `Opponent has sunk your destroyer! (2)`; computerDestroyerCount = 10; } if (computerSubmarineCount === 3) { infoDisplay.innerHTML = `Opponent has sunk your submarine! (3)`; computerSubmarineCount = 10; } if (computerCruiserCount === 3) { infoDisplay.innerHTML = `Opponent has sunk your cruiser! (3)`; computerCruiserCount = 10; } if (computerBattleshipCount === 4) { infoDisplay.innerHTML = `Opponent has sunk your battleship! (4)`; computerBattleshipCount = 10; } if (computerCarrierCount === 5) { infoDisplay.innerHTML = `Opponent has sunk your carrier! (5)`; computerCarrierCount = 10; } //Win condition, to check if player or computer has sunk enough spaces on grid. if ((playerDestroyerCount + playerSubmarineCount + playerCruiserCount + playerBattleshipCount + playerCarrierCount) === 50) { infoDisplay.innerHTML = "Congratulations You've Won!!!"; gameOver(); clearInterval(timer); playerWin(); getTime(); } if ((computerDestroyerCount + computerSubmarineCount + computerCruiserCount + computerBattleshipCount + computerCarrierCount) === 50) { infoDisplay.innerHTML = `Your Opponent has Won...`; gameOver(); } } function playerWin() { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { let div = document.getElementById("playerwin"); div.innerHTML = this.responseText; } }; xmlhttp.open("POST","updateplayerinfo.php",true); xmlhttp.send(); } function getTime() { var minutesLabel = document.getElementById("minutes").value; var secondsLabel = document.getElementById("seconds").value; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { let div = document.getElementById("playerwin"); div.innerHTML = this.responseText; } }; xmlhttp.open("POST","updatetime.php"); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send("minute="+minutesLabel+"&second="+secondsLabel+""); } function gameOver() { endGame = true; startGameButton.removeEventListener('click', playGame); } }) <file_sep><?php include "config.php"; $user = $_SESSION["userid"]; $minute = $_POST["minute"]; $second = $_POST["second"]; $sql = "UPDATE players SET time_played = '$minute' WHERE username = '$user';"; $result = $conn->query($sql); $conn->close(); ?>
f1f2d87329c5e6255fde04ea910f7a0f83aae884
[ "SQL", "Markdown", "JavaScript", "Text", "PHP" ]
15
Markdown
JoshuaFrancisco/Battleship-website
991f7f207fa61d0126c39047976ac71cfcad2eb9
3a7d3114673fbec6d1483d344a7d78af80609805
refs/heads/main
<repo_name>APPLESHOTTIPS/REACTFORMVALIDATIONS<file_sep>/Slectedbox.js import React from 'react'; class Slectedbox extends React.Component { constructor(props) { super(props); this.state = { selectedcars : "" }; } render() { return ( <React.Fragment> <section className ="p-3"> <div className="container"> <div className="row"> <div className="col-md-4"> <div className="card"> <div className="card-header bg-secondary text-white"> <p className="h4">SELECT A CAR</p> </div> <div className="card-body"> <form> <div className="form-group"> <select onChange ={e => this.setState({selectedcars : e.target.value})} className="form-control"> <option value="">select a car</option> <option value="bmw">bmw</option> <option value="audi">audi</option> <option value="benz">benz</option> <option value="ducati">ducati</option> <option value="rollsroyce"></option> </select> </div> </form> <div className="col"> <p className="h4">{this.state.selectedcars}</p> </div> </div> </div> </div> </div> </div> </section> </React.Fragment> ); } } export default Slectedbox; <file_sep>/Nav.jsx import React from 'react'; import './App.css'; class Nav extends React.Component{ styles = { fontStyle :"bold", color :"teal" }; render(){ return ( <div className = 'Appe'> <h1 style = {this.styles}></h1> </div> ); } } export default Nav;
b1f17f31e73597af3a04b9f5735b9f03917780b1
[ "JavaScript" ]
2
JavaScript
APPLESHOTTIPS/REACTFORMVALIDATIONS
377f524587167da799042536afe001992c288601
7145b02de3bc18337b8a2d5a0cc27865007437c6
refs/heads/master
<repo_name>paulmassen/volumio_rfid<file_sep>/README.md # volumio_rfid Volumio &amp; RFID via ESP8266 ## Usage <file_sep>/volumio.ino #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <SPI.h> #include <MFRC522.h> const char* ssid = "MYSSID"; const char* password = "<PASSWORD>"; //This is for a Wemos D1 Mini #define RSTPIN D1 #define SSPIN D2 // Pin usage for MFRC5522 MFRC522 rc(SSPIN, RSTPIN); int readsuccess; /* the following are the UIDs of the card which are authorised to know the UID of your card/tag use the example code 'DumpInfo', from the library mfrc522 it give the UID of the card as well as other information in the card on the serial monitor of the arduino alternatively, this sketch will output the code in the serial monitor */ //byte defcard[4]={0x32,0xD7,0x0F,0x2B}; // if you only want one card byte defcard[][4] = {{0x4, 0xDE, 0xC6, 0xFA}, {0x4, 0xDA, 0xC6, 0xFA}, {0x4, 0xE1, 0xC7, 0xFA},{0x4, 0x85, 0x77, 0xFA}, {0x4, 0xE1, 0xC7, 0xFA},{0x4, 0xE6, 0xC7, 0xFA}}; //for multiple cards int N = 6; //change this to the number of cards/tags you will use byte readcard[4]; //stores the UID of current tag which is read int cardNumber; void setup() { Serial.begin(9600); // Connecting to Wifi WiFi.begin(ssid, password); Serial.print("Connecting.."); while (WiFi.status() != WL_CONNECTED) { Serial.print(".."); delay(1000); } // Initialize the MFRC522 SPI.begin(); rc.PCD_Init(); //initialize the receiver rc.PCD_DumpVersionToSerial(); //show details of card reader module // Display list of authorized card Serial.println(F("the authorised cards are")); for (int i = 0; i < N; i++) { Serial.print(i + 1); Serial.print(" "); for (int j = 0; j < 4; j++) { Serial.print(defcard[i][j], HEX); } Serial.println(""); } Serial.println(""); Serial.println(F("Scan RFID Tags to launch volumio")); } void loop() { readsuccess = getid(); if (readsuccess) { int match = 0; // This change to 1 if the tag is in our defcard Array int cardIncr = 0; // Variable to know the location of the uid in the array //this is the part where compare the current tag with pre defined tags for (int i = 0; i < N; i++) { //Serial.print("Testing Against Authorised card no: "); //Serial.println(i+1); cardIncr++; if (memcmp(readcard, defcard[i], 4) == 0) { match = 1; cardNumber = cardIncr; Serial.print("la valeur de cardNumber est"); Serial.println(cardNumber); } else { // Serial.println("no match"); } } if (match) { if (cardNumber == 2) { Serial.println("numero de carte 2"); if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status Serial.println("le wifi est connecte"); HTTPClient http; //Declare an object of class HTTPClient http.begin("http://192.168.1.47/api/v1/commands/?cmd=toggle"); //Specify request destination int httpCode = http.GET(); //Send the request Serial.print("le code http recu est le : "); Serial.println(httpCode); if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); //Print the response payload } http.end(); //Close connection } //delay(30000); //Send a request every 30 seconds } else if (cardNumber == 1) { Serial.println("numero de carte 1 - <NAME>"); if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status Serial.println("le wifi est connecte"); HTTPClient http; //Declare an object of class HTTPClient http.begin("http://192.168.1.47/api/v1/commands/?cmd=playplaylist&name=django"); //Specify request destination int httpCode = http.GET(); //Send the request Serial.print("le code http recu est le : "); Serial.println(httpCode); if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); //Print the response payload } http.end(); //Close connection } } else if (cardNumber == 4) { Serial.println("numero de carte 4 - Polo et Pan"); if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status Serial.println("le wifi est connecte"); HTTPClient http; //Declare an object of class HTTPClient http.begin("http://192.168.1.47/api/v1/commands/?cmd=playplaylist&name=poloetpan"); //Specify request destination int httpCode = http.GET(); //Send the request Serial.print("le code http recu est le : "); Serial.println(httpCode); if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); //Print the response payload } http.end(); //Close connection } } else if (cardNumber == 5) { Serial.println("numero de carte 5 - corsica playlist"); if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status Serial.println("le wifi est connecte"); HTTPClient http; //Declare an object of class HTTPClient http.begin("http://192.168.1.47/api/v1/commands/?cmd=playplaylist&name=corse"); //Specify request destination int httpCode = http.GET(); //Send the request Serial.print("le code http recu est le : "); Serial.println(httpCode); if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); //Print the response payload } http.end(); //Close connection } } else if (cardNumber == 6) { Serial.println("numero de carte 6 - beach playlist"); if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status Serial.println("le wifi est connecte"); HTTPClient http; //Declare an object of class HTTPClient http.begin("http://192.168.1.47/api/v1/commands/?cmd=playplaylist&name=plage"); //Specify request destination int httpCode = http.GET(); //Send the request Serial.print("le code http recu est le : "); Serial.println(httpCode); if (httpCode > 0) { //Check the returning code String payload = http.getString(); //Get the request response payload Serial.println(payload); //Print the response payload } http.end(); //Close connection } } else { Serial.println("pas enregistre"); } } } } //function to get the UID of the card int getid() { if (!rc.PICC_IsNewCardPresent()) { return 0; } if (!rc.PICC_ReadCardSerial()) { return 0; } Serial.println("THE UID OF THE SCANNED CARD IS:"); for (int i = 0; i < 4; i++) { readcard[i] = rc.uid.uidByte[i]; //storing the UID of the tag in readcard Serial.print(readcard[i], HEX); } Serial.println(""); Serial.println("Now Comparing with Authorised cards"); rc.PICC_HaltA(); return 1; }
e33fe031f57a182f3ea7977e724cb2368b82a308
[ "Markdown", "C++" ]
2
Markdown
paulmassen/volumio_rfid
085cbf6cb6a0fa4417844fdd84af8b000bcc326c
2b67cc6e976a81f761b893a94de9b3f455631559
refs/heads/master
<file_sep># symfony-dzien-3-i-4- <file_sep><?php namespace CodersLabBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\HttpFoundation\Request; use CodersLabBundle\Entity\Book; class BookController extends Controller { // dodanie postu do bazy danych /** * @Route("/") */ public function indexAction() { $post = new Post(); $post ->setTitle('sfdsdfdsdf'); $post ->setText("some text"); $em = $this->getDoctrine()->getManager(); $em ->persist($post); $em->flush($post); return $this->render('CodersLabBundle:Default:index.html.twig', array('post'=>$post)); } /** * @Route("/showAll") */ public function showAllAction(){ $repo = $this->getDoctrine()->getRepository("CodersLabBundle:Post"); $posts = $repo->findAll(); return $this->render( 'CodersLabBundle:book:showAll.html.twig', array('posts'=>$posts) ); } // Część C – Praca na modelu // Zadanie C1 – tworzenie książki // Stwórz akcję /newBook, która ma wyświetlać formularz do tworzenia nowej książki. Formularz – póki co – napisz w normalnym HTML. Formularz ma kierować do akcji /createBook. /** * @Route("/newBook") *@Template() */ public function newBookAction() { // return $this->render( // 'CodersLabBundle:views1:newBook.html.twig' // ); return []; } /** * @Route("/createBook", name="createBook") *@Template() */ public function createBookAction(Request $req){ $title = $req->request->get('title'); $desc = $req->request->get('description'); $rating = $req->request->get('rating'); $book= new Book(); $book->setTitle($title); $book->setDescription($desc); $book->setRating($rating); $em = $this->getDoctrine()->getManager(); $em->persist($book); $em->flush(); return ['title' => $title, 'description'=>$desc,'rating'=>$rating]; } } <file_sep>project_model ============= A Symfony project created on April 22, 2017, 9:43 am. <file_sep>book ==== A Symfony project created on April 22, 2017, 11:03 am. <file_sep>projekt_form ============ A Symfony project created on April 23, 2017, 10:01 am.
82484c9b3fe07ea7584b63ffac361f534f22a031
[ "Markdown", "PHP" ]
5
Markdown
ms08/symfony_pModel_pForm
1b4e38354282b7698e44129372eebed4a28734bf
d80c81244366fde284348111baf0838f551598fb
refs/heads/master
<file_sep>import React, {Component} from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import {Link} from 'react-router' import actions from '../../redux/actions' class UserIndex extends Component{ componentDidMount(){ this.props.actions.getUsers(); } render(){ const users = this.props.users.map((user, idx)=>{ return ( <li key={idx}> <p>{user.id}. <Link to={`/users/${user.id}`}>{user.first_name} {user.last_name}</Link></p> </li> ); }); return ( <div> <div> <h1>User Index Component</h1> <button><Link to='/users/new'>Add New User</Link></button> </div> <div> <ul>{users}</ul> </div> </div> ); } } function mapStateToProps(state){ return state; } function mapDispatchToProps(dispatch){ return { actions: bindActionCreators(actions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(UserIndex);<file_sep>import axios from 'axios' import constants from './constants' const {GET_USERS, GET_USER, NEW_USER, EDIT_USER, DELETE_USER} = constants; const BASE_PATH = '/api/users'; const actions = { getUsers(){ const promise = axios.get(BASE_PATH); return { type: GET_USERS, payload: promise }; }, getUser(id){ const promise = axios.get(`${BASE_PATH}/${id}`); return { type: GET_USER, payload: promise } }, newUser(user){ const promise = axios.post(BASE_PATH, {user}); return { type: NEW_USER, payload: promise } }, deleteUser(id){ const promise = axios.delete(`${BASE_PATH}/${id}`); return { type: DELETE_USER, payload: promise } }, editUser(id, user){ const promise = axios.put(`${BASE_PATH}/${id}`, {user}); return { type: EDIT_USER, payload: promise } } }; export default actions<file_sep>import express from 'express' import knex from '../db/knex' const router = express.Router(); router.get('/', (req, res)=>{ knex('users').then(users=>{ res.send(users); }).catch(err=>{ res.send(err); }); }); router.post('/', (req, res)=>{ knex('users').insert(req.body.user, '*').then(([user])=>{ res.send(user); }).catch(err=>{ res.send(err); }); }); router.get('/:id', (req, res)=>{ knex('users').where('id', +req.params.id).first().then(user=>{ knex('robots').where('user_id', +req.params.id).then(robots=>{ res.send(Object.assign({}, user, {robots})); }); }); }); router.put('/:id', (req, res)=>{ knex('users').where('id', +req.params.id).update(req.body.user, '*').then(([user])=>{ res.send(user); }); }); router.delete('/:id', (req, res)=>{ knex('users').where('id', +req.params.id).del().then(()=>{ res.send(req.params.id); }); }); export default router<file_sep>import express from 'express' import bodyParser from 'body-parser' import path from 'path' import routes from './routes/index' import morgan from 'morgan' import webpack from 'webpack' import webpackDevMiddleware from 'webpack-dev-middleware' import webpackHotMiddleware from 'webpack-hot-middleware' const app = express(); const entryPoint = path.resolve('client/index.html'); // using export default adds a default property on object being exported const config = require(path.resolve('webpack/webpack.config')).default; const compiler = webpack(config); const port = process.env.PORT || 2222; const env = process.env.NODE_ENV; app.use(morgan('tiny')); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); if(env !== 'production'){ app.use(webpackDevMiddleware(compiler, { publicPath: config.output.publicPath, stats: { colors: true, chunkModules: false } })); app.use(webpackHotMiddleware(compiler)); } app.use('/api/users', routes.users); app.use('/api/users/:user_id/robots', routes.robots); app.get('/', (req, res)=>{ res.sendFile(entryPoint); }); app.use((req, res, next)=>{ const err = new Error('Not Found'); err.status = 404; next(err); }); app.use((err, req, res)=>{ res.status(err.status || 500); res.end(JSON.stringify({message: err.message, error: {}})); }); app.listen(port, err => { if(err) console.log(err); console.log(`Listening to port ${port}`); });<file_sep>import 'babel-polyfill' import React from 'react' import ReactDOM from 'react-dom' import {Provider} from 'react-redux' import {Router, Route, Redirect, browserHistory} from 'react-router' import RouterComponents from './routes' import configureStore from './src/redux/store' const initialState = {users: []}; const store = configureStore(initialState); ReactDOM.render( <Provider store={store}> {RouterComponents} </Provider> , document.getElementById('root') );<file_sep>import express from 'express' import knex from '../db/knex' const router = express.Router({mergeParams: true}); router.get('/', (req, res)=>{ knex('robots').where('user_id', +req.params.user_id).then(robots=>{ res.send(robots); }); }); router.post('/', (req, res)=>{ knex('robots') .insert(Object.assign({}, req.body.robots, {user_id: +req.params.user_id}), '*') .then(([robot])=>{ res.send(robot); }); }); router.get('/:id', (req, res)=>{ knex('robots').where('id', +req.params.id).first().then(robot=>{ res.send(robot); }); }); router.put('/:id', (req, res)=>{ knex('robots').where('id', +req.params.id).update(req.body.robot, '*').then(([robot])=>{ res.send(robot); }); }); router.delete('/:id', (req, res)=>{ knex('robots').where('id', +req.params.id).del().then(()=>{ res.send('Robot Deleted'); }); }); export default router<file_sep>import validate from 'webpack-validator' import dev from './webpack.dev.config' let config; switch(process.env.npm_lifecycle_event){ case 'dev': config = dev; break; case 'debug': config = dev; break; default: throw 'Invalid Command'; } export default validate(config)<file_sep># React Express Webpack A simple React/Redux example app using RESTful routing, express server, and webpack. Todos: * ~~Add database (resources - user, robots)~~ * ~~Enable es6/es7 on node~~ * ~~Use Redux Promise~~ * ~~Use Proptypes~~ * ~~Use React Router~~ Stretch Goals: * Add styling (sass) * Add tests/continuous integration * Add auth/redux-forms * Add animations * Deploy Resources: * https://react-redux.herokuapp.com/ * https://egghead.io/lessons/node-js-using-es6-and-beyond-with-node-js * http://kurtle.io/2015/11/29/react-redux-webpack-babel.html * http://sheffieldgeeks.org.uk/ * https://www.youtube.com/watch?v=7S8v8jfLb1Q * https://medium.com/@meagle/understanding-87566abcfb7a#.w0e0hl78z * http://exploringjs.com/es6/ch_classes.html<file_sep>import users from '../mock/USERS.json' import robotList from '../mock/ROBOTS.json' export function seed(knex, Promise) { return knex('users').del() .then(() => { return knex('users').insert(users).returning('id'); }) .then(ids => { const list = robotList.reduce((acc, entries, idx) => { entries.robots.forEach(robot => { robot.user_id = ids[idx]; acc.push(robot); }); return acc; }, []); return knex('robots').insert(list); }); }; <file_sep>import React from 'react' import {Router, Route, Redirect, browserHistory} from 'react-router' import App from './src/components/App' import UserIndex from './src/components/users/index' import UserNew from './src/components/users/new' import UserShow from './src/components/users/show' import UserEdit from './src/components/users/edit' // redirect issue: https://github.com/reactjs/react-router/issues/1675 export default ( <Router history={browserHistory}> <Route component={App}> <Route path='users' component={UserIndex}/> <Route path='users/new' component={UserNew}/> <Route path='users/:user_id' component={UserShow}/> <Route path='/users/:user_id/edit' component={UserEdit}/> </Route> <Redirect from='/' to='/users'/> </Router> ); <file_sep>export default { GET_USERS : 'GET_USERS', GET_USER : 'GET_USER', NEW_USER : 'NEW_USER', EDIT_USER : 'EDIT_USER', DELETE_USER : 'DELETE_USER', GET_ROBOTS : 'GET_ROBOTS', GET_ROBOT : 'GET_ROBOT', NEW_ROBOT : 'NEW_ROBOT', EDIT_ROBOT : 'EDIT_ROBOT', DELETE_ROBOT : 'DELETE_ROBOT' }<file_sep>import React, {Component, PropTypes} from 'react' import ReactDOM from 'react-dom' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import {Link, browserHistory} from 'react-router' import actions from '../../redux/actions' class UserNew extends Component{ // static contextTypes = { // router: PropTypes.object // }; constructor(props){ super(props); this.state = { gender: true } } handleSubmit(e){ e.preventDefault(); let first_name = ReactDOM.findDOMNode(this.refs.first).value; let last_name = ReactDOM.findDOMNode(this.refs.last).value; let gender = this.state.gender ? 'Male' : 'Female'; this.props.actions.newUser({first_name, last_name, gender}).then(()=>{ browserHistory.push('/'); }); } handleGenderChange(e){ this.setState({gender: !this.state.gender}); } render(){ return ( <div> <div> <h1>Create New User</h1> <button><Link to='/users'>Go Back</Link></button> </div> <div> <form onSubmit={this.handleSubmit.bind(this)}> <div> <label htmlFor="first_name">First Name: </label> <input ref='first' id='first_name' type="text"/> </div> <div> <label htmlFor="last_name">Last Name: </label> <input ref='last' id='last_name' type="text"/> </div> <div> <label className="form-label">Gender: </label> <label className="form-radio"> <input type="radio" name="gender" onChange={this.handleGenderChange.bind(this)} checked={this.state.gender}/> <i className="form-icon"></i> Male </label> <label className="form-radio"> <input type="radio" name="gender" onChange={this.handleGenderChange.bind(this)} checked={!this.state.gender}/> <i className="form-icon"></i> Female </label> </div> <button>Submit</button> </form> </div> </div> ); } } function mapStateToProps(state){ return state; } function mapDispatchToProps(dispatch, action){ return { actions: bindActionCreators(actions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(UserNew);<file_sep>export function up(knex, Promise) { return knex.schema.createTable('robots', table => { table.increments(); table.integer('user_id').index().notNullable().references('users.id').onDelete('CASCADE'); table.string('name'); table.string('url'); }); }; export function down(knex, Promise) { return knex.schema.dropTable('robots'); }; <file_sep>import users from './users' import robots from './robots' export default {users, robots}
6b02046d9468e908d78a0880822ecfcb86b04ab2
[ "JavaScript", "Markdown" ]
14
JavaScript
kakorcal/react_express_webpack
a073c83bbf65563c663ea852292dc4ccd0d3acb7
051694295aef5aaf35e7b97f6d517707dd9968fe
refs/heads/master
<repo_name>flum1025/Java-Rsa<file_sep>/src/rsasample/RSASample.java package rsasample; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.math.BigInteger; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PublicKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.KeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; public class RSASample { public static void main(String[] args) throws Exception { File keyFile = new File("/Users/flum/desktop/public_key.der"); //javaではpemファイルは扱えないため、derに変換して指定する。 byte[] encodedKey = new byte[(int)keyFile.length()]; FileInputStream in = new FileInputStream(keyFile); in.read(encodedKey); in.close(); X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey); KeyFactory kf = KeyFactory.getInstance("RSA"); PublicKey pubKey = kf.generatePublic(publicKeySpec); Cipher rsa = Cipher.getInstance("RSA"); rsa.init(Cipher.ENCRYPT_MODE, pubKey); String plainTest = "testplaintext"; byte[] plainText = plainTest.getBytes(); byte[] cipherText = rsa.doFinal(plainText); System.out.println(Base64.getEncoder().encodeToString(cipherText)); } }
308b5f0d0fb7544a9978995a42decb928a514d7b
[ "Java" ]
1
Java
flum1025/Java-Rsa
bded662ca282b8f56988376c90d34040194e55cf
85c3c20e847c0baeb7f26900b97500d44be1b370
refs/heads/master
<repo_name>SDEagle/kaheim<file_sep>/db/migrate/20140821101422_remove_public_and_public_until_fields_from_items.rb class RemovePublicAndPublicUntilFieldsFromItems < ActiveRecord::Migration def change remove_column :offers, :public, :boolean remove_column :offers, :public_until, :datetime remove_column :requests, :public, :boolean remove_column :requests, :public_until, :datetime end end <file_sep>/test/controllers/item_reactivation_controller_test.rb require 'test_helper' class ItemReactivationControllerTest < ActionDispatch::IntegrationTest test 'reactivate item' do offer = offers(:roommate_wanted) offer.updated_at = 40.days.ago offer.save reactivator = ItemReactivator.create! item: offer get reactivate_path(token: reactivator.token) offer = Offer.find(offer.id) assert offer.updated_at > 5.minutes.ago end test 'reactivating item confirms item' do offer = offers(:roommate_wanted) offer.updated_at = 40.days.ago offer.save reactivator = ItemReactivator.create! item: offer assert_nil offer.email_confirmed_at get reactivate_path(token: reactivator.token) offer = Offer.find(offer.id) assert offer.updated_at > 5.minutes.ago assert_not_nil offer.email_confirmed_at end end<file_sep>/app/models/item_reactivator.rb class ItemReactivator < ApplicationRecord belongs_to :item, polymorphic: true validates :token, uniqueness: true, presence: true validates_presence_of :item before_validation :generate_token, on: :create protected def generate_token self.token = loop do random_token = SecureRandom.urlsafe_base64(nil, false) break random_token unless ItemReactivator.exists?(token: random_token) end end end <file_sep>/db/migrate/20140722222606_add_public_and_public_until_to_request.rb class AddPublicAndPublicUntilToRequest < ActiveRecord::Migration def change add_column :requests, :public, :boolean add_column :requests, :public_until, :datetime end end <file_sep>/app/controllers/application_controller.rb class ApplicationController < ActionController::Base # Prevent CSRF attacks by ignoring the session protect_from_forgery delegate :tm, to: :view_context before_action :configure_permitted_parameters, if: :devise_controller? before_action :set_locale after_action :store_location def authenticate_admin_user! authenticate_user! unless current_user.admin? flash[:alert] = "Unauthorized Access!" redirect_to root_path end end def store_location if request.path != new_user_session_path && request.path != new_user_registration_path && request.path != new_user_password_path && request.path != edit_user_password_path && request.path != destroy_user_session_path && !request.xhr? # don't store ajax calls store_location_for(:user, request.original_url) end end protected def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:name]) devise_parameter_sanitizer.permit(:account_update, keys: [:name]) end def set_locale I18n.locale = locale_param || I18n.default_locale end def locale_param I18n.available_locales.map(&:to_s).include?(params[:locale]) ? params[:locale] : nil end def default_url_options(options = {}) (I18n.locale == :de) ? options : options.merge(locale: I18n.locale) end def verify_captcha params[:stupid_captcha] == "Maria" end def owner_show_item_path(item) if item.is_a?(Offer) owner_show_offer_path(item, token: item.owner_show_token) elsif item.is_a?(Request) owner_show_request_path(item, token: item.owner_show_token) end end end <file_sep>/app/form_builders/custom_bootstrap_form_builder.rb class CustomBootstrapFormBuilder < BootstrapForm::FormBuilder def prepend_and_append_input(options, &block) options = options.extract!(:prepend, :append, :input_group_wrapper_class) input = capture(&block) input = content_tag(:span, options[:prepend], class: input_group_class(options[:prepend])) + input if options[:prepend] input << content_tag(:span, options[:append], class: input_group_class(options[:append])) if options[:append] input = content_tag(:div, input, class: "input-group #{options[:input_group_wrapper_class]}") unless options.empty? input end def localized_text_field method, options = {} val = object.send(method) options[:value] = @template.l val if val text_field method, options end end<file_sep>/db/migrate/20140717093117_add_fields_to_offer.rb class AddFieldsToOffer < ActiveRecord::Migration def change add_column :offers, :rent, :integer add_column :offers, :size, :integer add_column :offers, :gender, :integer add_column :offers, :from_date, :datetime rename_column :offers, :until, :to_date end end <file_sep>/Gemfile source 'https://rubygems.org' ruby '2.7.2' # Bundle edge Rails instead: gem 'rails', github: 'rails/rails' gem 'rails', '~> 6.0.0' gem 'pg', '~> 1.1' # Use Puma as the app server gem 'puma', '~> 3.0' gem 'bootsnap', '~> 1.4' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails', '~> 5.0' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails', '~> 4.3' # Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks gem 'turbolinks', '~> 5.2' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 2.9' # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', '~> 1.0', group: :doc group :development do # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring gem 'spring', '~> 2.1' gem 'letter_opener', '~> 1.7' gem 'better_errors', '~> 2.5' gem 'binding_of_caller', '~> 0.8' gem 'listen', '~> 3.1' end # Use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.1.2' group :development do # Use Capistrano for deployment gem 'capistrano', '~> 3.11' gem 'capistrano-rails', '~> 1.4' gem 'capistrano-bundler', '~> 1.5' gem 'capistrano3-puma', '~> 3.1' end # Use debugger # gem 'debugger', group: [:development, :test] gem 'bootstrap-sass', '~> 3.4' gem 'autoprefixer-rails', '~> 9.7' gem 'bootstrap_form', '~> 2.7' gem 'bootstrap-datepicker-rails', '~> 1.8' gem 'font-awesome-rails', '~> 4.7' # better links in locales yml. gem 'it' # cool js selects gem 'select2-rails', '~> 4.0' gem 'groupdate', '~> 4.1' gem 'chartkick', '~> 3.0' gem 'actionview-encoded_mail_to', '~> 1.0' gem 'rails_autolink', '~> 1.1' # admin stuff gem 'activeadmin', '~> 2.6' gem 'kaminari-i18n', '~> 0.5' # Authentication with Devise gem 'devise', '~> 4.7' # static pages gem 'high_voltage', '~> 3.1' # cron scheduling gem 'whenever', '~> 0.10', require: false gem 'dotenv-rails', '~> 2.7' group :production do gem 'dkim', '~> 1.0' gem 'exception_notification', '~> 4.4' end gem 'simplecov', '~> 0.16.0', :require => false, :group => :test gem 'capybara', '~> 3.31' gem 'selenium-webdriver', '~> 3.142' <file_sep>/config/routes.rb Rails.application.routes.draw do get 'stats/counts' => 'stats#counts' get 'stats/statistiken' => 'stats#statistics' post 'subscriptions/create' delete 'subscriptions/destroy' get 'subscription/confirm/:confirmation_token' => 'subscriptions#confirm', as: 'subscriptions_confirm' get 'subscription/unsubscribe/:item_type/:unsubscribe_token' => 'subscriptions#destroy', as: 'subscriptions_unsubscribe' delete 'subscription/unsubscribe' => 'subscriptions#unsubscribe_user', as: 'subscriptions_unsubscribe_user' get 'reactivate/:token' => 'item_reactivation#reactivate', as: 'reactivate' get 'welcome/index' ActiveAdmin.routes(self) devise_for :users, :controllers => {confirmations: 'confirmations'} resources :offers do member do put :toggle_active get :owner_show post :request_owner_link end end resources :requests do member do put :toggle_active get :owner_show post :request_owner_link end end resources :answers, only: [:create] # Error handling get '/404' => redirect('/errors/404') get '/422' => redirect('/errors/422') get '/500' => redirect('/errors/500') get '/errors/:error_code', to: 'errors#error' root to: 'welcome#index' end <file_sep>/db/migrate/20140910202041_add_unsubscribe_token_to_subscriptions.rb class AddUnsubscribeTokenToSubscriptions < ActiveRecord::Migration def change add_column :subscriptions, :unsubscribe_token, :string add_index :subscriptions, :unsubscribe_token, unique: true add_index :subscriptions, :confirmation_token add_index :subscriptions, :email add_index :subscriptions, :offers add_index :subscriptions, :requests end end <file_sep>/db/migrate/20170903135929_create_history_items.rb class CreateHistoryItems < ActiveRecord::Migration def change create_table :history_items do |t| t.integer :offers_count t.integer :requests_count t.timestamps null: false end end end <file_sep>/db/migrate/20140910162201_add_gender_default_to_offers_and_requests.rb class AddGenderDefaultToOffersAndRequests < ActiveRecord::Migration def change change_column :offers, :gender, :integer, :default => 0 change_column :requests, :gender, :integer, :default => 0 end end <file_sep>/app/models/answer.rb class Answer < ApplicationRecord validates_presence_of :message, :item, :mail validates_format_of :mail, :with => /\A[^@]+@([^@\.]+\.)+[^@\.]+\z/ belongs_to :item, polymorphic: true end <file_sep>/test/controllers/requests_controller_test.rb require 'test_helper' class RequestsControllerTest < ActionDispatch::IntegrationTest test 'should get index' do get requests_url assert_response :success assert_select 'table.request-specifics', 1 end test 'send notification when request is confirmed' do request = requests(:need_room2) assert_not request.email_confirmed? num_subscribers = Subscription.requests.confirmed.count assert num_subscribers > 0 assert_difference 'ActionMailer::Base.deliveries.size', +num_subscribers do get owner_show_request_url(request, token: request.owner_show_token) end assert request.reload.email_confirmed? end end <file_sep>/app/models/history_item.rb class HistoryItem < ApplicationRecord validates_presence_of :offers_count, :requests_count end <file_sep>/lib/tasks/kaheim.rake namespace :kaheim do desc 'sends out notifications for newly invisible items and deletes items too old' task handle_obsolete: :environment do Offer.outdated.find_each do |offer| handle_obsolete offer end Request.outdated.find_each do |request| handle_obsolete request end end desc 'creates new history item' task create_history_item: :environment do offers_count = Offer.visible_for(nil, Offer).count requests_count = Request.visible_for(nil, Request).count HistoryItem.create({offers_count: offers_count, requests_count: requests_count}) end def handle_obsolete item reactivator = ItemReactivator.find_by item: item if reactivator.nil? reactivator = ItemReactivator.create! item: item ItemMailer.reactivate_item_mail(item, reactivator.token).deliver_now elsif reactivator && reactivator.created_at < 100.days.ago reactivator.destroy item.destroy end end desc 'sends out token mails to existing users' task send_token_mails: :environment do Offer.confirmed.find_each do |offer| send_token_mail offer end Request.confirmed.find_each do |request| send_token_mail request end end def send_token_mail item print "Sending mail to #{item.email}...\n" ItemMailer.send_token_mail(item).deliver_now end end <file_sep>/README.md [![Build Status](https://travis-ci.com/tim3z/kaheim.svg?branch=destroy_all_users)](https://travis-ci.com/tim3z/kaheim) Kaheim ====== This is the software running at [kaheim.de](https://kaheim.de) as a platform for young adults looking for a room in a shared flat in Karlsruhe. It's written using Ruby on Rails. Do you want to improve this platform? Or do you want to start a similar website in your city? Please [contact us](mailto:%74%65%61%6d@%6b%61%68%65%69%6d.%64%65) - we would love to share and work with you! <file_sep>/app/controllers/errors_controller.rb class ErrorsController < ApplicationController def error render params[:error_code].to_s end end <file_sep>/test/system/offers_test.rb require "application_system_test_case" SimpleCov.command_name "test:system" class OffersTest < ApplicationSystemTestCase test "title is shown" do offer = offers(:tworooms) visit offer_url(offer) assert_selector '.title', text: offer.title end end <file_sep>/app/helpers/requests_helper.rb module RequestsHelper def from_date_info request if request.from_date && !request.from_date.past? "#{t 'requests.show.from'} #{l request.from_date}" else t 'requests.show.now' end end end <file_sep>/app/controllers/item_reactivation_controller.rb class ItemReactivationController < ApplicationController def reactivate unless reactivator = ItemReactivator.find_by(token: params[:token]) redirect_to root_path, flash: { error: t('reactivation.bad_token') } return false end reactivator.item.confirm_email! unless reactivator.item.email_confirmed? reactivator.item.touch reactivator.destroy redirect_to owner_show_item_path(reactivator.item), notice: tm('reactivation.success', reactivator.item.class) end end <file_sep>/db/migrate/20140717134103_add_address_fields_to_offer.rb class AddAddressFieldsToOffer < ActiveRecord::Migration def change add_column :offers, :district, :string add_column :offers, :street, :string add_column :offers, :zip_code, :string end end <file_sep>/app/controllers/answers_controller.rb class AnswersController < ApplicationController before_action :block_spam, only: [:create] def create @answer = Answer.new(answer_params) @answer.save or (render_item and return) ItemMailer.answer_mail(@answer).deliver_now ItemMailer.answer_mail_notification(@answer).deliver_now redirect_to @answer.item, notice: t('answers.success') end private # Never trust parameters from the scary internet, only allow the white list through. def answer_params params[:answer].permit(:message, :mail, :item_id, :item_type) end def block_spam unless (user_signed_in? && current_user.confirmed?) || verify_captcha flash[:error] = t('captcha.errors.verification_failed') render_item end end def render_item @answer ||= Answer.new(answer_params) if @answer.item_type == Request.to_s @request = @answer.item render 'requests/show' elsif @answer.item_type == Offer.to_s @offer = @answer.item render 'offers/show' else redirect_back(fallback_location: root_path, flash: { error: 'Invalid params' }) end end end <file_sep>/app/helpers/pages_helper.rb module PagesHelper COST_PER_MONTH = 5 def current_balance(last_balance, last_update) last_update_months_ago = (Time.now.year * 12 + Time.now.month) - (last_update.year * 12 + last_update.month) last_balance - COST_PER_MONTH * last_update_months_ago end def end_of_balance_date(last_balance, last_update) last_update + (last_balance / COST_PER_MONTH).months end end <file_sep>/app/models/subscription.rb class Subscription < ApplicationRecord include CreationSpamCheck validates :email, presence: true, uniqueness: { case_sensitive: false }, format: { with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/ } validates :confirmation_token, uniqueness: { allow_blank: true, allow_nil: true } validates :unsubscribe_token, uniqueness: true before_validation :generate_tokens!, on: :create scope :confirmed, -> { where(confirmation_token: [nil, '']) } scope :offers, -> { where(offers: true) } scope :requests, -> { where(requests: true) } def generate_tokens! self.confirmation_token = loop do random_token = SecureRandom.urlsafe_base64(nil, false) Subscription.unscoped.exists?(confirmation_token: random_token) or break random_token end self.unsubscribe_token = loop do random_token = SecureRandom.urlsafe_base64(nil, false) Subscription.unscoped.exists?(unsubscribe_token: random_token) or break random_token end end def confirmed? confirmation_token.blank? end def confirm! update!(confirmation_token: nil) end def subscribed_types return 'all' if offers? && requests? return 'requests' if requests? return 'offers' if offers? nil end end <file_sep>/app/controllers/stats_controller.rb class StatsController < ApplicationController def counts counts = { offers: Offer.visible_for(current_user, Offer).count, requests: Request.visible_for(current_user, Request).count } render json: counts.to_json end def statistics end end <file_sep>/test/controllers/offers_controller_test.rb require 'test_helper' class OffersControllerTest < ActionDispatch::IntegrationTest test 'should get index' do get offers_url assert_response :success assert_select 'table.offer-specifics', 1 end test 'unlocking offer sends notifications to subscribers' do offer = offers(:roommate_wanted) assert_not offer.email_confirmed? num_subscribers = Subscription.offers.confirmed.count assert num_subscribers > 0 assert_difference 'ActionMailer::Base.deliveries.size', +num_subscribers do get owner_show_offer_url(offer, token: offer.owner_show_token) end assert offer.reload.email_confirmed? end end <file_sep>/app/controllers/subscriptions_controller.rb class SubscriptionsController < ApplicationController before_action :check_offers_or_requests, only: [:create] before_action :authenticate_user!, only: [:unsubscribe_user] def create @subscription = Subscription.find_or_create_by(email: subscription_params[:email]) @subscription.no_spam = subscription_params[:no_spam] @subscription.offers = true if subscription_params[:offers] == 'true' @subscription.requests = true if subscription_params[:requests] == 'true' if @subscription.changed? unless @subscription.save redirect_back(fallback_location: root_path, flash: { error: t('subscriptions.subscribe.error_save') + ' ' + @subscription.errors.full_messages.join('. ') + '.'}) return end if @subscription.confirmed? SubscriptionMailer.subscribe_notification(@subscription).deliver_now unless user_signed_in? redirect_back(fallback_location: root_path, notice: t('subscriptions.subscribe.success.confirmed')) return end end if user_signed_in? && current_user.email == @subscription.email if current_user.confirmed? @subscription.confirm! redirect_back(fallback_location: root_path) else redirect_back(fallback_location: root_path, notice: t('subscriptions.subscribe.success.unconfirmed_user')) end elsif @subscription.confirmed? redirect_back(fallback_location: root_path, flash: { error: t('subscriptions.subscribe.error_existing')}) else SubscriptionMailer.confirmation_request(@subscription).deliver_now redirect_back(fallback_location: root_path, notice: t('subscriptions.subscribe.success.unconfirmed')) end end def unsubscribe_user @subscription = Subscription.find_by_email(current_user.email) unless @subscription redirect_back(fallback_location: root_path, flash: { error: t('subscriptions.unsubscribe.not_subscribed')}) return end @subscription.offers = false if subscription_params[:offers] == 'true' @subscription.requests = false if subscription_params[:requests] == 'true' if @subscription.offers || @subscription.requests @subscription.save! if @subscription.changed? else @subscription.destroy end redirect_back(fallback_location: root_path) end def destroy @subscription = Subscription.find_by_unsubscribe_token(params[:unsubscribe_token]) unless @subscription redirect_to root_path, flash: { error: t('subscriptions.unsubscribe.bad_token')} return end case params[:item_type] when 'offers' @subscription.offers = false when 'requests' @subscription.requests = false when 'all' @subscription.offers = false @subscription.requests = false else redirect_to root_path, flash: { error: t('subscriptions.unsubscribe.bad_item_type')} return end if @subscription.offers || @subscription.requests @subscription.save! if @subscription.changed? else @subscription.destroy end unless user_signed_in? SubscriptionMailer.unsubscribe_notification(@subscription).deliver_now end redirect_to root_path, notice: t('subscriptions.unsubscribe.success') end def confirm @subscription = Subscription.find_by(confirmation_token: params[:confirmation_token]) @subscription or return redirect_to root_path, flash: { error: t('subscriptions.activation.bad_token') } @subscription.confirm! redirect_to root_path, notice: t('subscriptions.activation.success') end private # Never trust parameters from the scary internet, only allow the white list through. def subscription_params params[:subscription].permit(:email, :offers, :requests, :no_spam) end def check_offers_or_requests unless subscription_params[:offers] == 'true' || subscription_params[:requests] == 'true' redirect_back(fallback_location: root_path, flash: { error: t('subscriptions.subscribe.nothing_selected')}) end end end <file_sep>/app/models/offer.rb class Offer < ApplicationRecord include Item validates_presence_of :title, :description, :from_date, :rent, :size, :gender, :street, :zip_code validates_length_of :title, maximum: 140 enum gender: { dontcare: 0, female: 1, male: 2 } end <file_sep>/test/controllers/subscriptions_controller_test.rb require 'test_helper' class SubscriptionsControllerTest < ActionDispatch::IntegrationTest test 'subscribe offers with non user' do email_address = '<EMAIL>' assert_difference 'ActionMailer::Base.deliveries.size', +1 do post subscriptions_create_path, params: {subscription: { email: email_address, offers: 'true', no_spam: 1 }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.success.unconfirmed'), flash[:notice] confirm_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.confirmation_request.subject'), confirm_email.subject assert_equal email_address, confirm_email.to[0] assert_match(/.*Um deine E-Mail-Adresse zu bestätigen.*/, confirm_email.body.to_s) subscription = Subscription.find_by_email(email_address) assert subscription.offers assert_not subscription.requests assert_not subscription.confirmed? end test 'subscribe offers with invalid email address' do email_address = 'donald.duck(at)duckburg.com' assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: email_address, offers: 'true', no_spam: 1 }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_match(/#{I18n.t('subscriptions.subscribe.error_save')}.*/, flash[:error]) subscription = Subscription.find_by_email(email_address) assert_nil subscription end test 'do not create subscription if spam prevention is missing' do email_address = '<EMAIL>' assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: email_address, offers: 'true' }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' end test 'confirm offer subscriber' do subscription = subscriptions(:offer_subscriber_unconfirmed) assert_no_difference 'ActionMailer::Base.deliveries.size' do get subscriptions_confirm_path(confirmation_token: subscription.confirmation_token) end assert_redirected_to root_path assert_equal I18n.t('subscriptions.activation.success'), flash[:notice] subscription = Subscription.find_by_email(subscription.email) assert subscription.confirmed? end test 'confirm request subscriber' do subscription = subscriptions(:request_subscriber_unconfirmed) assert_no_difference 'ActionMailer::Base.deliveries.size' do get subscriptions_confirm_path(confirmation_token: subscription.confirmation_token) end assert_redirected_to root_path assert_equal I18n.t('subscriptions.activation.success'), flash[:notice] subscription = Subscription.find_by_email(subscription.email) assert subscription.confirmed? end test 'confirm everything subscriber' do subscription = subscriptions(:everything_subscriber_unconfirmed) assert_no_difference 'ActionMailer::Base.deliveries.size' do get subscriptions_confirm_path(confirmation_token: subscription.confirmation_token) end assert_redirected_to root_path assert_equal I18n.t('subscriptions.activation.success'), flash[:notice] subscription = Subscription.find_by_email(subscription.email) assert subscription.confirmed? end test 'subscribe requests when offers already subscribed and confirmed' do subscriber = subscriptions(:offer_subscriber) assert_difference 'ActionMailer::Base.deliveries.size', +1 do post subscriptions_create_path, params: {subscription: { email: subscriber.email, requests: 'true', no_spam: 1 }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.success.confirmed'), flash[:notice] subscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.subscribe_notification.subject'), subscribe_email.subject assert_equal subscriber.email, subscribe_email.to[0] assert_match(/.*dein Abonnement für neue Angebote und Gesuche auf Kaheim ist jetzt aktiv.*/, subscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert subscription.requests assert subscription.offers end test 'subscribe requests when offers already subscribed but not confirmed' do subscriber = subscriptions(:offer_subscriber_unconfirmed) assert_not subscriber.confirmed? assert_difference 'ActionMailer::Base.deliveries.size', +1 do post subscriptions_create_path, params: {subscription: { email: subscriber.email, requests: 'true', no_spam: 1 }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.success.unconfirmed'), flash[:notice] subscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.confirmation_request.subject'), subscribe_email.subject assert_equal subscriber.email, subscribe_email.to[0] assert_match(/.*Um deine E-Mail-Adresse zu bestätigen.*/, subscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert subscription.requests assert subscription.offers end test 'subscribe offers when requests already subscribed and confirmed' do subscriber = subscriptions(:request_subscriber) assert_difference 'ActionMailer::Base.deliveries.size', +1 do post subscriptions_create_path, params: {subscription: { email: subscriber.email, offers: 'true', no_spam: 1 }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.success.confirmed'), flash[:notice] subscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.subscribe_notification.subject'), subscribe_email.subject assert_equal subscriber.email, subscribe_email.to[0] assert_match(/.*dein Abonnement für neue Angebote und Gesuche auf Kaheim ist jetzt aktiv.*/, subscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert subscription.offers assert subscription.requests end test 'error message when subscribing offers and offers already subscribed and confirmed' do subscriber = subscriptions(:offer_subscriber) assert subscriber.offers assert_not subscriber.requests assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: subscriber.email, offers: 'true', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.error_existing'), flash[:error] subscription = Subscription.find_by_email(subscriber.email) assert subscription.offers assert_not subscription.requests end test 'error message when subscribing offers and offers and requests already subscribed and confirmed' do subscriber = subscriptions(:everything_subscriber) assert subscriber.offers assert subscriber.requests assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: subscriber.email, offers: 'true', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.error_existing'), flash[:error] subscription = Subscription.find_by_email(subscriber.email) assert subscription.offers assert subscription.requests end test 'subscribe offers for confirmed user without existing subscriptions and user is signed in' do user = users(:david) subscription = Subscription.find_by_email(user.email) assert_nil subscription sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: user.email, offers: 'true', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_nil flash[:notice] assert_nil flash[:error] subscription = Subscription.find_by_email(user.email) assert subscription.offers assert_not subscription.requests assert subscription.confirmed? end test 'subscribe offers for confirmed user without existing subscriptions and user is not signed in' do user = users(:david) subscription = Subscription.find_by_email(user.email) assert_nil subscription assert_difference 'ActionMailer::Base.deliveries.size', +1 do post subscriptions_create_path, params: {subscription: { email: user.email, offers: 'true', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.success.unconfirmed'), flash[:notice] confirm_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.confirmation_request.subject'), confirm_email.subject assert_equal user.email, confirm_email.to[0] assert_match(/.*Um deine E-Mail-Adresse zu bestätigen.*/, confirm_email.body.to_s) subscription = Subscription.find_by_email(user.email) assert subscription.offers assert_not subscription.requests assert_not subscription.confirmed? end test 'subscribe offers for unconfirmed user without existing subscriptions and user is signed in' do user = users(:tina) subscription = Subscription.find_by_email(user.email) assert_nil subscription sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: user.email, offers: 'true', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.success.unconfirmed_user'), flash[:notice] assert_nil flash[:error] subscription = Subscription.find_by_email(user.email) assert subscription.offers assert_not subscription.requests assert_not subscription.confirmed? end test 'subscribe nothing for existing user without existing subscriptions and user is signed in' do user = users(:david) subscription = Subscription.find_by_email(user.email) assert_nil subscription sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: user.email, offers: 'no', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.nothing_selected'), flash[:error] subscription = Subscription.find_by_email(user.email) assert_nil subscription end test 'subscribe nothing for existing user without existing subscriptions and user is not signed in' do user = users(:david) subscription = Subscription.find_by_email(user.email) assert_nil subscription assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: user.email, offers: 'no', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.nothing_selected'), flash[:error] subscription = Subscription.find_by_email(user.email) assert_nil subscription end test 'subscribe nothing for everything subscriber' do subscriber = subscriptions(:everything_subscriber) assert subscriber.offers assert subscriber.requests assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: subscriber.email, offers: 'no', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.nothing_selected'), flash[:error] subscription = Subscription.find_by_email(subscriber.email) assert subscription.offers assert subscription.requests end test 'subscribe offers for existing user with requests subscribed and user is signed in' do user = users(:request_subscriber) subscription = Subscription.find_by_email(user.email) assert_not subscription.offers assert subscription.requests sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do post subscriptions_create_path, params: {subscription: { email: user.email, offers: 'true', no_spam: 1}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_equal I18n.t('subscriptions.subscribe.success.confirmed'), flash[:notice] subscription = Subscription.find_by_email(user.email) assert subscription.offers assert subscription.requests end # ==================== Unsubscribe User ==================== # ========== user signed in ========== test 'unsubscribe everything user from offers when signed in' do user = users(:everything_subscriber) subscription = Subscription.find_by_email(user.email) assert subscription.offers assert subscription.requests sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_unsubscribe_user_path, params: {subscription: { offers: 'true'}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_nil flash[:notice] assert_nil flash[:error] subscription = Subscription.find_by_email(user.email) assert_not subscription.offers assert subscription.requests end test 'unsubscribe everything user from requests when signed in' do user = users(:everything_subscriber) subscription = Subscription.find_by_email(user.email) assert subscription.offers assert subscription.requests sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_unsubscribe_user_path, params: {subscription: { requests: 'true'}}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_nil flash[:notice] assert_nil flash[:error] subscription = Subscription.find_by_email(user.email) assert subscription.offers assert_not subscription.requests end test 'unsubscribe offer user from offers when signed in' do user = users(:offer_subscriber) subscription = Subscription.find_by_email(user.email) assert subscription.offers assert_not subscription.requests sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_unsubscribe_user_path, params: {subscription: { offers: 'true' }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_nil flash[:notice] assert_nil flash[:error] subscription = Subscription.find_by_email(user.email) assert_nil subscription end test 'unsubscribe request user from requests when signed in' do user = users(:request_subscriber) subscription = Subscription.find_by_email(user.email) assert_not subscription.offers assert subscription.requests sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_unsubscribe_user_path, params: {subscription: { requests: 'true' }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_nil flash[:notice] assert_nil flash[:error] subscription = Subscription.find_by_email(user.email) assert_nil subscription end test 'unsubscribe not subscribed user when signed in' do user = users(:david) subscription = Subscription.find_by_email(user.email) assert_nil subscription sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_unsubscribe_user_path, params: {subscription: { offers: 'true' }}, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to 'localhost' assert_nil flash[:notice] assert_equal I18n.t('subscriptions.unsubscribe.not_subscribed'), flash[:error] end test 'unsubscribe offer user by token when signed in' do user = users(:offer_subscriber) subscription = Subscription.find_by_email(user.email) assert subscription.offers assert_not subscription.requests sign_in(user) assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_destroy_path, params: {unsubscribe_token: subscription.unsubscribe_token, item_type: 'offers' }, headers: {'HTTP_REFERER': 'localhost'} end assert_redirected_to root_path assert_nil flash[:error] assert_equal I18n.t('subscriptions.unsubscribe.success'), flash[:notice] subscription = Subscription.find_by_email(user.email) assert_nil subscription end # ========== user not signed in ========== test 'unsubscribe everything user from offers when not signed in' do subscriber = subscriptions(:everything_subscriber) assert subscriber.offers assert subscriber.requests assert_difference 'ActionMailer::Base.deliveries.size', +1 do delete subscriptions_destroy_path, params: {unsubscribe_token: subscriber.unsubscribe_token, item_type: 'offers' } end assert_redirected_to root_path assert_equal I18n.t('subscriptions.unsubscribe.success'), flash[:notice] assert_nil flash[:error] unsubscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.unsubscribe_notification.subject'), unsubscribe_email.subject assert_equal subscriber.email, unsubscribe_email.to[0] assert_match(/.*Benachrichtigungen über neue Gesuche erhältst.*/, unsubscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert_not subscription.offers assert subscription.requests end test 'unsubscribe everything user from requests when not signed in' do subscriber = subscriptions(:everything_subscriber) assert subscriber.offers assert subscriber.requests assert_difference 'ActionMailer::Base.deliveries.size', +1 do delete subscriptions_destroy_path, params: {unsubscribe_token: subscriber.unsubscribe_token, item_type: 'requests' } end assert_redirected_to root_path assert_equal I18n.t('subscriptions.unsubscribe.success'), flash[:notice] assert_nil flash[:error] unsubscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.unsubscribe_notification.subject'), unsubscribe_email.subject assert_equal subscriber.email, unsubscribe_email.to[0] assert_match(/.*Benachrichtigungen über neue Angebote erhältst.*/, unsubscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert_not subscription.requests assert subscription.offers end test 'unsubscribe everything user from offers and requests when not signed in' do subscriber = subscriptions(:everything_subscriber) assert subscriber.offers assert subscriber.requests assert_difference 'ActionMailer::Base.deliveries.size', +1 do delete subscriptions_destroy_path, params: {unsubscribe_token: subscriber.unsubscribe_token, item_type: 'all' } end assert_redirected_to root_path assert_equal I18n.t('subscriptions.unsubscribe.success'), flash[:notice] assert_nil flash[:error] unsubscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.unsubscribe_notification.subject'), unsubscribe_email.subject assert_equal subscriber.email, unsubscribe_email.to[0] assert_match(/.*erhältst in Zukunft keine Benachrichtigungen über neue Einträge.*/, unsubscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert_nil subscription end test 'unsubscribe offer user from offers when not signed in' do subscriber = subscriptions(:offer_subscriber) assert subscriber.offers assert_difference 'ActionMailer::Base.deliveries.size', +1 do delete subscriptions_destroy_path, params: {unsubscribe_token: subscriber.unsubscribe_token, item_type: 'offers' } end assert_redirected_to root_path assert_equal I18n.t('subscriptions.unsubscribe.success'), flash[:notice] assert_nil flash[:error] unsubscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.unsubscribe_notification.subject'), unsubscribe_email.subject assert_equal subscriber.email, unsubscribe_email.to[0] assert_match(/.*erhältst in Zukunft keine Benachrichtigungen über neue Einträge.*/, unsubscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert_nil subscription end test 'unsubscribe request user from requests when not signed in' do subscriber = subscriptions(:request_subscriber) assert subscriber.requests assert_difference 'ActionMailer::Base.deliveries.size', +1 do delete subscriptions_destroy_path, params: {unsubscribe_token: subscriber.unsubscribe_token, item_type: 'requests' } end assert_redirected_to root_path assert_equal I18n.t('subscriptions.unsubscribe.success'), flash[:notice] assert_nil flash[:error] unsubscribe_email = ActionMailer::Base.deliveries.last assert_equal '[Kaheim] ' + I18n.t('subscription_mailer.unsubscribe_notification.subject'), unsubscribe_email.subject assert_equal subscriber.email, unsubscribe_email.to[0] assert_match(/.*erhältst in Zukunft keine Benachrichtigungen über neue Einträge.*/, unsubscribe_email.body.to_s) subscription = Subscription.find_by_email(subscriber.email) assert_nil subscription end test 'unsubscribe user with bad token when not signed in' do assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_destroy_path, params: {unsubscribe_token: '<KEY>', item_type: 'requests' } end assert_redirected_to root_path assert_equal I18n.t('subscriptions.unsubscribe.bad_token'), flash[:error] assert_nil flash[:notice] end test 'unsubscribe everything user from invalid item type when not signed in' do subscriber = subscriptions(:everything_subscriber) assert subscriber.offers assert subscriber.requests assert_no_difference 'ActionMailer::Base.deliveries.size' do delete subscriptions_destroy_path, params: {unsubscribe_token: subscriber.unsubscribe_token, item_type: 'foobar' } end assert_redirected_to root_path assert_equal I18n.t('subscriptions.unsubscribe.bad_item_type'), flash[:error] assert_nil flash[:notice] subscription = Subscription.find_by_email(subscriber.email) assert subscription.offers assert subscription.requests end end <file_sep>/app/mailers/subscription_mailer.rb class SubscriptionMailer < ActionMailer::Base default from: "Kaheim <<EMAIL>>" def confirmation_request subscription @subscription = subscription mail to: subscription.email, subject: default_i18n_subject end def unsubscribe_notification subscription @subscription = subscription mail to: subscription.email, subject: default_i18n_subject end def subscribe_notification subscription @subscription = subscription mail to: subscription.email, subject: default_i18n_subject end def new_item_notification item, subscriber @item = item @subscriber = subscriber mail to:subscriber.email, subject: default_i18n_subject end end <file_sep>/app/admin/dashboard.rb ActiveAdmin.register_page "Dashboard" do menu priority: 1, label: proc{ I18n.t('active_admin.dashboard.title') } content title: proc{ I18n.t('active_admin.dashboard.title') } do columns do column do panel I18n.t('active_admin.dashboard.active_items') do h6 I18n.t('activerecord.models.offer.other') table_for(Offer.current) do column :title column :description column I18n.t('active_admin.actions.title') do |offer| link_to(I18n.t('active_admin.actions.show'), offer) + ' ' + link_to(offer.blocked ? 'Freischalten' : 'Sperren', offer.blocked ? unblock_admin_offer_path(offer) : block_admin_offer_path(offer), method: :put) + ' ' + link_to(I18n.t('items.request_edit_link.send_link_again'), request_owner_link_offer_path(offer, email: offer.email), method: :post) + ' ' + link_to(I18n.t('active_admin.actions.show_in_admin_panel'), admin_offer_path(offer)) end end h6 I18n.t('activerecord.models.request.other') table_for(Request.current) do column :title column :description column I18n.t('active_admin.actions.title') do |request| link_to(I18n.t('active_admin.actions.show'), request) + ' ' + link_to(request.blocked ? 'Freischalten' : 'Sperren', request.blocked ? unblock_admin_request_path(request) : block_admin_request_path(request), method: :put) + ' ' + link_to(I18n.t('items.request_edit_link.send_link_again'), request_owner_link_request_path(request, email: request.email), method: :post) + ' ' + link_to(I18n.t('active_admin.actions.show_in_admin_panel'), admin_request_path(request)) end end end end end end end <file_sep>/app/helpers/items_helper.rb module ItemsHelper def badges_for item result = '' result << content_tag(:span, t('helpers.hidden'), class: 'label label-default') << ' ' unless item.is_public? result << content_tag(:span, t('items.outdated'), class: 'label label-danger') << ' ' if item.outdated? result << content_tag(:span, t('items.unconfirmed'), class: 'label label-danger') << ' ' unless item.email_confirmed_at result.html_safe end def gender_icon gender case gender when 'female' content_tag(:i, '', class: 'fa fa-female') when 'male' content_tag(:i, '', class: 'fa fa-male') else content_tag :span, content_tag(:i, '', class: 'fa fa-female') + '/' + content_tag(:i, '', class: 'fa fa-male'), class: 'dontcare' end end def gender_select value content_tag(:button, id: 'gender-select-button', type: 'button', class: 'btn btn-default dropdown-toggle', 'data-toggle' => 'dropdown') do gender_icon(value) << ' ' << content_tag(:span, '', class: 'caret') end << content_tag(:ul, class: 'dropdown-menu dropdown-menu-auto', role: 'menu', 'data-no-turbolink' => true) do %w(female male dontcare).map do |gender| content_tag(:li, class: 'gender-select-item', 'data-gender' => gender) do link_to '#' do content_tag :span, class: 'gender-label' do gender_icon gender end end end end.join.html_safe end end end <file_sep>/db/migrate/20190525104015_remove_users_from_items.rb class RemoveUsersFromItems < ActiveRecord::Migration[6.0] class Offer < ApplicationRecord belongs_to :user end class Request < ApplicationRecord belongs_to :user end def change add_column :offers, :owner_name, :string add_column :requests, :owner_name, :string add_column :offers, :email, :string add_column :requests, :email, :string add_column :offers, :blocked, :boolean, default: false, null: false add_column :requests, :blocked, :boolean, default: false, null: false add_column :offers, :email_confirmed_at, :datetime add_column :requests, :email_confirmed_at, :datetime reversible do |dir| dir.up do [Offer, Request].each do |item_class| item_class.all.each do |item| item.owner_name = item.user.name item.email = item.user.email item.email_confirmed_at = item.user.confirmed_at item.blocked = true unless item.user.unlocked item.save!(touch: false) end end end dir.down do puts '😢' raise ActiveRecord::IrreversibleMigration end end change_column_null :offers, :owner_name, false change_column_null :requests, :owner_name, false change_column_null :offers, :email, false change_column_null :requests, :email, false remove_column :offers, :user_id, :integer, null: false, default: 0 remove_column :requests, :user_id, :integer, null: false, default: 0 end end <file_sep>/config/initializers/before_dkim_email_subject_prefixer.rb class PrefixEmailSubject def self.delivering_email(mail) mail.subject = "[Kaheim] " + mail.subject end end ActionMailer::Base.register_interceptor(PrefixEmailSubject)<file_sep>/app/helpers/subscriptions_helper.rb module SubscriptionsHelper def user_subscribed(user, item_type) subscription = Subscription.find_by_email(user.email) or return false case item_type when :requests return subscription.requests when :offers return subscription.offers else return false end end end <file_sep>/test/models/subscription_test.rb require 'test_helper' class SubscriptionTest < ActiveSupport::TestCase test 'confirm! confirmes' do subscription = subscriptions(:unconfirmed) subscription.confirm! assert subscription.confirmed? end test 'confirmed if token is nil' do subscription = Subscription.create({email: '<EMAIL>'}) subscription.confirmation_token = nil assert subscription.confirmed? end test 'not confirmed if token is not empty' do subscription = Subscription.create({email: '<EMAIL>'}) subscription.confirmation_token = '123' assert_not subscription.confirmed? end test 'not confirmed if just created' do subscription = Subscription.create({email: '<EMAIL>'}) assert_not subscription.confirmed? end test 'unsubscribe token is generated' do subscription = Subscription.create({email: '<EMAIL>'}) assert_not_empty subscription.unsubscribe_token end test 'cannot save second subscription with same unsubscribe token' do subscription1 = Subscription.create({email: '<EMAIL>'}) subscription2 = Subscription.create({email: '<EMAIL>'}) subscription2.unsubscribe_token = subscription1.unsubscribe_token assert_not subscription2.save end test 'user without confirmation token is confirmed' do subscriber = subscriptions(:offer_subscriber) assert subscriber.confirmed? end end<file_sep>/app/controllers/users_controller.rb class UsersController < ApplicationController before_action :authenticate_user! before_action :authenticate_admin_user!, only: [:locked] end <file_sep>/app/controllers/welcome_controller.rb class WelcomeController < ApplicationController def index @offers = Offer.visible_for(current_user, Offer).order(from_date: :asc, updated_at: :desc) @requests = Request.visible_for(current_user, Request).order(Arel.sql('from_date IS NOT NULL, from_date ASC'), updated_at: :desc) end end <file_sep>/db/migrate/20150629215516_change_active_to_is_public.rb class ChangeActiveToIsPublic < ActiveRecord::Migration def change rename_column :offers, :active, :is_public rename_column :requests, :active, :is_public end end <file_sep>/db/migrate/20140906172601_create_subscriptions.rb class CreateSubscriptions < ActiveRecord::Migration def change create_table :subscriptions do |t| t.string :email, unique: true t.boolean :offers, default: false t.boolean :requests, default: false t.string :confirmation_token t.timestamps end end end <file_sep>/test/models/offer_test.rb require 'test_helper' class OfferTest < ActiveSupport::TestCase default_values = {title: 'Title', description: 'Description', from_date: '01-01-1970', rent: 250, size: 14, gender: 0, street: 'Street', zip_code: '12394', owner_name: 'Owner', email: '<EMAIL>'} test 'default_values work' do offer = Offer.new(default_values) offer.save! end test 'must have title' do offer = Offer.new(default_values.except(:title)) assert_not offer.save end test 'must have description' do offer = Offer.new(default_values.except(:description)) assert_not offer.save end test 'must have from_date' do offer = Offer.new(default_values.except(:from_date)) assert_not offer.save end test 'must have size' do offer = Offer.new(default_values.except(:size)) assert_not offer.save end test 'must have gender' do offer = Offer.new(default_values) offer.gender = nil assert_not offer.save end test 'must have street' do offer = Offer.new(default_values.except(:street)) assert_not offer.save end test 'must have zip_code' do offer = Offer.new(default_values.except(:zip_code)) assert_not offer.save end test 'must have owner_name' do offer = Offer.new(default_values.except(:owner_name)) assert_not offer.save end test 'must have email' do offer = Offer.new(default_values.except(:email)) assert_not offer.save end test 'title can have 140 characters' do offer = Offer.new(default_values.except(:title)) offer.title = 'a' * 140 assert offer.save end test "title can't be longer than 140 characters" do offer = Offer.new(default_values.except(:title)) offer.title = 'a' * 141 assert_not offer.save end end<file_sep>/db/migrate/20140723114813_change_from_date_format_in_offers.rb class ChangeFromDateFormatInOffers < ActiveRecord::Migration def change change_column :offers, :from_date, :date end end <file_sep>/app/helpers/application_helper.rb module ApplicationHelper def translate_with_model(key, model, options = {}) model = model.class unless model.class == Class options[:model] = model.model_name.human(count: options[:count] || 1) translate key, options end alias :tm :translate_with_model def custom_bootstrap_form_for object, options = {}, &block options[:builder] = CustomBootstrapFormBuilder bootstrap_form_for object, options, &block end end <file_sep>/app/mailers/item_mailer.rb class ItemMailer < ActionMailer::Base default from: "Kaheim <<EMAIL>>" def item_creation_mail item @item = item mail to: item.email, subject: default_i18n_subject(item_type: item.class.model_name.human) end def item_edit_link_mail item @item = item mail to: item.email, subject: default_i18n_subject(item_type: item.class.model_name.human) end def reactivate_item_mail item, token @item = item @token = token mail to: item.email end def answer_mail answer @content = answer.message @item = answer.item mail to: answer.item.email, subject: default_i18n_subject(title: answer.item.title), reply_to: answer.mail end def answer_mail_notification answer @content = answer.message @item = answer.item mail to: answer.mail, subject: default_i18n_subject end def admin_notice_mail item, admin @item = item mail to: admin.email, subject: default_i18n_subject end def send_token_mail item @item = item mail from: "<EMAIL>", to: item.email, subject: default_i18n_subject(item_type: item.class.model_name.human) end end <file_sep>/app/controllers/offers_controller.rb class OffersController < ApplicationController before_action :set_editable_offer, only: [:edit, :update, :destroy, :toggle_active, :owner_show] def index @offers = Offer.visible_for(current_user, Offer).order(from_date: :asc, updated_at: :desc) end def show @offer = Offer.visible_for(current_user, Offer).find_by(id: params[:id]) unless @offer redirect_to root_path, flash: { error: t('items.no_access') } end end def owner_show unless @offer.email_confirmed? @offer.confirm_email! Subscription.offers.confirmed.each do |subscriber| SubscriptionMailer.new_item_notification(@offer, subscriber).deliver_now end flash.now[:notice] = tm('helpers.email_verified', @offer) end render :owner_show end def new @offer = Offer.new end def edit end def create @offer = Offer.new(offer_params) if @offer.save ItemMailer.item_creation_mail(@offer).deliver_now User.admin.find_each do |admin| ItemMailer.admin_notice_mail(@offer, admin).deliver_now end @item = @offer render 'pages/item_created' else render action: 'new' end end def update if @offer.update(offer_params) redirect_to owner_show_offer_path(@offer, token: @offer.owner_show_token), notice: tm('helpers.update_success', @offer) else render action: 'edit' end end def destroy @offer.destroy redirect_to offers_url end def toggle_active if @offer.toggle!(:is_public) redirect_to owner_show_offer_path(@offer, token: @offer.owner_show_token), notice: tm("helpers.#{@offer.is_public? ? 'make_public_success' : 'hide_success'}", @offer) else render action: 'show' end end def request_owner_link @offer = Offer.visible_for(current_user, Offer).find_by(id: params[:id]) ItemMailer.item_edit_link_mail(@offer).deliver_now if params[:email] == @offer.email redirect_to @offer, notice: t('items.request_edit_link.sent_notice') end private def set_editable_offer @offer = GlobalID::Locator.locate_signed(params[:token], for: :owner) redirect_to root_path, flash: { error: t('offers.invalid_token')} unless @offer end # Never trust parameters from the scary internet, only allow the white list through. def offer_params params[:offer].permit(:owner_name, :email, :title, :description, :rent, :size, :gender, :from_date, :to_date, :district, :street, :zip_code) end end <file_sep>/app/models/concerns/item.rb require 'active_support/concern' module Item extend ActiveSupport::Concern included do validates_presence_of :email, :owner_name attr_readonly :email has_many :answers, as: :item, dependent: :destroy has_one :item_reactivator, as: :item, dependent: :destroy scope :not_blocked, -> { where(blocked: false) } scope :blocked, -> { where(blocked: true) } scope :confirmed, -> { where.not(email_confirmed_at: nil) } scope :current, -> { where("#{table_name}.updated_at >= ?", outdating_date) } scope :outdated, -> { where("#{table_name}.updated_at < ?", outdating_date) } scope :is_public, -> { where(is_public: true) } end module ClassMethods def outdating_date 31.days.ago end def visible_for(user = nil, scope) if user&.admin? scope.current else scope.current.not_blocked.confirmed.is_public end end end def current? updated_at >= self.class.outdating_date end def outdated? updated_at < self.class.outdating_date end def visible? !blocked && email_confirmed? && current? end def email_confirmed? !email_confirmed_at.nil? end def confirm_email! update!(email_confirmed_at: Time.now) end def get_or_create_reactivator return item_reactivator if item_reactivator ItemReactivator.create! item: self end def unblock! update!(blocked: false) end def block! update!(blocked: true) end def owner_show_token self.to_sgid(expires_in: nil, for: :owner).to_s end end <file_sep>/db/migrate/20140722222707_add_fields_to_request.rb class AddFieldsToRequest < ActiveRecord::Migration def change add_column :requests, :from_date, :datetime rename_column :requests, :until, :to_date add_column :requests, :gender, :integer end end <file_sep>/app/models/request.rb class Request < ApplicationRecord include Item include CreationSpamCheck validates_presence_of :title, :description, :gender validates_length_of :title, maximum: 140 validates :description, format: { with: /.+\s.+/, message: "at least two words" } enum gender: { dontcare: 0, female: 1, male: 2 } end <file_sep>/app/helpers/offers_helper.rb module OffersHelper def date_info offer out = t('offers.show.from') << ' ' << l(offer.from_date) out << ' ' << t('offers.show.to') << ' ' << l(offer.to_date) if offer.to_date out end def address_info offer if offer.district && offer.district != '' "#{offer.district}, #{offer.street}" else offer.street end end end <file_sep>/app/helpers/stats_helper.rb module StatsHelper def create_day_of_year_averages(type) oldest_item = HistoryItem.order(created_at: :asc).first return [] unless oldest_item start_date = oldest_item.created_at.at_beginning_of_year.next_year start_date = 1.year.ago if start_date > 1.year.ago data = HistoryItem.all.where('created_at > ?', start_date).sort_by {|item| item.created_at.yday} data = data.group_by {|item| l(item.created_at, format: t('stats.statistics.date_format'))} data.each { |date, items| data[date] = (items.sum(&type).to_f / items.count)} end def create_month_averages(type) HistoryItem.group_by_month(:created_at).average(type) end end <file_sep>/config/initializers/dkim.rb if Rails.env.production? Dkim::domain = 'kaheim.de' Dkim::selector = '20200605' Dkim::private_key = open('/home/kaheim/dkim/20200605.private').read ActionMailer::Base.register_interceptor(Dkim::Interceptor) end <file_sep>/app/models/user.rb class User < ApplicationRecord # Include default devise modules. Others available are: # :token_authenticatable, # :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model validates_presence_of :name scope :admin, -> { where admin: true } scope :unlocked, -> { where(unlocked: true) } scope :locked, -> { where(unlocked: false) } scope :confirmed, -> { where.not(confirmed_at: nil) } def unlock! update!(unlocked: true) end def lock! update!(unlocked: false) end def confirmed? confirmed_at != nil end end <file_sep>/app/admin/users.rb ActiveAdmin.register User do menu priority: 3 index do column :name column :email column :unlocked column :admin column :confirmed_at actions default: true end filter :email form do |f| f.inputs "User Details" do f.input :name f.input :email f.input :admin f.input :password end f.actions end controller do def permitted_params params.permit user: [:name, :email, :admin, :password] end end end <file_sep>/db/migrate/20140723114929_change_from_date_format_in_requests.rb class ChangeFromDateFormatInRequests < ActiveRecord::Migration def change change_column :requests, :from_date, :date end end <file_sep>/db/migrate/20140722222444_add_public_and_public_until_to_offer.rb class AddPublicAndPublicUntilToOffer < ActiveRecord::Migration def change add_column :offers, :public, :boolean add_column :offers, :public_until, :datetime end end <file_sep>/app/admin/requests.rb ActiveAdmin.register Request do menu priority: 2 index do column :title column :owner_name column :email column :blocked column :email_confirmed_at actions default: true do |item| link_to(item.blocked ? 'Freischalten' : 'Sperren', item.blocked ? unblock_admin_request_path(item) : block_admin_request_path(item), method: :put) end end controller do def permitted_params params.permit request: [:blocked] end end member_action :block, method: :put do Request.find(params[:id]).block! redirect_back(fallback_location: root_path, notice: "Gesuch geblockt!") end member_action :unblock, method: :put do Request.find(params[:id]).unblock! redirect_back(fallback_location: root_path, notice: "Gesuch entblockt!") end end <file_sep>/test/controllers/answers_controller_test.rb require 'test_helper' class AnswersControllerTest < ActionDispatch::IntegrationTest test 'create answer gets rejected without captcha' do item = offers(:tworooms) assert_no_difference 'ActionMailer::Base.deliveries.size' do post answers_url, params: {answer: {message: 'test', mail: '<EMAIL>', item_id: item.id, item_type: 'Offer'} } end end test 'creating answer sends two mails' do item = offers(:tworooms) assert_difference 'ActionMailer::Base.deliveries.size', +2 do post answers_url, params: {answer: {message: 'test', mail: '<EMAIL>', item_id: item.id, item_type: 'Offer'}, stupid_captcha: 'Maria' } end end end <file_sep>/app/models/concerns/creation_spam_check.rb require 'active_support/concern' module CreationSpamCheck extend ActiveSupport::Concern included do validate :is_not_spam?, on: :create attr_accessor :no_spam end def is_not_spam? errors.add(:no_spam, I18n.t('errors.messages.accepted')) unless no_spam == '1' end end <file_sep>/app/controllers/requests_controller.rb class RequestsController < ApplicationController before_action :set_editable_request, only: [:edit, :update, :destroy, :toggle_active, :owner_show] def index @requests = Request.visible_for(current_user, Request).order(Arel.sql('from_date IS NOT NULL, from_date ASC'), updated_at: :desc) end def show @request = Request.visible_for(current_user, Request).find_by(id: params[:id]) unless @request redirect_to root_path, flash: { error: t('items.no_access') } end end def owner_show unless @request.email_confirmed? @request.confirm_email! Subscription.requests.confirmed.each do |subscriber| SubscriptionMailer.new_item_notification(@request, subscriber).deliver_now end flash.now[:notice] = tm('helpers.email_verified', @request) end render :owner_show end def new @request = Request.new end def edit end def create @request = Request.new(request_params) if @request.save ItemMailer.item_creation_mail(@request).deliver_now User.admin.find_each do |admin| ItemMailer.admin_notice_mail(@request, admin).deliver_now end @item = @request render 'pages/item_created' else render action: 'new' end end def update if @request.update(request_params) redirect_to owner_show_request_path(@request, token: @request.owner_show_token), notice: tm('helpers.update_success', @request) else render action: 'edit' end end def destroy @request.destroy redirect_to requests_url end def toggle_active if @request.toggle!(:is_public) redirect_to owner_show_request_path(@request, token: @request.owner_show_token), notice: tm("helpers.#{@request.is_public? ? 'make_public_success' : 'hide_success'}", @request) else render action: 'show' end end def request_owner_link @request = Request.visible_for(current_user, Request).find_by(id: params[:id]) ItemMailer.item_edit_link_mail(@request).deliver_now if params[:email] == @request.email redirect_to @request, notice: t('items.request_edit_link.sent_notice') end private def set_editable_request @request = GlobalID::Locator.locate_signed(params[:token], for: :owner) redirect_to root_path, flash: { error: t('requests.invalid_token')} unless @request end # Never trust parameters from the scary internet, only allow the white list through. def request_params params[:request].permit(:owner_name, :email, :title, :description, :from_date, :to_date, :gender, :no_spam) end end
916bc8074e0788d08fa6dd51f17d95fa3d79ccd6
[ "Markdown", "Ruby" ]
60
Ruby
SDEagle/kaheim
19f730aec8f888f23c1c81ffb8ffe0cee31bb579
22a6c5b7c46819367a28c3a16e60f17ae95c0561
refs/heads/master
<repo_name>kajames2/bidding<file_sep>/src/first_price_auction.cc #include "bidding/first_price_auction.h" #include <algorithm> #include <boost/math/distributions/uniform.hpp> #include <boost/math/quadrature/gauss.hpp> #include <boost/math/quadrature/gauss_kronrod.hpp> #include "bidding/bid_function_ops.h" #include <iostream> using namespace boost::math; namespace bidding { FirstPriceAuction::FirstPriceAuction(std::vector<Distribution> value_dists) : bid_funcs_(value_dists.size()), bid_cdfs_(value_dists.size()), value_dists_(value_dists), n_players_(value_dists.size()) {} float FirstPriceAuction::GetValue(float value, float bid) const { return value - bid; } void FirstPriceAuction::AcceptStrategy(std::function<float(float)> bid_func, int id) { bid_funcs_[id] = bid_func; bid_cdfs_[id] = ResampleFunction( ApproximateRandomVariableFunctionCDF(value_dists_[id], bid_func), Interval{0, upper(value_dists_)}); } float FirstPriceAuction::GetFitness(const std::function<float(float)>& bid_func, int id) const { float exp_profit = quadrature::gauss_kronrod<float, 61>::integrate( [this, bid_func, id](float value) { return GetIntegrand(bid_func, id, value); }, lower(value_dists_[id]), upper(value_dists_[id]), 0, 0); return exp_profit; } float FirstPriceAuction::GetIntegrand( const std::function<float(float)>& bid_func, int id, float value) const { float bid = bid_func(value); float integrand = value - bid; integrand *= pdf(value_dists_[id], value); for (int j = 0; j < n_players_; ++j) { if (j != id) { integrand *= bid_cdfs_[j](bid); } } return integrand; } } // namespace bidding <file_sep>/test/all_pay_auction_tests.cc #include <gtest/gtest.h> #include <vector> #include "bidding/all_pay_auction.h" #include "bidding/bid_function_ops.h" #include "bidding/distribution.h" #include "boost/math/distributions/uniform.hpp" namespace gatests { class AllPayAuctionTest : public ::testing::Test { public: AllPayAuctionTest() {} protected: virtual void SetUp() {} bidding::AllPayAuction auction = bidding::AllPayAuction(std::vector<float>{1, 1}); float epsilon = 0.0001; }; TEST_F(AllPayAuctionTest, NoSingularityTest) { auto bid_func = [](float x) { return x*x; }; auction.AcceptStrategy(bid_func, 0); auction.AcceptStrategy(bid_func, 1); float fit = auction.GetFitness(bid_func, 1); EXPECT_NEAR(-1/6., fit, epsilon); } // TEST_F(AllPayAuctionTest, OneSingularityAtValueTest) { // auto bid_func = [](float x) { return x; }; // auto bid_func2 = [](float x) { return 0; }; // auction.AcceptStrategy(bid_func, 0); // auction.AcceptStrategy(bid_func2, 1); // float fit = auction.GetFitness(bid_func, 0); // float fit2 = auction.GetFitness(bid_func2, 1); // EXPECT_NEAR(-0.5, fit, epsilon); // EXPECT_NEAR(0, fit2, epsilon); // } // TEST_F(AllPayAuctionTest, OneSingularityAtZeroTest) { // auto bid_func = [](float x) { return x; }; // auto bid_func2 = [](float x) { return 1; }; // auction.AcceptStrategy(bid_func, 0); // auction.AcceptStrategy(bid_func2, 1); // float fit = auction.GetFitness(bid_func, 0); // float fit2 = auction.GetFitness(bid_func2, 1); // EXPECT_NEAR(0.5, fit, epsilon); // EXPECT_NEAR(0, fit2, epsilon); // } // TEST_F(AllPayAuctionTest, TwoSingularityAtZeroTest) { // auto bid_func = [](float x) { return 0.3; }; // auto bid_func2 = [](float x) { return 1; }; // auction.AcceptStrategy(bid_func, 0); // auction.AcceptStrategy(bid_func2, 1); // float fit = auction.GetFitness(bid_func, 0); // float fit2 = auction.GetFitness(bid_func2, 1); // EXPECT_NEAR(0.15, fit, epsilon); // EXPECT_NEAR(0.15, fit2, epsilon); // } // TEST_F(AllPayAuctionTest, TwoSingularityAtValueTest) { // auto bid_func = [](float x) { return 0.3; }; // auto bid_func2 = [](float x) { return 0; }; // auction.AcceptStrategy(bid_func, 0); // auction.AcceptStrategy(bid_func2, 1); // float fit = auction.GetFitness(bid_func, 0); // float fit2 = auction.GetFitness(bid_func2, 1); // EXPECT_NEAR(-0.35, fit, epsilon); // EXPECT_NEAR(-0.35, fit2, epsilon); // } // TEST_F(AllPayAuctionTest, AllSingularitiesTest) { // auto bid_func = [](float x) { return 0.3; }; // auto bid_func2 = [](float x) { return 0.6; }; // auction.AcceptStrategy(bid_func, 0); // auction.AcceptStrategy(bid_func2, 1); // float fit = auction.GetFitness(bid_func, 0); // float fit2 = auction.GetFitness(bid_func2, 1); // EXPECT_NEAR(-0.05, fit, epsilon); // EXPECT_NEAR(-0.05, fit2, epsilon); // } // TEST_F(AllPayAuctionTest, FullTest) { // auto bid_func = [](float x) { return 0.3 + x/2.; }; // auto bid_func2 = [](float x) { return 0.1 + x/2.; }; // auction.AcceptStrategy(bid_func, 0); // auction.AcceptStrategy(bid_func2, 1); // float fit = auction.GetFitness(bid_func, 0); // float fit2 = auction.GetFitness(bid_func2, 1); // EXPECT_NEAR(-0.1, fit, epsilon); // EXPECT_NEAR(0, fit2, epsilon); // } } // namespace gatests <file_sep>/include/bidding/first_price_auction.h #ifndef _BIDDING_FIRST_PRICE_AUCTION_H_ #define _BIDDING_FIRST_PRICE_AUCTION_H_ #include <boost/math/quadrature/gauss_kronrod.hpp> #include <functional> #include "bidding/distribution.h" #include "bidding/piecewise_linear_function.h" namespace bidding { class FirstPriceAuction { public: FirstPriceAuction(std::vector<Distribution> value_dists); float GetValue(float value, float bid) const; void AcceptStrategy(std::function<float(float)> bid, int id); float GetFitness(const std::function<float(float)>& bid_func, int id) const; private: float GetIntegrand(const std::function<float(float)>& bid_func, int id, float value) const; std::vector<std::function<float(float)>> bid_funcs_; std::vector<std::function<float(float)>> bid_cdfs_; std::vector<Distribution> value_dists_; int n_players_; }; } // namespace bidding #endif // _BIDDING_FIRST_PRICE_AUCTION_H_ <file_sep>/src/second_price_auction.cc #include "bidding/second_price_auction.h" #include <algorithm> #include <boost/math/distributions/uniform.hpp> #include <boost/math/quadrature/gauss.hpp> #include <boost/math/quadrature/gauss_kronrod.hpp> #include "bidding/bid_function_ops.h" #include <iostream> using namespace boost::math; namespace bidding { SecondPriceAuction::SecondPriceAuction(std::vector<Distribution> value_dists) : bid_funcs_(value_dists.size()), order_stat_funcs_(value_dists.size()), exp_value_funcs_(value_dists.size()), value_dists_(value_dists), n_players_(value_dists.size()), pre_calculated_(false) {} void SecondPriceAuction::AcceptStrategy(std::function<float(float)> bid_func, int id) { bid_funcs_[id] = bid_func; pre_calculated_ = false; } float SecondPriceAuction::GetFitness( const std::function<float(float)>& bid_func, int id) const { if (!pre_calculated_) { Precalculate(); } float exp_profit = quadrature::gauss_kronrod<float, 61>::integrate( [this, bid_func, id](float value) { return GetIntegrand(bid_func, id, value); }, lower(value_dists_[id]), upper(value_dists_[id]), 0, 0); return exp_profit; } void SecondPriceAuction::Precalculate() const { Interval interval = Interval{0, upper(value_dists_)}; std::vector<std::function<float(float)>> cdfs; for (int i = 0; i < n_players_; ++i) { cdfs.push_back(ResampleFunction( ApproximateRandomVariableFunctionCDF(value_dists_[i], bid_funcs_[i]), interval)); } for (int i = 0; i < n_players_; ++i) { std::vector<std::function<float(float)>> other_cdfs; std::vector<Distribution> other_dists; for (int j = 0; j < n_players_; ++j) { if (i != j) { other_cdfs.emplace_back(cdfs[j]); other_dists.emplace_back(value_dists_[j]); } } order_stat_funcs_[i] = ApproximateKthLowestOrderStatisticCDF(other_cdfs, interval, n_players_ - 1); exp_value_funcs_[i] = ApproximateExpectedValueFunction(order_stat_funcs_[i], interval); } pre_calculated_ = true; } double SecondPriceAuction::GetIntegrand( const std::function<float(float)>& bid_func, int id, float value) const { double bid = bid_func(value); double prob_bid = pdf(value_dists_[id], value); double prob_win = order_stat_funcs_[id](bid); double exp_second_bid_given_win = exp_value_funcs_[id](bid); return (value - exp_second_bid_given_win) * prob_win * prob_bid; } } // namespace bidding <file_sep>/src/all_pay_auction.cc #include "bidding/all_pay_auction.h" #include <boost/math/distributions/uniform.hpp> #include <boost/math/quadrature/gauss_kronrod.hpp> #include "bidding/bid_function_ops.h" using namespace boost::math; namespace bidding { AllPayAuction::AllPayAuction(std::vector<float> values) : bid_cdf_funcs_(values.size()), bid_pdf_funcs_(values.size()), values_(values), n_players_(values.size()) {} float AllPayAuction::GetValue(float bid, float value) const { return value; } void AllPayAuction::AcceptStrategy(std::function<float(float)> cdf, int id) { bid_cdf_funcs_[id] = cdf; bid_pdf_funcs_[id] = ApproximateDerivative(cdf, Interval{0, values_[id]}); } float ExpectedProfitTiesAtZero( const std::vector<std::function<float(float)>>& bid_cdfs, float value, int id) { int n_players = bid_cdfs.size(); float prob_all_zero = 1; for (int j = 0; j < n_players; ++j) { prob_all_zero *= bid_cdfs[j](0); } return 1. / n_players * value * prob_all_zero; } float AllPayAuction::GetFitness(const std::function<float(float)>& cdf_func, int id) const { float exp_profit = quadrature::gauss_kronrod<float, 61>::integrate( [this, cdf_func, id](float bid) { return GetIntegrand(cdf_func, id, bid); }, 0, values_[id], 0, 0); exp_profit += ExpectedProfitTiesAtZero(bid_cdf_funcs_, values_[id], id); float prob_no_other_val = 1; float prob_no_above = 1; for (int j = 0; j < n_players_; ++j) { if (j != id) { if (values_[j] == values_[id]) { prob_no_other_val *= bid_cdf_funcs_[j](values_[id]); } else { prob_no_above *= bid_cdf_funcs_[j](values_[id]); } } } float prob_val = (1 - cdf_func(values_[id])); exp_profit += (0 - values_[id]) * (1 - prob_no_above) * prob_val; exp_profit += ((1. / n_players_ * values_[id]) - values_[id]) * (1 - prob_no_other_val) * prob_no_above * prob_val; // exp_profit += (values_[id] - values_[id]) * prob_no_other_val * // prob_no_above * prob_val; return exp_profit; } float AllPayAuction::GetIntegrand(const std::function<float(float)>& cdf_func, int id, float bid) const { float density = bid_pdf_funcs_[id](bid); float prob_win = 1; for (int j = 0; j < n_players_; ++j) { if (j != id) { prob_win *= bid_cdf_funcs_[j](bid); } } return (prob_win * values_[id] - bid) * density; } } // namespace bidding <file_sep>/include/bidding/all_pay_auction.h #ifndef _BIDDING_ALL_PAY_AUCTION_H_ #define _BIDDING_ALL_PAY_AUCTION_H_ #include <boost/math/quadrature/gauss_kronrod.hpp> #include "bidding/distribution.h" #include "bidding/piecewise_linear_function.h" namespace bidding { class AllPayAuction { public: AllPayAuction(std::vector<float> values); float GetValue(float bid, float value) const; void AcceptStrategy(std::function<float(float)> cdf, int id); float GetFitness(const std::function<float(float)>& cdf, int id) const; private: float GetIntegrand(const std::function<float(float)>& cdf, int id, float bid) const; std::vector<std::function<float(float)>> bid_cdf_funcs_; std::vector<std::function<float(float)>> bid_pdf_funcs_; std::vector<float> values_; int n_players_; }; } // namespace bidding #endif // _BIDDING_ALL_PAY_AUCTION_H_ <file_sep>/include/bidding/player_bid.h #ifndef _BIDDING_PLAYER_BID_H_ #define _BIDDING_PLAYER_BID_H_ #include "bidding/piecewise_linear_function.h" namespace bidding { struct PlayerBid { int id; PiecewiseLinearFunction bid; }; } // namespace bidding #endif // _BIDDING_PLAYER_BID_H_ <file_sep>/test/first_price_auction_tests.cc #include <gtest/gtest.h> #include <vector> #include "bidding/bid_function_ops.h" #include "bidding/distribution.h" #include "bidding/first_price_auction.h" #include "boost/math/distributions/uniform.hpp" namespace gatests { class FirstPriceAuctionTest : public ::testing::Test { public: FirstPriceAuctionTest() {} protected: virtual void SetUp() {} bidding::FirstPriceAuction auction = bidding::FirstPriceAuction(std::vector<bidding::Distribution>{ boost::math::uniform_distribution<>(0, 1), boost::math::uniform_distribution<>(0, 1)}); float epsilon = 0.0001; }; TEST_F(FirstPriceAuctionTest, AlwaysWinTest) { auction.AcceptStrategy([](float x) { return 0; }, 0); float fit = auction.GetFitness([](float x) { return 0.01; }, 1); EXPECT_NEAR(0.49, fit, epsilon); } TEST_F(FirstPriceAuctionTest, WinHalfTest) { auto bid_func = [](float x) { return x / 2; }; auction.AcceptStrategy(bid_func, 0); float fit = auction.GetFitness([](float x) { return x / 2; }, 1); EXPECT_NEAR(.166666, fit, epsilon); } TEST_F(FirstPriceAuctionTest, DecreasingBidsTest) { auto bid_func = [](float x) { return 0.5 - x / 2; }; auction.AcceptStrategy(bid_func, 0); float fit = auction.GetFitness([](float x) { return x / 2; }, 1); EXPECT_NEAR(.166666, fit, epsilon); } TEST_F(FirstPriceAuctionTest, DecreasingBids2Test) { auto bid_func = [](float x) { return x / 2; }; auction.AcceptStrategy(bid_func, 0); float fit = auction.GetFitness([](float x) { return 0.5 - 0.5*x; }, 1); EXPECT_NEAR(0, fit, epsilon); } TEST_F(FirstPriceAuctionTest, NoIntersectDistsTest) { auction = bidding::FirstPriceAuction(std::vector<bidding::Distribution>{ boost::math::uniform_distribution<>(20, 40), boost::math::uniform_distribution<>(40, 60)}); float epsilon = 0.001; auto bid_func = [](float x) { return 20; }; auction.AcceptStrategy(bid_func, 0); auto bid_func2 = [](float x) { return 20.2; }; auction.AcceptStrategy(bid_func2, 1); float fit = auction.GetFitness(bid_func, 0); EXPECT_NEAR(0, fit, epsilon); float fit2 = auction.GetFitness(bid_func2, 1); EXPECT_NEAR(29.8, fit2, epsilon); } } // namespace gatests <file_sep>/test/second_price_auction_tests.cc #include <gtest/gtest.h> #include <vector> #include "bidding/bid_function_ops.h" #include "bidding/distribution.h" #include "bidding/second_price_auction.h" #include "boost/math/distributions/uniform.hpp" namespace gatests { class SecondPriceAuctionTest : public ::testing::Test { public: SecondPriceAuctionTest() {} protected: virtual void SetUp() {} bidding::SecondPriceAuction auction = bidding::SecondPriceAuction(std::vector<bidding::Distribution>{ boost::math::uniform_distribution<>(0, 1), boost::math::uniform_distribution<>(0, 1)}); float epsilon = 0.001; }; TEST_F(SecondPriceAuctionTest, AlwaysWinTest) { auto func1 = [](float x) { return 0; }; auto func2 = [](float x) { return 1; }; auction.AcceptStrategy(func1, 0); auction.AcceptStrategy(func2, 1); float fit = auction.GetFitness(func2, 1); EXPECT_NEAR(0.5, fit, epsilon); } TEST_F(SecondPriceAuctionTest, WinHalfTest) { auto bid_func = [](float x) { return x; }; auction.AcceptStrategy(bid_func, 0); auction.AcceptStrategy(bid_func, 1); float fit = auction.GetFitness([](float x) { return x; }, 1); EXPECT_NEAR(.166666, fit, epsilon); } TEST_F(SecondPriceAuctionTest, DecreasingBidsTest) { auto bid_func = [](float x) { return 1 - x; }; auto bid_func2 = [](float x) { return x; }; auction.AcceptStrategy(bid_func, 0); auction.AcceptStrategy(bid_func2, 1); float fit = auction.GetFitness(bid_func2, 1); EXPECT_NEAR(.166666, fit, epsilon); } TEST_F(SecondPriceAuctionTest, DecreasingBids2Test) { auto bid_func = [](float x) { return x; }; auto bid_func2 = [](float x) { return 1 - x; }; auction.AcceptStrategy(bid_func, 0); auction.AcceptStrategy(bid_func2, 1); float fit = auction.GetFitness(bid_func2, 1); EXPECT_NEAR(0, fit, epsilon); } TEST_F(SecondPriceAuctionTest, NoIntersectDistsTest) { auction = bidding::SecondPriceAuction(std::vector<bidding::Distribution>{ boost::math::uniform_distribution<>(20, 40), boost::math::uniform_distribution<>(40, 60)}); epsilon = 0.015; auto bid_func = [](float x) { return 20; }; auto bid_func2 = [](float x) { return 21; }; auction.AcceptStrategy(bid_func, 0); auction.AcceptStrategy(bid_func2, 1); float fit = auction.GetFitness(bid_func, 0); EXPECT_NEAR(0, fit, epsilon); float fit2 = auction.GetFitness(bid_func2, 1); EXPECT_NEAR(30, fit2, epsilon); } } // namespace gatests <file_sep>/include/bidding/second_price_auction.h #ifndef _BIDDING_SECOND_PRICE_AUCTION_H_ #define _BIDDING_SECOND_PRICE_AUCTION_H_ #include <boost/math/quadrature/gauss_kronrod.hpp> #include <functional> #include "bidding/distribution.h" #include "bidding/piecewise_linear_function.h" namespace bidding { class SecondPriceAuction { public: SecondPriceAuction(std::vector<Distribution> value_dists); void AcceptStrategy(std::function<float(float)> bid, int id); float GetFitness(const std::function<float(float)>& bid_func, int id) const; private: double GetIntegrand(const std::function<float(float)>& bid_func, int id, float value) const; void Precalculate() const; std::vector<std::function<float(float)>> bid_funcs_; mutable std::vector<std::function<float(float)>> order_stat_funcs_; mutable std::vector<std::function<float(float)>> exp_value_funcs_; std::vector<Distribution> value_dists_; int n_players_; mutable bool pre_calculated_; }; } // namespace bidding #endif // _BIDDING_SECOND_PRICE_AUCTION_H_
845c0b300503fef112abdba7625d1676ee6cb7ce
[ "C++" ]
10
C++
kajames2/bidding
582e0499ecd13de3512b83dc8a5ea97128d7e3b3
c505f49e51c621df08291bdfcfbcb8b5dfbb96d1
refs/heads/master
<file_sep># django import from django.conf.urls.defaults import include, patterns, url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.views.generic.simple import direct_to_template from django.contrib import admin admin.autodiscover() urlpatterns = patterns( "", url(r"^dirlist/$", 'django_toopy_editor.views.dirlist', name='toopy_editor.dirlist'), url(r"^editor/$", 'django_toopy_editor.views.editor', name='toopy_editor'), # .. url(r"^admin/", include(admin.site.urls)), url(r"^$", 'django_toopy_editor.views.editor', name='index'), ) urlpatterns += staticfiles_urlpatterns()
9d5645fffebb0d2ae350b39c925fda3328894846
[ "Python" ]
1
Python
toopy/django-toopy-editor
90ff809d90808c6fa206a762c0c6fb19bf390554
b3b160941d4604a03be1e482d690c558a268b864
refs/heads/main
<repo_name>nazimbandoui/car_tracking<file_sep>/track.py import numpy as np import cv2 import time def foofunction(x, y): a = [] b = [] c = [] for i in range(0, len(x)): state = False for j in range(0, len(y)): if np.all(x[i] == y[j]): b.append(x[i]) state = True if not state: a.append(x[i]) for i in range(0, len(y)): state = False for j in range(0, len(x)): if np.all(x[j] == y[i]): state = True break if not state: c.append(y[i]) return a, b, c def labelformat(a): a = str(a) for i in range(len(a), 4): a = "0"+a return a car_cascade = cv2.CascadeClassifier('haar_car.xml') init = False car_dataset = [] frame_counter = 1 for i in range(1, 1701): img = cv2.imread("highway\\input\\in00"+labelformat(i)+".jpg") car_dataset.append(img) all_cars = [] id_vehicle = 1 for img in car_dataset: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cars = car_cascade.detectMultiScale(gray, 1.1, 5) new_cars = [] # read new detected objects for (x, y, w, h) in cars: new_cars.append(detected_object(x, y, w, h, "Vehicle TBD")) for element in range(len(all_cars)): all_cars[element].draw = False if not init and len(cars) > 0: for element in new_cars: element.label = str(id_vehicle) id_vehicle += 1 all_cars = new_cars.copy() init = True elif init: # delete elements with no TTL left and decrements TTL for element in range(len(all_cars)): # todel = [] if all_cars[element].TTL <= 0: all_cars[element].draw = False else: all_cars[element].TTL -= 1 all_cars[element].draw = False # Determin object correspendence # compute xxo as [a,b] where a is the index of the new object in new_cars and o is the index of the object in all_cars if init and len(new_cars) > 0: xxo = [] for new_element in range(len(new_cars)): distance = [] distance_indexes = [] for old_element in range(len(all_cars)): distance.append(new_cars[new_element].distance( all_cars[old_element])) distance_indexes.append([new_element, old_element]) xxo.append(distance_indexes[np.argmin(distance)]) # Same thing as precedent , but this time we inverse the loop oxo = [] for old_element in range(len(all_cars)): distance = [] distance_indexes = [] for new_element in range(len(new_cars)): distance.append(all_cars[old_element].distance( new_cars[new_element])) distance_indexes.append([new_element, old_element]) oxo.append(distance_indexes[np.argmin(distance)]) # now we search for the intersection of xxo and oxo : # 1- if an element is common , the we update it's position in all_cars # 2 - if an element belongs only to xxo , then it's a new element # 3 - if an element belongs onlt to oxo , then we don't render it only_x, common, only_o = foofunction(xxo, oxo) # case 1 : for common_element in common: all_cars[common_element[1]].TTL = 5 all_cars[common_element[1]].x = new_cars[common_element[0]].x all_cars[common_element[1]].y = new_cars[common_element[0]].y all_cars[common_element[1] ].centroid = new_cars[common_element[0]].centroid all_cars[common_element[1]].draw = True # case 2 : for only_x_element in only_x: new_cars[only_x_element[0]].label = str(id_vehicle) new_cars[only_x_element[0]].draw = True id_vehicle += 1 all_cars = list(all_cars) all_cars.append(new_cars[only_x_element[0]]) # case 3 : for only_o_element in only_o: all_cars[only_o_element[1]].x = 9999 all_cars[only_o_element[1]].y = 9999 all_cars[only_o_element[1]].centroid = (9999, 9999) all_cars[only_o_element[1]].draw = False showdown = all_cars for element in showdown: element.history.append(element.centroid) print(element.history) if element.draw: startpoint = element.history[0] endpoint = element.history[-1] vector = (endpoint[0]-startpoint[0], endpoint[1]-startpoint[1]) enddraw = (element.centroid[0]+vector[0], element.centroid[1]+vector[1]) cv2.rectangle(img, (element.x, element.y), (element.x + element.w, element.y+element.h), (0, 0, 255), 2) cv2.putText(img, element.label, (element.x, element.y+element.h+50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA) try: cv2.arrowedLine(img, element.centroid, enddraw, (255, 0, 0), 2) except: pass for i in element.history: cv2.circle(img, i, 2, (0, 255, 255), -1) cv2.imshow("CAR TRACKING", img) time.sleep(0.01) frame_counter += 1 # Stop if 'q' key is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break
5ae96fb12fb3b7f7633b01c8002304b691a482e9
[ "Python" ]
1
Python
nazimbandoui/car_tracking
588ec00154ed1c71dd644cfc5c4531cb5c70976d
551c6c8e9390ad392f409a43807bd54879cd2e26
refs/heads/master
<file_sep>const carname='Swift'; function discount_percentage(price,deliverycharge,discount){ var original_price=price; var deliver=deliverycharge; var discountvalue=discount; return function(){ console.log(`The car name is ${carname}`); return((original_price+deliver-discountvalue)*100); }; } let dzire= discount_percentage(1000000,100,500); console.log("The original price of the car is"+" "+dzire()); <file_sep>var Location="Chennai"; function print_location(){ console.log("The location of the showroom is in"+" "+Location); } class car_showroom{ constructor(carname,brand,price){ this.carname=carname; this.brand=brand; this.price=price; this.show_room_name=function(){ var showroomname="Car_Park"; console.log("My car showroom name is"+" "+showroomname); } this.displaydetails=function(){ console.log(`The car name is ${this.carname}`); console.log(`Brand of the car ${this.carname} is ${this.brand}`); console.log(`Price of the car ${this.carname} is ${this.price}`); } this.warranty_period=function(){ if(this.carname=="AudiA4") console.log("The warranty period of the car"+this.carname+" "+"is"+" "+"5 years"); if(this.carname=="Innova") console.log("The warranty period of the car"+this.carname+" "+"is"+" "+"10 years"); if(this.carname=="Alto") console.log("The warranty period of the car"+this.carname+" "+"is"+" "+"7 years"); } } }; car_showroom.prototype.Free_service=function() { console.log(this.carname+" "+"has a free service in the sixth month after buying the car"); } const car_obj1=new car_showroom("Innova","Toyota",900000); const car_obj2=new car_showroom("AudiA4","Audi",1000000); const car_obj3=new car_showroom("Alto","Maruti",400000); console.log(window.Location);//Prints the Location since it is a global variable accessible by window object window.print_location();//window object can access print_location function since it is global car_obj1.show_room_name(); console.log("----------------------Showroom1---------------------"); car_obj1.displaydetails(); console.log("----------------------Showroom2---------------------"); car_obj2.displaydetails(); console.log("----------------------Showroom3---------------------"); car_obj3.displaydetails(); console.log("-----------------------------------------------------"); car_obj1.warranty_period(); car_obj2.warranty_period(); car_obj3.warranty_period(); console.log("------------------------------------------------------------------"); car_obj1.Free_service(); car_obj2.Free_service(); car_obj3.Free_service(); console.log("------------------------------------------------------------------"); car_showroom.prototype.discount_price=500; const dp1=car_showroom.prototype.discounted_price=(function(){ car_obj1.price=car_obj1.price-car_obj1.discount_price; console.log("The discounted price of all cars is"+" "+car_obj1.price); })(); const dp2=car_showroom.prototype.discounted_price=(function(){ car_obj2.price=car_obj2.price-car_obj2.discount_price; console.log("The discounted price of all cars is"+" "+car_obj2.price); })(); const dp3=car_showroom.prototype.discounted_price=(function(){ car_obj3.price=car_obj3.price-car_obj3.discount_price; console.log("The discounted price of all cars is"+" "+car_obj3.price); })(); console.log("------------------------------------------------------------------"); car_showroom.prototype.mode; car_obj1.mode="Petrol"; car_obj2.mode="Diesel"; car_obj3.mode="Petrol"; car_obj1.color="Red"; car_obj2.color="Blue"; car_obj3.color="Black"; function added_colors(){ car_obj1.color="Black"; car_obj2.color="White"; car_obj3.color="Green"; } added_colors(); console.log("New colors changed"); car_showroom.prototype.total_profit; car_showroom.prototype.profit; car_obj1.profit=200; car_obj2.profit=500; car_obj3.profit=400; (function Profit_calc(){ car_obj1.total_profit = (car_obj1.price * car_obj1.profit); console.log("Total profit made by showrrom 1 is " , car_obj1.total_profit); car_obj2.total_profit = (car_obj2.price * car_obj2.profit); console.log("Total profit made by shwroom 2 is " , car_obj2.total_profit); car_obj3.total_profit = (car_obj3.price * car_obj3.profit); console.log("Total profit made by shwroom 2 is " , car_obj3.total_profit); })(); console.log("------------------------------------------------------------------"); //Revealing module pattern let people_visited = (function () { let count=0; let count1=0; function no_of_people_visted() { count += 1; count1+=1; console.log(`Number of people visited the showroom ${count1} are:${count}`); } function displayName() { car_obj1.displaydetails(); car_obj2.displaydetails(); car_obj2.displaydetails(); } function display_visited() { no_of_people_visted(); } return { name: displayName, visited: display_visited }; })(); people_visited.name(); console.log("------------------------------------------------------------------"); people_visited.visited(); people_visited.visited(); people_visited.visited(); console.log("------------------------------------------------------------------"); //Composite pattern (function Feedback(){ function Customer(name,feedback,city,email){ this.cus_name = name; this.email=email this.feedback = feedback; this.city = city; } function car_showrooms(name) { this.sname = name; this.cars = []; } car_showrooms.prototype.add = function(cars){ this.cars.push(cars); } car_showrooms.prototype.getName = function(index){ return this.cars[index].cus_name; } car_showrooms.prototype.getFeedback = function(index){ return this.cars[index].feedback; } car_showrooms.prototype.getCity = function(index){ return this.cars[index].city; } car_showrooms.prototype.getemail = function(index){ var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(mailformat.test(this.cars[index].email)) { console.log("Valid email address!"); } else { console.log("You have entered an invalid email address!"); } return this.cars[index].email; } car_showrooms.prototype.display = function(){ console.log("Customers Feedback for " + this.sname); for(var i = 0 , len = this.cars.length ; i < len ; i++){ console.log(" " , this.getName(i) , " gave a review of " , this.getFeedback(i) , " from " , this.getCity(i),"of address",this.getemail(i)); } } showroom1 = new car_showrooms("Showroom 1"); showroom2 = new car_showrooms("Showroom 2"); input3 = new Customer("Priya" , "Good" , "Mumbai","<EMAIL>"); input4 = new Customer("Sherin" , "Poor" , "Chennai","<EMAIL>"); input5 = new Customer("Leela" , "Outstanding" , "Bangalore","<EMAIL>"); showroom1.add(input3); showroom1.add(input4); showroom2.add(input5); showroom2.add(input3); showroom2.add(input4); showroom1.display(); showroom2.display(); })(); console.log("----------------------Showroom1---------------------"); car_obj1.displaydetails(); console.log("Mode:"+" "+car_obj1.mode); console.log("Color:"+" "+car_obj1.color); console.log("Profit made for a single car:"+" "+car_obj1.profit); console.log("Total profit:"+" "+car_obj1.total_profit); console.log("----------------------Showroom2---------------------"); car_obj2.displaydetails(); console.log("Mode:"+" "+car_obj2.mode); console.log("Color:"+" "+car_obj2.color); console.log("Profit made for a single car:"+" "+car_obj2.profit); console.log("Total profit:"+" "+car_obj2.total_profit); console.log("----------------------Showroom3---------------------"); car_obj3.displaydetails(); console.log("Mode:"+" "+car_obj3.mode); console.log("Color:"+" "+car_obj3.color); console.log("Profit made for a single car:"+" "+car_obj3.profit); console.log("Total profit:"+" "+car_obj3.total_profit); console.log("-----------------------------------------------------"); <file_sep> use CollegeDatabase; SELECT RollNo from Attendance where LectureID=14; --Displaying the roll number of students who attended the lecture on tuesday and thursday Create View [Student_Rollno] as SELECT RollNo from Attendance where LectureID IN (Select LectureID from Lecture where Day='Monday' OR Day='Thursday'); --Subqueries --Retrieving the name of students who attended the lecture on wednesday and thursday create View [Student_names] as SELECT Name from Student,Attendance where Attendance.RollNo=Student.RollNo AND LectureID IN (Select LectureID from Lecture where Day='Wednesday' OR Day='Thursday'); --Executing the view Student_names select * from [Student_names]; --displaying the number of students who attended the lecture on monday and friday SELECT COUNT(RollNo) from Attendance where LectureID IN (Select LectureID from Lecture where Day='Monday' or Day='Tuesday'); --Joins --Displaying the course name belonging to department computer science SELECT CourseName from Courses,DepartmentCourses where DepartmentCourses.CourseID=Courses.CourseID AND DeptID=101 ORDER BY CourseName DESC; --Do more students attend college on wednesday Select Lecture.Day,count(Attendance.RollNo) AS noofstudents from Attendance join Lecture on Attendance.LectureID=Lecture.LectureID GROUP BY Lecture.Day ORDER BY noofstudents DESC; --Which day has maximum number of students attended the lecture Select Lecture.Day,count(Attendance.RollNo) AS noofstudents from Attendance join Lecture on Attendance.LectureID=Lecture.LectureID GROUP BY Lecture.Day ORDER BY noofstudents DESC offset 0 rows fetch next 1 rows only; <file_sep>using System; using System.Collections.Generic; using System.Globalization; namespace Hospital_management { class Appointment { private static int Option; public static string GetOption { get; private set; } public static bool ConfirmResult { get; private set; } static bool dateCheck(string stringDate) { // Define the acceptable date formats and check if entered date is valid string[] formats = { "d/MM/yyyy", "dd/MM/yyyy", "d/M/yyyy" }; DateTime parsedDate; try { //Conversion from string to Date time bool isValidFormat = DateTime.TryParseExact(stringDate, formats, new CultureInfo("ta-IN"), DateTimeStyles.None, out parsedDate); if (isValidFormat) { // If date is valid, check whether the given year is more than the year Today if (parsedDate < DateTime.Now) { Console.WriteLine("Appointment date must be appropriate"); return false; } else { //end do while Loop return true; } } else { //if not a valid date, give an error Console.WriteLine("Wrong Date format"); return false; } } catch (FormatException) { //Catch format exception errors on date return false; } } static int CalculateAge(string dateOfBirth) { DateTime birthDay = DateTime.Parse(dateOfBirth); int years = DateTime.Now.Year - birthDay.Year; return years; } static int Calculatemonth(string dateOfBirth) { DateTime birthDay = DateTime.Parse(dateOfBirth); int month = DateTime.Now.Month - birthDay.Month; return month; } static double Calculatedate(string dateOfBirth) { DateTime birthDay = DateTime.Parse(dateOfBirth); double date = (DateTime.Now.Date - birthDay.Date).TotalDays; return date; } public static void Confirm(List<patientAppointment> Patient_name) { Bill.PrintBill(Patient_name); // Calling the print bill function previousAppointment.AddAppoint(Patient_name); do { Console.WriteLine("How do you want to save your file? "); Console.WriteLine("1. json"); Console.WriteLine("2. xml"); Console.WriteLine("Enter your Option"); GetOption = Console.ReadLine(); while (!int.TryParse(GetOption, out Option)) { Console.WriteLine("This is not a number!"); GetOption = Console.ReadLine(); } if ((Option > 0) && (Option < 3)) { ConfirmResult = false; switch (Option) //Switch case for chosing what to do { case 1: Bill.saveasjson(Patient_name); //Patient_info.saveasjson(PatientList); break; case 2: Bill.saveasxml(Patient_name); break; default: Console.WriteLine("Option not found"); break; } }else { ConfirmResult = true; Console.WriteLine("Re-enter option"); } } while (ConfirmResult == true); Console.WriteLine("\nYour Appointment slip is being processed"); Console.WriteLine("\n Press Enter to exit"); Console.ReadLine(); Environment.Exit(0); } public static void Update(List<patientAppointment> Patient_name) { bool ConfirmResult = true; int UpdateOption = 0; string Getupdateoption; string UpdateQuantity=" "; bool result = true; patientAppointment pt = new patientAppointment(); Console.WriteLine("Which Item you want to update"); do { Getupdateoption = Console.ReadLine(); while (!int.TryParse(Getupdateoption, out UpdateOption)) { Console.WriteLine("This is not a number!"); Getupdateoption = Console.ReadLine(); } foreach (patientAppointment i in Patient_name) { if (UpdateOption == i.SNo) { ConfirmResult = false; Console.WriteLine("Enter the appointment date you want to change"); //Getting the update quantity do { //Prompt and obtain user input //get Date of Birth Console.Write("Date of Appointment: (dd/mm/yyyy): "); UpdateQuantity = Console.ReadLine(); //i.Correct_time = UpdateQuantity; //validate date input if empty and if satisfies formatting conditions if (!string.IsNullOrEmpty(UpdateQuantity) && dateCheck(UpdateQuantity)) { //end loop result = false; i.Correct_time = UpdateQuantity; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (result==true); // Checking its a proper number i.Correct_time = UpdateQuantity; } } if (ConfirmResult == true) { Console.WriteLine("Item doesnt Exist"); Console.WriteLine("Which Item you want to update"); ConfirmResult = true; } } while (ConfirmResult == true); Console.WriteLine("Updated Appointment details"); pt.Display(Patient_name); } public static void Delete(List<patientAppointment> Patient_name) { bool ConfirmResult = true; int UpdateOption = 0; string Getupdateoption; patientAppointment pt = new patientAppointment(); Console.WriteLine("Which Item you want to Delete"); do { Getupdateoption = Console.ReadLine(); while (!int.TryParse(Getupdateoption, out UpdateOption)) { Console.WriteLine("This is not a number!"); Getupdateoption = Console.ReadLine(); } ConfirmResult = false; Patient_name.RemoveAll(idel => idel.SNo == UpdateOption); } while (ConfirmResult == true); Console.WriteLine("Updated Appointment details:"); pt.Display(Patient_name); } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hospital_management { class Departments { public void displayDepartment() { int userOption; string Getoption; bool Confirmresult = false; List<patientAppointment> Patient_name = new List<patientAppointment>(); Checkup check = new Checkup(); do { Console.WriteLine("\t\t\t Welcome To Front Line Hospital"); Console.WriteLine(); Console.WriteLine("\t\tDepartments"); Console.WriteLine(); Console.WriteLine("\t\tSelect a Department:"); Console.WriteLine(); Console.WriteLine("1. Cardiology "); Console.WriteLine("2. Neurology "); Console.WriteLine("3. Dermatology "); Console.WriteLine("4. Generalcheckup"); Console.WriteLine("5. Exit "); Console.WriteLine(""); Console.WriteLine("Enter your option"); Getoption = Console.ReadLine(); while (!int.TryParse(Getoption, out userOption)) { Console.WriteLine("This is not a number!"); Getoption = Console.ReadLine(); } if ((userOption > 0) && (userOption < 5)) { Confirmresult = false; switch (userOption) { case 1: Console.Clear(); check.Cardiology_list(Patient_name); break; case 2: Console.Clear(); check.Neurology_list(Patient_name); break; case 3: Console.Clear(); check.Dermatology_list(Patient_name); break; case 4: Console.Clear(); check.Generalcheckup_list(Patient_name); break; case 5: Environment.Exit(0); break; default: Console.WriteLine("No match found"); break; } } else { Confirmresult = true; Console.Clear(); Console.WriteLine("Re-enter the options"); } } while (Confirmresult == true); } } } <file_sep>using System; using System.Net; using System.Net.Sockets; using System.IO; using System.Collections.Generic; using System.Linq; using System.Threading; namespace BankApplication { class server { static void Main(string[] args) { Console.WriteLine("Welcome!!"); Console.WriteLine("Waiting for incoming client connections..."); ServerOperation serverOperation = new ServerOperation(); Thread connectClient = new Thread(() => serverOperation.ConnectClients()); connectClient.Start(); } } public class ServerOperation { private static List<TcpClient> clients = new List<TcpClient>(); private StreamReader reader = null; private StreamWriter writer = null; readonly object _lock = new object(); readonly Dictionary<string, TcpClient> list_clients = new Dictionary<string, TcpClient>(); readonly object key = new object(); public bool locker = false; public void ConnectClients() { TcpListener ServerSocket = new TcpListener(IPAddress.Any, 5000); ServerSocket.Start(); try { Thread handle_client = new Thread(HandleClient); Thread sendTask = new Thread(SendScheme); while (true) { TcpClient client = ServerSocket.AcceptTcpClient(); Console.WriteLine("New client connected"); clients.Add(client); sendTask.Start(client); handle_client.Start(client); } } catch (ThreadStartException) { } } public void HandleClient(object o) { List<string> loan = new List<string>(); List<string> creditcard = new List<string>(); List<string> providentfund = new List<string>(); loan.Add("Loan offer 12%"); loan.Add("Loan offer 22%!!! avail soon"); creditcard.Add("credit card offer!!!! 15% discount on abc bank account holders"); creditcard.Add("credit card offer 70%"); providentfund.Add("PF offer!!! for you"); providentfund.Add("This is a pf offer"); var messages = loan .Concat(creditcard) .Concat(providentfund) .ToList(); // Monitor.Wait(this); TcpClient client = (TcpClient)o; string option = string.Empty; string scheme = string.Empty; writer = new StreamWriter(client.GetStream()); reader = new StreamReader(client.GetStream()); Console.WriteLine("entered server"); try { while (!(option = reader.ReadLine()).Equals("Exit") || (option == null)) { if (!client.Connected) { Console.WriteLine("Client disconnected."); } locker = true; if (option == "1") { Console.WriteLine("Client requested for Loan messages"); foreach (string loanmessages in loan) { writer.WriteLine(loanmessages); writer.Flush(); Thread.Sleep(1000); } } else if (option == "2") { Console.WriteLine("Client requested for credit card messages"); foreach (string creditmsg in creditcard) { writer.WriteLine(creditmsg); writer.Flush(); Thread.Sleep(1000); } } else if (option == "3") { Console.WriteLine("Client requested provident fund messages"); foreach (string providentmsg in providentfund) { writer.WriteLine(providentmsg); writer.Flush(); Thread.Sleep(1000); } } } CloseServer(reader,writer); } catch (System.IO.IOException) { } catch (Exception e) { Console.WriteLine(e); } } public void SendScheme(object o) { List<string> loan = new List<string>(); List<string> creditcard = new List<string>(); List<string> providentfund = new List<string>(); loan.Add("Loan offer 12%"); loan.Add("Loan offer 22%!!! avail soon"); creditcard.Add("credit card offer!!!! 15% discount on abc bank account holders"); creditcard.Add("credit card offer 70%"); providentfund.Add("PF offer!!! for you"); providentfund.Add("This is a pf offer"); var messages = loan .Concat(creditcard) .Concat(providentfund) .ToList(); TcpClient client = (TcpClient)o; StreamWriter writer; writer = new StreamWriter(client.GetStream()); try { while (locker == false) { foreach (string msg in messages) { writer.WriteLine(msg); writer.Flush(); Thread.Sleep(3000); } } } catch (InvalidOperationException e) { Console.WriteLine(e); } catch (System.IO.IOException) { } catch (Exception e) { Console.WriteLine(e.Message); } } private static void CloseServer(StreamReader reader, StreamWriter writer) { reader.Close(); writer.Close(); clients.ForEach(tcpClient => tcpClient.Close()); } } } <file_sep>class Vehicle { constructor(name, brand, color) { this.name = name; this.brand = brand; this.color = color; } describecar(){ console.log("Name :" + this.name ); console.log("Brand: " + this.brand + " " + "Color:" +this.color); } } const figo = new Vehicle('Figo', 'Ford', 'Green'); figo.describecar(); const estilo = new Vehicle('Zen Estilo', 'Maruti', 'Brown'); estilo.describecar();<file_sep>let carname = "Alto"; var brand="Maruti"; var price="500000"; function describe_data(){ console.log(`The price of the brand ${this.brand} is ${this.price}`); } const vehicle ={ carname:"Innova", color:"blue", display_data:function(){ console.log(`Car name is`+this.carname+`which is of color`+this.color);//prints the local variable of vehicle object console.log(`Car name is `+carname +`which belongs to brand`+brand+`of price`+price);//prints the global variables } } window.describe_data(); console.log(window.brand);//prints the brand since the global variable is accessible by window object console.log(window.carname);//does not print because of the let keyword vehicle.display_data();<file_sep>//This can be illustrated for inheritance also function Car(name,color) { this.name = name; this.color = color; } Car.prototype.display = function () { console.log(this.car); } function Car_showroom(name) { this.name = name; this.cars = []; } Car_showroom.prototype.add = function (item) { this.cars.push(item); } Car_showroom.prototype.getCarName = function (index) { return this.cars[index].name; } Car_showroom.prototype.getCarColor = function(index) { return this.cars[index].color; } Car_showroom.prototype.describe = function() { console.log(this.name); for (let i = 0, length = this.cars.length; i < length; i++) { console.log(" ", this.getCarName(i) , "of color " , this.getCarColor(i)); } } Showroom1 = new Car_showroom('Showroom 1'); Showroom2 = new Car_showroom('Showroom 2'); Showroom3 = new Car_showroom('Showroom 3'); car1 = new Car('Maruti800' , 300000); car2 = new Car('Benz' , 900000); car3 = new Car('Audi' , 1000000); Showroom1.add(car1); Showroom1.add(car2); Showroom2.add(car1); Showroom2.add(car3); Showroom3.add(car1); Showroom3.add(car2); Showroom3.add(car3); Showroom1.describe(); Showroom2.describe(); Showroom3.describe();<file_sep>using System; using System.Collections.Generic; namespace Hospital_management { class loginSystem { public void loginUser() { var arrUsers = new Users[] { new Users("Aparna","<PASSWORD>"), new Users("John","<PASSWORD>"), new Users("Ganesh","<PASSWORD>") }; var username = ""; var password =""; Start: Console.WriteLine("Press 1 for Login and 2 for Register"); var input = Console.ReadLine(); bool successfull = true; do { switch (input) { case "1": Console.WriteLine("Write your username:"); username = Console.ReadLine(); Console.WriteLine("Enter your password:"); password = Console.ReadLine(); foreach (Users user in arrUsers) { if (username == user.username && password == <PASSWORD>) { Console.WriteLine("You have successfully logged in !!!"); Console.WriteLine("Press Enter to continue:"); Console.ReadLine(); Console.Clear(); successfull = false; } } break; case "2": Console.WriteLine("Enter your username:"); username= Console.ReadLine(); Console.WriteLine("Enter your password:"); password = Console.ReadLine(); Array.Resize(ref arrUsers, arrUsers.Length + 1); arrUsers[arrUsers.Length - 1] = new Users(username, password); //successfull = true; goto Start; default: Console.WriteLine("Try again !!!"); goto Start; } if (successfull == false) { return; } if (successfull == true) { Console.WriteLine("Your username or password is incorect, try again !!!"); } } while (successfull == true); } } } <file_sep> using System; using System.Globalization; using System.IO; using System.Linq; namespace Hospital_management { public class patientInfo { static bool DateCheck(string stringdate) { // Define the acceptable date formats and check if entered date is valid string[] formats = { "d/MM/yyyy", "dd/MM/yyyy", "d/M/yyyy" }; string bdate = stringdate; DateTime parsedDate; try { //Conversion from string to Date time bool isValidFormat = DateTime.TryParseExact(stringdate, formats, new CultureInfo("ta-IN"), DateTimeStyles.None, out parsedDate); if (isValidFormat) { // If date is valid, check whether the given year is more than the year Today if (CalculateAge(parsedDate.ToString()) < 0) { Console.WriteLine("Birth date must be prior to today!"); return false; } else { //end do while Loop return true; } } else { //if not a valid date, give an error Console.WriteLine("Wrong Date format"); return false; } } catch (FormatException) { //Catch format exception errors on date return false; } } // Define a function to calculate a person's age by subtracting their yearOfBirth from the current year static int CalculateAge(string dateOfbirth) { DateTime birthDay = DateTime.Parse(dateOfbirth); int years = DateTime.Now.Year - birthDay.Year; return years; } //A function to check if a given phone/telephone number is null, a number or less/greater than 10 digits static bool checkPhoneNumber(string phoneNumber) { string number = phoneNumber; //check if empty if (String.IsNullOrEmpty(number)) { Console.WriteLine("Number field is empty!"); return false; } //check if all characters are digits else if (!number.All(char.IsNumber)) { Console.WriteLine("Number must be a number!"); return false; } //check if length is equal to 10 else if (number.Length != 10) { Console.WriteLine("Improper number of numeric digits for a phone number."); return false; } else { return true; } } public void patient_info() { //Create Patient and contact objects Patient patient = new Patient(); Contact contact = new Contact(); ResidentPatient inpatient = new ResidentPatient(); OutPatient outpatient = new OutPatient(); Console.Write("Welcome to Front Line Hospital!\n"); //Loop over the app while (true) { Console.Write("Enter data about a patient\n"); //Prompt for patient type and get user input do { Console.Write("Patient type: O(ut), R(esident)?: "); patient.PatientType = Console.ReadLine(); //check if empty field given if (string.IsNullOrEmpty(patient.PatientType)) { Console.WriteLine("Patient Type is empty!"); } //check if a valid symbol/word is given else if (patient.PatientType.ToLower() != "o" && patient.PatientType.ToLower() != "out" && patient.PatientType.ToLower() != "resident" && patient.PatientType.ToLower() != "r") { Console.WriteLine("Enter a valid patient type!"); } else { break; } } while (true); do { //Prompt and obtain user input //get first name Console.Write("First Name: "); patient.FirstName = Console.ReadLine(); //check if user entered empty string as Firstname if (string.IsNullOrEmpty(patient.FirstName)) { Console.WriteLine("First Name is empty!"); } //Check if name consists of letters only else if (!patient.FirstName.ToLower().All(char.IsLetter)) { Console.WriteLine("First name must consist of letters only!"); } else { //end do while Loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get last name Console.Write("Last Name: "); patient.LastName = Console.ReadLine(); //check if user entered empty string as lastname if (string.IsNullOrEmpty(patient.LastName)) { Console.WriteLine("Last Name is empty!"); } //Check if name consists of letters only else if (!patient.LastName.ToLower().All(char.IsLetter)) { Console.WriteLine("Last name must consist of letters only!"); } else { //end do while Loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get Gender Console.Write("Gender (M/F): "); // set input string to uppercase patient.Gender = Console.ReadLine().ToUpper(); //validate gender field empty if (String.IsNullOrEmpty(patient.Gender)) { Console.WriteLine("Gender field is Empty!"); } //validate if gender is male or female else if (patient.Gender.ToUpper() != "M" && patient.Gender.ToUpper() != "F") { Console.WriteLine("Gender must be M or F!"); } else { //end do while Loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get Married status Console.Write("Married? (Y/N): "); // set input string to uppercase patient.Married = Console.ReadLine().ToUpper(); //validate input if empty if (String.IsNullOrEmpty(patient.Married)) { Console.WriteLine("Married field is Empty!"); } //check if input is Yes or No else if (patient.Married.ToUpper() != "Y" && patient.Married.ToUpper() != "N") { Console.WriteLine("Marriage status must be Y or N!"); } else { //end do while Loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get Date of Birth Console.Write("Date of Birth: (dd/mm/yyyy): "); patient.BirthDate = Console.ReadLine(); //validate date input if empty and if satisfies formatting conditions if (!string.IsNullOrEmpty(patient.BirthDate) && DateCheck(patient.BirthDate)) { //end loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt user to enter input //For their street address Console.Write("Street Address: "); patient.StreetAddress = Console.ReadLine(); //validate if the input field is empty if (!string.IsNullOrEmpty(patient.StreetAddress)) { //end do while Loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get City Console.Write("City: "); patient.City = Console.ReadLine(); //validate if the entered value field is empty if (string.IsNullOrEmpty(patient.City)) { Console.WriteLine("City Field is empty!"); } //validate if the city name atleast has a string character else if (patient.City.All(char.IsNumber)) { Console.WriteLine("Enter a valid city name!"); } else { //end do while Loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get State Console.Write("State: "); patient.State = Console.ReadLine(); //Check if the field is empty if (string.IsNullOrEmpty(patient.State)) { Console.WriteLine("State field is empty!"); } //An array containing all 50 states in the U.S string[] UsStates = { "Delhi","Karnataka","Kerala","Tamil Nadu","Mumbai","Goa","Punjab","Kolkata","Andhra pradesh","Orissa","Gujarat","Jammu & Kashmir","J&K", "Bihar","Assam","Andhra"}; //Boolean variable to mark a user entry as a valid state or not bool isValidState = false; //Loop through all possible states checking if a given city is valid for (int i = 0; i < UsStates.Length; i++) { if (patient.State.ToString().ToUpper() != UsStates[i].ToUpper()) { isValidState = false; } else { //If the user input is a valid state, mark state as valid and break out of the for loop isValidState = true; break; } } //If the user input is a valid state, break out of the do-while loop if (isValidState) { break; } else { //If the user input is a invalid state, give error message and continue executing the do-while loop Console.WriteLine(patient.State + " is not an Indian state"); continue; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get Zip code Console.Write("Zip: "); patient.Zip = Console.ReadLine(); //validate if input field is empty if (string.IsNullOrEmpty(patient.Zip)) { Console.WriteLine("Zip field is empty!"); } //check if the code contains only number characters else if (!patient.Zip.All(char.IsNumber)) { Console.WriteLine("Zip code must be a number!"); } //Validate the length of the zip code to 5 digits only else if (patient.Zip.Length != 6) { Console.WriteLine("Zip should consist of 6 digits"); } else { //end do while Loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get Home phone Console.Write("Home Phone: "); contact.HomeNumber = Console.ReadLine(); //call function to validate number bool validNumber = checkPhoneNumber(contact.HomeNumber); //if valid, break out of the do-while loop else, keep looping if (validNumber) { break; } else { continue; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); do { //Prompt and obtain user input //get Mobile number Console.Write("Mobile Phone: "); contact.MobileNumber = Console.ReadLine(); //Call function to validate entered number bool validNumber = checkPhoneNumber(contact.MobileNumber); //if valid, break out of loop if (validNumber) { break; } else { continue; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); //Boolean variable to track if a patient is a resident or out patient bool patientresident = false; //Check if the entered value is "out" or "o" if (patient.PatientType.ToLower() == "out" || patient.PatientType.ToLower() == "o") { //Set current patient to non-resident patientresident = false; do { //Get user input on contact information //Input contact first name Console.Write("Contact First Name: "); outpatient.ContactFirstName = Console.ReadLine(); //Check if name field empty if (string.IsNullOrEmpty(outpatient.ContactFirstName)) { Console.WriteLine("Contact First Name is empty!"); } //Check if name consists of letters only else if (!outpatient.ContactFirstName.ToLower().All(char.IsLetter)) { Console.WriteLine("Contact First name must consist of letters only!"); } else { //end do while Loop break; } } while (true); do { //input last name Console.Write("Contact Last Name: "); outpatient.ContactLastName = Console.ReadLine(); //check if field empty if (string.IsNullOrEmpty(outpatient.ContactLastName)) { Console.WriteLine("Last Name is empty!"); } //check if name consists of letters only else if (!outpatient.ContactLastName.ToLower().All(char.IsLetter)) { Console.WriteLine("Contact Last name must consist of letters only!"); } else { //end do while Loop break; } } while (true); do { //Input contact phone number Console.Write("Contact Phone: "); contact.ContactPhone = Console.ReadLine(); //call function to validate the number bool validNumber = checkPhoneNumber(contact.ContactPhone); if (validNumber) { //end do while Loop break; } else { continue; } } while (true); } //check if the resident type is "resident" or "r" if (patient.PatientType.ToLower() == "resident" || patient.PatientType.ToLower() == "r") { //Set patient to resident patientresident = true; do { //Prompt for hospital details //Input hospital name Console.Write("Problem: "); inpatient.ProblemName = Console.ReadLine(); //check if name field is empty if (string.IsNullOrEmpty(inpatient.ProblemName)) { Console.WriteLine("Problem name is empty!"); } //check if the field only contains number characters else if (inpatient.ProblemName.All(char.IsNumber)) { Console.WriteLine("Enter a valid problem!"); } else { //break out of loop if all conditions satisfied break; } } while (true); } display_patient_info(patient,contact,inpatient,outpatient); do { Console.Write("Do you want to continue (Y/N)?: "); patient.check = Console.ReadLine().ToUpper(); // set input string to uppercase //validate input if Yes or No if (patient.check == "N" || patient.check == "Y") { //end do while Loop, return to the main while loop break; } //loop until a valid value has been entered } while (patient.check != "Y" || patient.check != "N"); if (patient.check == "Y") { //end user input prompt return; } if (patient.check == "N") { //end user input prompt loginSystem login = new loginSystem(); login.loginUser(); } } } public void display_patient_info(Patient patient,Contact contact,ResidentPatient inpatient,OutPatient outpatient) { //Call function to calculate patient age bool patientin = false; int patientAge = CalculateAge(patient.BirthDate); StreamWriter sw = new StreamWriter(@"Bill.txt"); StreamWriter sw1 = File.AppendText(@"Appointments.txt"); //Enter 3 blank lines Console.Write("\n\n\n"); //Display patient Data //check gender and appropriate Title(Mr or Ms) Console.WriteLine("----------------------------------------------------------------------------------------"); Console.WriteLine("Patient Details"); Console.WriteLine("----------------------------------------------------------------------------------------"); sw.WriteLine("----------------------------------------------------------------------------------------"); sw.WriteLine("Patient Details"); sw.WriteLine("----------------------------------------------------------------------------------------"); sw1.WriteLine("----------------------------------------------------------------------------------------"); sw1.WriteLine("Patient Details"); sw1.WriteLine("----------------------------------------------------------------------------------------"); Console.Write("Name :"); sw.Write("Name :"); sw1.Write("Name :"); Console.Write(patient.Gender == "M" ? "Mr. " : "Ms. "); sw.Write(patient.Gender == "M" ? "Mr. " : "Ms. "); sw1.Write(patient.Gender == "M" ? "Mr. " : "Ms. "); //Format first name and concatenate to second name Console.Write((patient.LastName) + ", " + (patient.FirstName) + "\t"); sw.Write((patient.LastName) + ", " + (patient.FirstName) + "\t"); sw1.Write((patient.LastName) + ", " + (patient.FirstName) + "\t"); //Output patient type Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); Console.Write("Type of Patient :"); sw.Write("Type of Patient :"); sw1.Write("Type of Patient :"); Console.WriteLine( patient.PatientType.ToLower() == "resident" || patient.PatientType.ToLower() == "r" ? "ResidentPatient, " : "OutPatient"); sw.WriteLine(patient.PatientType.ToLower() == "resident" || patient.PatientType.ToLower() == "r" ? "ResidentPatient, " : "OutPatient"); sw1.WriteLine(patient.PatientType.ToLower() == "resident" || patient.PatientType.ToLower() == "r" ? "ResidentPatient, " : "OutPatient"); //Output marital status Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); Console.Write("Status:"); sw.Write("Status :"); sw1.Write("Status :"); Console.WriteLine(patient.Married == "Y" ? "Married " : "Single "); sw.WriteLine(patient.Married == "Y" ? "Married " : "Single "); sw1.WriteLine(patient.Married == "Y" ? "Married " : "Single "); Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); //output calculated age Console.WriteLine("Age: " + patientAge + ", "); sw.WriteLine("Age: " + patientAge + ", "); sw1.WriteLine("Age: " + patientAge + ", "); Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); //Format and output expenses value //Output street address Console.Write("Address :" + patient.StreetAddress + ", "); sw.Write("Address :" + patient.StreetAddress + ", "); sw1.Write("Address :" + patient.StreetAddress + ", "); //output city Console.Write(patient.City + ", "); sw.Write(patient.City + ", "); sw1.Write(patient.City + ", "); //output State in UPPERCASE Console.Write(patient.State.ToUpper() + " "); sw.Write(patient.State.ToUpper() + " "); sw1.Write(patient.State.ToUpper() + " "); //output zip code Console.Write(patient.Zip + ". "); sw.Write(patient.Zip + ". "); sw1.Write(patient.Zip + ". "); Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); //Format and output home number and mobile number Console.WriteLine("Home number :" +" "+String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.HomeNumber)) + "/"); sw.WriteLine("Home number :" + " "+ String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.HomeNumber)) + "/"); sw1.WriteLine("Home number :" + " " + String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.HomeNumber)) + "/"); Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); Console.WriteLine("Mobile number :" + " " + String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.MobileNumber)) + ". "); sw.WriteLine("Mobile number :" + " " +String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.MobileNumber)) + ". "); sw1.WriteLine("Mobile number :" + " " + String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.MobileNumber)) + ". "); Console.WriteLine(); sw.WriteLine(); sw1.WriteLine(); if (patientin) { Console.WriteLine(); //Format and output hospital name and phone number Console.Write("Problem: " + inpatient.ProblemName + " / "); sw.Write("Problem: " + inpatient.ProblemName + " / "); sw1.Write("Problem: " + inpatient.ProblemName + " / "); } else { Console.WriteLine(); //Format and output contact names and phone number Console.Write("Contact: " +(outpatient.ContactFirstName) + " , " + (outpatient.ContactLastName) + " / "); Console.Write(String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.ContactPhone))); sw.Write("Contact: " + (outpatient.ContactFirstName) + " , " + (outpatient.ContactLastName) + " / "); sw.Write(String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.ContactPhone))); sw1.Write("Contact: " + (outpatient.ContactFirstName) + " , " + (outpatient.ContactLastName) + " / "); sw1.Write(String.Format("{0:(###) ###-####}", Convert.ToInt64(contact.ContactPhone))); } sw.WriteLine(); sw1.WriteLine(); sw.WriteLine("----------------------------------------------------------------------------------------"); sw1.WriteLine("----------------------------------------------------------------------------------------"); Console.Write("\n\n\n"); //Prompt and obtain user input //user wants to continue or Quit Console.Write("\n\n\n"); sw.Flush(); sw.Close(); sw1.Close(); } } } <file_sep>using System; //Author: namespace Hospital_management { public class Patient { public string PatientType { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Gender { get; set; } public string Married { get; set; } public string BirthDate { get; set; } public string StreetAddress { get; set; } public string City { get; set; } public string State { get; set; } public string Zip { get; set; } public string check { get; set; } } public class OutPatient : Patient { public string ContactFirstName { get; set; } public string ContactLastName { get; set; } } public class ResidentPatient : Patient { public string ProblemName{ get; set; } } public class Contact { public string HomeNumber { get; set; } public string MobileNumber { get; set; } public string ContactPhone { get; set; } } }<file_sep>--EASY --1.Show the first name and the email address of customer with CompanyName 'Bike World' SELECT FirstName,EmailAddress FROM Customer WHERE CompanyName = 'Bike World'; --2.Show the CompanyName for all customers with an address in City 'Dallas'. SELECT CompanyName FROM Customer JOIN CustomerAddress ON Customer.CustomerID = CustomerAddress.CustomerID JOIN Addressb ON CustomerAddress.AddressID = Address.AddressID WHERE Address.City = 'Dallas'; --3.How many items with ListPrice more than $1000 have been sold? SELECT COUNT(*) AS Total FROM SalesOrderDetail JOIN Product ON SalesOrderDetail.ProductID = Product.ProductID WHERE Product.ListPrice > 1000; --4.Give the CompanyName of those customers with orders over $100000. Include the subtotal plus tax plus freight. SELECT Customer.CompanyName FROM SalesOrderHeader JOIN Customer ON SalesOrderHeader.CustomerID = Customer.CustomerID WHERE SalesOrderHeader.SubTotal + SalesOrderHeader.TaxAmt + SalesOrderHeader.Freight > 100000; --5.Find the number of left racing socks ('Racing Socks, L') ordered by CompanyName 'Riding Cycles' SELECT SUM(SalesOrderDetail.OrderQty) As Total FROM SalesOrderDetail JOIN Product ON SalesOrderDetail.ProductID = Product.ProductID JOIN SalesOrderHeader ON SalesOrderDetail.SalesOrderID = SalesOrderHeader.SalesOrderID JOIN Customer ON SalesOrderHeader.CustomerID = Customer.CustomerID WHERE Product.Name = 'Racing Socks, L' AND Customer.CompanyName = 'Riding Cycles'; --MEDIUM --6.A "Single Item Order" is a customer order where only one item is ordered. Show the SalesOrderID and the UnitPrice for every Single Item Order. SELECT SalesOrderID,UnitPrice FROM SalesOrderDetail WHERE OrderQty = 1; --7.Where did the racing socks go? List the product name and the CompanyName for all Customers who ordered ProductModel 'Racing Socks'. SELECT Product.name, Customer.CompanyName FROM ProductModel JOIN Product ON ProductModel.ProductModelID = Product.ProductModelID JOIN SalesOrderDetail ON SalesOrderDetail.ProductID = Product.ProductID JOIN SalesOrderHeader ON SalesOrderDetail.SalesOrderID = SalesOrderHeader.SalesOrderID JOIN Customer ON SalesOrderHeader.CustomerID = Customer.CustomerID WHERE ProductModel.Name = 'Racing Socks'; --8.Show the product description for culture 'fr' for product with ProductID 736. SELECT ProductDescription.Description FROM ProductDescription JOIN ProductModelProductDescription ON ProductDescription.ProductDescriptionID = ProductModelProductDescription.ProductDescriptionID JOIN ProductModel ON ProductModelProductDescription.ProductModelID = ProductModel.ProductModelID JOIN Product ON ProductModel.ProductModelID = Product.ProductModelID WHERE ProductModelProductDescription.culture = 'fr'AND Product.ProductID = '736'; --9.Use the SubTotal value in SaleOrderHeader to list orders from the largest to the smallest. For each order show the CompanyName and the SubTotal and the total weight of the order. SELECT Customer.CompanyName,SalesOrderHeader.SubTotal, SUM(SalesOrderDetail.OrderQty * Product.weight) FROM Product JOIN SalesOrderDetail ON Product.ProductID = SalesOrderDetail.ProductID JOIN SalesOrderHeader ON SalesOrderDetail.SalesOrderID = SalesOrderHeader.SalesorderID JOIN Customer ON SalesOrderHeader.CustomerID = Customer.CustomerID GROUP BY SalesOrderHeader.SalesOrderID, SalesOrderHeader.SubTotal, Customer.CompanyName ORDER BY SalesOrderHeader.SubTotal DESC; --10.How many products in ProductCategory 'Cranksets' have been sold to an address in 'London'? SELECT SUM(SalesOrderDetail.OrderQty) FROM ProductCategory JOIN Product ON ProductCategory.ProductCategoryID = Product.ProductCategoryID JOIN SalesOrderDetail ON Product.ProductID = SalesOrderDetail.ProductID JOIN SalesOrderHeader ON SalesOrderDetail.SalesOrderID = SalesOrderHeader.SalesorderID JOIN Address ON SalesOrderHeader.ShipToAddressID = Address.AddressID WHERE Address.City = 'London' AND ProductCategory.Name = 'Cranksets'; --HARD --11.For every customer with a 'Main Office' in Dallas show AddressLine1 of the 'Main Office' and AddressLine1 of the 'Shipping' address - if there is no shipping address leave it blank. Use one row per customer. SELECT Customer.CompanyName,MAX(CASE WHEN AddressType = 'Main Office' THEN AddressLine1 ELSE '' END) AS 'Main Office Address', MAX(CASE WHEN AddressType = 'Shipping' THEN AddressLine1 ELSE '' END) AS 'Shipping Address' FROM Customer JOIN CustomerAddress ON Customer.CustomerID = CustomerAddress.CustomerID JOIN Address ON CustomerAddress.AddressID = Address.AddressID WHERE Address.City = 'Dallas' GROUP BY Customer.CompanyName; --12.For each order show the SalesOrderID and SubTotal calculated three ways: A) From the SalesOrderHeader B) Sum of OrderQty*UnitPrice C) Sum of OrderQty*ListPrice SELECT SalesOrderHeader.SalesOrderID,SalesOrderHeader.SubTotal,SUM(SalesOrderDetail.OrderQty * SalesOrderDetail.UnitPrice),SUM(SalesOrderDetail.OrderQty * Product.ListPrice) FROM SalesOrderHeader JOIN SalesOrderDetail ON SalesOrderHeader.SalesOrderID = SalesOrderDetail.SalesOrderID JOIN Product ON SalesOrderDetail.ProductID = Product.ProductID GROUP BY SalesOrderHeader.SalesOrderID,SalesOrderHeader.SubTotal; --13.Show the best selling item by value. SELECT Product.Name,SUM(SalesOrderDetail.OrderQty * SalesOrderDetail.UnitPrice) AS Total_Sale_Value FROM Product JOIN SalesOrderDetail ON Product.ProductID = SalesOrderDetail.ProductID GROUP BY Product.Name ORDER BY Total_Sale_Value DESC; <file_sep>using System; namespace Hospital_management { class Program { public static void Main(string[] args) { Console.WriteLine("Welcome to Front Line Hospital!!"); Console.WriteLine(); loginSystem login = new loginSystem(); login.loginUser(); patientInfo p = new patientInfo(); p.patient_info(); Departments d = new Departments(); d.displayDepartment(); } } }<file_sep>function car(brand,color,noofwheels,price,tax,deliverycharge) { this.brand=brand; this.color=color; this.noofwheels=noofwheels; this.price=price; this.tax=tax; this.deliverycharge=deliverycharge; this.display_data=function(){ console.log(`The car is of brand ${this.brand},color ${this.color} and has ${this.noofwheels} wheels `); }; this.calculate_originalprice=function(){ return ((this.price+this.tax+this.deliverycharge)*10); }; this.display_originalprice=function(){ var original_price=this.calculate_originalprice(); console.log(`The original price of the car is`+original_price); }; } var Benz=new car("Mercedes","Red",4,9000000,20,100); Benz.display_data(); Benz.display_originalprice(); console.log(Benz.price);//this variable can be accessed console.log(Benz.brand);//this variable can be accessed console.log(Benz.color);//this variable can be accessed console.log(Benz.original_price);//the variable original_price cannot be accessed because it is a private variable encapsulated inside display_originalprice <file_sep>using System.Net.Sockets; using System.Net; using System.IO; using System; using System.Collections.Generic; using System.Threading; namespace BankApplication { class client1 { private static TcpClient client = new TcpClient(); public static void Main() { Console.Title = "Client"; StreamWriter writer; bool pass = false; do { Console.WriteLine("Connecting to server..."); try { Console.WriteLine("Enter the ip address:"); IPAddress ip = IPAddress.Parse(Console.ReadLine()); Console.WriteLine("Enter the port number:"); int port = Convert.ToInt32(Console.ReadLine()); TcpClient client = new TcpClient(); client.Connect(ip, port); writer = new StreamWriter(client.GetStream()); Console.WriteLine("Connected."); Console.WriteLine("Press Enter to proceed"); writer.WriteLine(Console.ReadLine()); Operation op = new Operation(); Thread sendTask = new Thread(() => op.SendMessage(client, pass)); //task for sending messages Thread receiveTask = new Thread(() => op.ReceiveMessage(client)); //task for recieving messages receiveTask.Start(); Console.ReadLine(); pass = true; sendTask.Start(); sendTask.Join(); break; // updateConvTask.Start(); // receiveTask.Join(); //sendTask.Join(); } catch (SocketException) { } Thread.Sleep(10); } while (!client.Connected); } } public class Operation { private TcpClient client = new TcpClient(); private List<string> messages = new List<string>(); readonly object key = new object(); static bool Waitcheck = false; public void SendMessage(TcpClient client, bool pass) { Waitcheck = true; Thread.Sleep(5000); Console.WriteLine("Enter pressed"); StreamReader reader = null; StreamWriter writer = null; writer = new StreamWriter(client.GetStream()); reader = new StreamReader(client.GetStream()); lock (key) { if (pass == true) { Console.WriteLine("Enter M for menu and E to exit"); string msgToSend = string.Empty; msgToSend = Console.ReadLine(); switch (msgToSend) { case "E": EndConnection(reader,writer,client); break; case "M": Menu(client, pass); break; default: Console.WriteLine("No input"); break; } } } } public static void Menu(TcpClient client, bool pass) { StreamReader reader = null; StreamWriter writer = null; writer = new StreamWriter(client.GetStream()); reader = new StreamReader(client.GetStream()); int UserOption; string GetOption; bool Confirm = false; do { Console.WriteLine("Please choose a particular scheme"); Console.WriteLine(); Console.WriteLine("1. Loan "); Console.WriteLine("2. Credit card "); Console.WriteLine("3. Provident fund "); Console.WriteLine(); GetOption = Console.ReadLine(); while (!int.TryParse(GetOption, out UserOption)) { Console.WriteLine("This is not a number!"); GetOption = Console.ReadLine(); } if ((UserOption > 0) && (UserOption < 4)) { Confirm = false; switch (UserOption) { case 1: //Console.Clear(); Console.WriteLine("You requested for Loan messages"); writer.WriteLine("1"); writer.Flush(); break; case 2: //Console.Clear(); Console.WriteLine("You requested for credit card messages"); writer.WriteLine("2"); writer.Flush(); break; case 3: //Console.Clear(); Console.WriteLine("You requested for provident fund"); writer.WriteLine("3"); writer.Flush(); break; default: Console.WriteLine("No match found"); break; } Console.Clear(); while (pass == true) { string msg = reader.ReadLine(); Console.WriteLine(msg); } } else { Confirm = true; Console.Clear(); Console.WriteLine("Re-enter the options"); } } while (Confirm == true); } public void ReceiveMessage(TcpClient client) { lock (key) { if (Waitcheck == true) { //Monitor.Pulse(key); Monitor.Wait(key); Waitcheck = false; } while (Waitcheck==false) { StreamReader reader; reader = new StreamReader(client.GetStream()); string msg = reader.ReadLine(); Console.WriteLine(msg); } } } private static void EndConnection(StreamReader reader,StreamWriter writer,TcpClient client) { reader.Close(); writer.Close(); client.Close(); } } } <file_sep>var current_page = 1; var records_per_page = 5; var count = Object.keys(record_copy).length; function go() { records_per_page = document.getElementById("myInput1").value; validation(records_per_page); current_page = 1; changePage(current_page); document.getElementById("myInput1").value=" "; } function show() { records_per_page = document.getElementById("sel").value; current_page = 1; changePage(current_page); } function gotopage() { current_page = document.getElementById("myInput2").value; validategotopage(current_page); changePage(current_page); document.getElementById("myInput2").value=" "; } function validategotopage(y) { if (y == "") { alert("Enter some page number"); return false; } else if (y > numPages()) { alert("The page number entered is not available"); insertNewRecord(data); return false; } else if (y < 0) { alert("Page number should be positive"); insertNewRecord(data); return false; } else if (y = 0) { alert("Enter a valid page number"); insertNewRecord(data); return false; } else { return true; } } function validation(x) { if (x == "") { alert("Enter some value"); insertNewRecord(data); return false; } else if ((x < 0) || x > Object.keys(records).length) { alert("Enter valid number of records"); insertNewRecord(data); return false; } else { return true; } } function prevPage() { deleteall(); if (current_page > 1) { current_page--; changePage(current_page); } } function nextPage() { deleteall(); if (current_page < numPages()) { current_page++; changePage(current_page); } } function changePage(page) { deleteall(); var btn_next = document.getElementById("btn_next"); var btn_prev = document.getElementById("btn_prev"); //var listing_table = document.getElementById("listingTable"); var page_span = document.getElementById("page"); // Validate page if (page < 1) page = 1; if (page > numPages()) page = numPages(); for (var i = (page - 1) * records_per_page; i < (page * records_per_page) && i < records.length; i++) { var table = document.getElementById("myTable").getElementsByTagName('tbody')[0]; var newRow = table.insertRow(table.length); cell1 = newRow.insertCell(0); cell1.innerHTML = `<input id="chk" type="checkbox" value="check"/>` cell1 = newRow.insertCell(1); cell1.innerHTML = record_copy[i].itemName; cell2 = newRow.insertCell(2); cell2.innerHTML = record_copy[i].description; cell3 = newRow.insertCell(3); cell3.innerHTML = record_copy[i].price; cell4 = newRow.insertCell(4); cell4.innerHTML = record_copy[i].category; cell4 = newRow.insertCell(5); cell4.innerHTML = `<input type='button' class="Edit" value='Edit' onclick='onEdit(this)'> <input type='button' class="Read" value='Read' onclick='onRead(this)'> <input type='button' class="Delete" value='Delete' onclick='onDelete(this)'>` } page_span.innerHTML = page; if (page == 1) { btn_prev.style.visibility = "hidden"; } else { btn_prev.style.visibility = "visible"; } if (page == numPages()) { btn_next.style.visibility = "hidden"; } else { btn_next.style.visibility = "visible"; } } function numPages() { return Math.ceil(Object.keys(record_copy).length / records_per_page); } function num_pages_after() { return Math.ceil(Object.keys(record_copy).length); } window.onload = function () { changePage(1); };<file_sep>var car=(function() //Main Module { var carname="Audi"; var price=500000; var discount=2000; var discountpercent; console.log(carname); var discounted_price=function(){ return price-discount; } discountpercent=discounted_price()/100; let find_warrantyperiod=(function(){ //SubModule let warranty; if(carname=="Audi") { warranty=5; } return warranty; })(); console.log("The warranty period for Audi is"+" "+find_warrantyperiod+" "+"years"); return discountpercent; }()); console.log(car);<file_sep>function car(name,price,color) { this.name=name; this.price=price; this.color=color; this.describe=function(){ console.log(this.name); console.log(this.price); console.log(this.color); } } car.prototype.noofwheels=function(){ console.log(this.name +" "+"has four wheels"); } const car_obj1=new car("Dzire",900000,"Grey"); const car_obj2=new car("Benz",1000000,"Black"); const car_obj3=new car("Audi",2000000,"Blue"); car_obj1.describe(); car_obj2.describe(); car_obj3.describe(); car_obj1.noofwheels(); car_obj2.noofwheels(); car_obj3.noofwheels(); car.prototype={ type:"petrol", warranty:"5 years", } console.log(car_obj1.type);//gives undefined because the updated values are not known for car_obj1,car_obj2,car_obj3 console.log(car_obj1.name);//This is accessible beacuse the old properties still exists const car_obj4=new car();//A new object created for car console.log(car_obj4.type);//This will give the updated value<file_sep> using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; using System.Xml.Serialization; namespace Hospital_management { class Bill { public static void PrintBill(List<patientAppointment> Patient_name) //Printing bill { var SNo = 1; DateTime now = DateTime.Now; Patient patient = new Patient(); File.Delete(@"Jsonfile.txt"); File.Delete("@Xmlfile.xml"); StreamWriter sw = File.AppendText(@"Bill.txt"); sw.WriteLine(); sw.WriteLine("-----------------------FrontLine Hospital appointment ---------------------------------"); sw.WriteLine("----------------------------------------------------------------------------------------");//Displaying the order sw.WriteLine($"{"SNo",13}" + "\t" + $"{"Checkup_Name",13}" + "\t" + "\t" +$"{"Appointment Date",13}"); sw.WriteLine("----------------------------------------------------------------------------------------"); sw.WriteLine(); SNo = 1; foreach (patientAppointment i in Patient_name) { i.SNo = SNo; sw.WriteLine($"{i.SNo,10} \t {i.Checkup_Name,10}{i.Correct_time,10}"); SNo += 1; } sw.WriteLine("----------------------------------------------------------------------------------------"); sw.Flush(); sw.Close(); } public static void saveasjson(List<patientAppointment> Patient_name) { using (StreamWriter file = File.CreateText(@"Jsonfile.txt")) { JsonSerializer serializer1 = new JsonSerializer(); //serialize object directly into file stream serializer1.Serialize(file, Patient_name); } } public static void saveasxml(List<patientAppointment> Patient_name) { XmlSerializer xs1 = new XmlSerializer(typeof(List<patientAppointment>)); TextWriter txtWriter = new StreamWriter(@"Xmlfile.xml"); xs1.Serialize(txtWriter, Patient_name); txtWriter.Close(); } } }<file_sep>var vehicle = [ { product: 'Car', name: 'Innova' }, { product: 'Bike', name: 'Yamaha' } ]; //using call for (var i = 0; i < vehicle.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.product + ': ' + this.name); } this.print(); }).call(vehicle[i], i); } //using apply for (var i = 0; i < vehicle.length; i++) { (function(i) { this.print = function() { console.log('#' + i + ' ' + this.product + ': ' + this.name); } this.print(); }).apply(vehicle[i], [i]); } <file_sep> using System; using System.Collections.Generic; using System.IO; namespace Hospital_management { class previousAppointment { public static void AddAppoint(List<patientAppointment> Patient_name) { var SNo = 1; DateTime now = DateTime.Now; StreamWriter sw1 = File.AppendText(@"Appointments.txt"); sw1.WriteLine("-----------------------FrontLine Hospital appointment ------------------------"); sw1.WriteLine("------------------------------------------------------------------------------");//Displaying the order sw1.WriteLine($"{"SNo",13}" + "\t" + $"{"Checkup_Name",13}" + " " + " " + " " + " " + " " + $"{"Appointment Date",13}"); sw1.WriteLine("------------------------------------------------------------------------------"); sw1.WriteLine(); SNo = 1; foreach (patientAppointment i in Patient_name) { i.SNo = SNo; sw1.WriteLine($"{i.SNo,10} \t {i.Checkup_Name,10}{i.Correct_time,10}"); SNo += 1; } sw1.WriteLine("-------------------------------------------------------------------------------"); sw1.Close(); } } }<file_sep> using System; using System.Collections.Generic; namespace Hospital_management { class Checkup { public void Cardiology_list(List<patientAppointment> Patient_name) { int userOption; string whileOption; patientAppointment patientdetails = new patientAppointment(); var Cardiology = new List<Tuple<int, string>>() { new Tuple<int,string>(1,"Appointment with Dr.Rajesh "), new Tuple<int,string>(2,"Appointment with Dr.Mugil "), new Tuple<int,string>(3,"Appointment with Dr.Kadhir "), new Tuple<int,string>(4,"Appointment with Dr.Karthik "), new Tuple<int,string>(5,"Blood Test Check "), new Tuple<int,string>(6,"Chest X-Ray "), new Tuple<int,string>(7,"MRI scanning "), }; do { Console.WriteLine("\t\t Cardiology check:"); Console.WriteLine(); Console.WriteLine($"{"SNo.",10}\t{"Check Ups",10}"); foreach (Tuple<int, string> department in Cardiology) { Console.WriteLine($"{department.Item1,10}\t{department.Item2,10}"); } Console.WriteLine(); Console.WriteLine("Enter your option"); var choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } while ((userOption > 7) || (userOption <= 0)) { Console.WriteLine("Enter a number less than 7 and greater than 0!"); choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } } patientdetails.GetOrder(Cardiology, userOption, Patient_name); patientdetails.Display(Patient_name); whileOption = "y"; } while (whileOption == "Y" || whileOption == "y"); } public void Neurology_list(List<patientAppointment> Patient_name) { int userOption; string whileOption; patientAppointment patientdetails = new patientAppointment(); var Neurology= new List<Tuple<int, string>>() { new Tuple<int,string>(1,"Appointment with Dr.Kalyani "), new Tuple<int,string>(2,"Appointmnet with Dr.Fathima "), new Tuple<int,string>(3,"Appointment with Dr.Prem "), new Tuple<int,string>(4,"MRI scanning "), new Tuple<int,string>(5,"CT Scan "), new Tuple<int,string>(6,"Xray for Brain "), new Tuple<int,string>(7,"Angiography "), }; do { Console.WriteLine("\t\t Neurology Check:"); Console.WriteLine(); Console.WriteLine($"{"SNo.",10}\t{"Check ups:",10}"); foreach (Tuple<int, string> department in Neurology) { Console.WriteLine($"{department.Item1,10}\t{department.Item2,10}"); } Console.WriteLine(); Console.WriteLine("Enter your option"); var choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } while ((userOption > 7) || (userOption <= 0)) { Console.WriteLine("Enter a number less than 7 and greater than 0!"); choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } } patientdetails.GetOrder(Neurology, userOption, Patient_name); patientdetails.Display(Patient_name); whileOption = "y"; } while (whileOption == "Y" || whileOption == "y"); } public void Dermatology_list(List<patientAppointment> Patient_name) { int userOption = 0; string whileOption; patientAppointment patientdetails = new patientAppointment(); var Dermatology = new List<Tuple<int, string>>() { new Tuple<int,string>(1,"Appointment with Dr.Kalyani "), new Tuple<int,string>(2,"Appointmnet with Dr.Fathima "), new Tuple<int,string>(3,"Appointment with Dr.Prem "), new Tuple<int,string>(4,"MRI scanning "), new Tuple<int,string>(5,"CT Scan "), new Tuple<int,string>(6,"Xray for Brain "), new Tuple<int,string>(7,"Angiography "), }; do { Console.WriteLine("\t\t Deramtology Check:"); Console.WriteLine(); Console.WriteLine($"{"SNo.",10}\t{"Check ups:",10}"); foreach (Tuple<int, string> department in Dermatology) { Console.WriteLine($"{department.Item1,10}\t{department.Item2,10}"); } Console.WriteLine(); Console.WriteLine("Enter your option"); var choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } while ((userOption > 7) || (userOption <= 0)) { Console.WriteLine("Enter a number less than 7 and greater than 0!"); choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } } patientdetails.GetOrder(Dermatology, userOption, Patient_name); patientdetails.Display(Patient_name); whileOption = "y"; } while (whileOption == "Y" || whileOption == "y"); } public void Generalcheckup_list(List<patientAppointment> Patient_name) { int userOption; string whileOption; patientAppointment patientdetails = new patientAppointment(); var Generalcheckup = new List<Tuple<int, string>>() { new Tuple<int,string>(1,"Check up with Dr.Sheela "), new Tuple<int,string>(2,"Check up with Dr.Priya "), new Tuple<int,string>(3,"Blood Test "), new Tuple<int,string>(4,"Eye Check up "), new Tuple<int,string>(5,"Tooth check up "), new Tuple<int,string>(6,"Master check up "), new Tuple<int,string>(7,"CHeck up with Dr.Akil "), }; do { Console.WriteLine("\t\t General check up:"); Console.WriteLine(); Console.WriteLine($"{"SNo.",10}\t{"Check Ups",10}"); foreach (Tuple<int, string> department in Generalcheckup) { Console.WriteLine($"{department.Item1,10}\t{department.Item2,10}"); } Console.WriteLine(); Console.WriteLine("Enter your option"); var choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } while ((userOption > 7) || (userOption <= 0)) { Console.WriteLine("Enter a number less than 7 and greater than 0!"); choiceasString = Console.ReadLine(); while (!int.TryParse(choiceasString, out userOption)) { Console.WriteLine("This is not a number!"); choiceasString = Console.ReadLine(); } } patientdetails.GetOrder(Generalcheckup, userOption, Patient_name); patientdetails.Display(Patient_name); whileOption = "y"; } while (whileOption == "Y" || whileOption == "y"); } } } <file_sep>function validation(mail) { const regex=new RegExp(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/); if(regex.test(mail)) { console.log(mail); console.log("Valid email address"); } else{ console.log(mail); console.log("Invalid email address"); } } function phone_valid(phone_number) { const regex1=new RegExp(/^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/) if(regex1.test(phone_number)) { console.log(phone_number); console.log("Valid phone number"); } else{ console.log(phone_number); console.log("Invalid phone number"); } } validation("<EMAIL>"); validation("<EMAIL>jh"); phone_valid("032-243-8991"); phone_valid("04442-243-8991"); <file_sep> -- tables -- Table: Attendance CREATE TABLE Attendance ( AttendanceID int NOT NULL, LectureID int NOT NULL, RollNo int NOT NULL, CONSTRAINT Attendance_pk PRIMARY KEY (AttendanceID) ); -- Table: Classroom CREATE TABLE Classroom ( ClassID int NOT NULL, Capacity int NOT NULL, CONSTRAINT Classroom_pk PRIMARY KEY (ClassID) ); -- Table: Courses CREATE TABLE Courses ( CourseID int NOT NULL, CourseName nvarchar(max) NOT NULL, CONSTRAINT Courses_pk PRIMARY KEY (CourseID) ); -- Table: Department CREATE TABLE Department ( DeptName nvarchar(max) NOT NULL, DeptID int NOT NULL, CONSTRAINT Department_pk PRIMARY KEY (DeptID) ); -- Table: DepartmentCourses CREATE TABLE DepartmentCourses ( DeptCoursesID int NOT NULL, DeptID int NOT NULL, CourseID int NOT NULL, CONSTRAINT DepartmentCourses_pk PRIMARY KEY (DeptCoursesID) ); -- Table: Faculty CREATE TABLE Faculty ( FacultyID int NOT NULL, Facultyname int NOT NULL, BirthDate date NOT NULL, Salary nvarchar(max) NOT NULL, Contact nvarchar(max) NOT NULL, Email nvarchar(max) NOT NULL, Address nvarchar(max) NOT NULL, Gender nvarchar(max) NOT NULL, CONSTRAINT Faculty_pk PRIMARY KEY (FacultyID) ); -- Table: FacultyCourses CREATE TABLE FacultyCourses ( DeptFacultyID int NOT NULL, FacultyID int NOT NULL, DeptCoursesID int NOT NULL, CONSTRAINT FacultyCourses_pk PRIMARY KEY (DeptFacultyID) ); -- Table: Lecture CREATE TABLE Lecture ( LectureID int NOT NULL, Start_time time NOT NULL, End_time int NOT NULL, ClassID int NOT NULL, Date date NOT NULL, DeptFacultyID int NOT NULL, Day nvarchar(max) NOT NULL, CONSTRAINT Lecture_pk PRIMARY KEY (LectureID) ); -- Table: Student CREATE TABLE Student ( RollNo int NOT NULL, Name nvarchar(max) NOT NULL, BirthDate date NOT NULL, Address nvarchar(max) NOT NULL, Contact nvarchar(max) NOT NULL, Gender nvarchar(max) NOT NULL, Email nvarchar(max) NOT NULL, Year int NOT NULL, DeptID int NOT NULL, CONSTRAINT Student_pk PRIMARY KEY (RollNo) ); -- foreign keys -- Reference: Attendance_Lecture (table: Attendance) ALTER TABLE Attendance ADD CONSTRAINT Attendance_Lecture FOREIGN KEY (LectureID) REFERENCES Lecture (LectureID); -- Reference: Attendance_Student (table: Attendance) ALTER TABLE Attendance ADD CONSTRAINT Attendance_Student FOREIGN KEY (RollNo) REFERENCES Student (RollNo); -- Reference: DepartmentCourses_Courses (table: DepartmentCourses) ALTER TABLE DepartmentCourses ADD CONSTRAINT DepartmentCourses_Courses FOREIGN KEY (CourseID) REFERENCES Courses (CourseID); -- Reference: DepartmentCourses_Department (table: DepartmentCourses) ALTER TABLE DepartmentCourses ADD CONSTRAINT DepartmentCourses_Department FOREIGN KEY (DeptID) REFERENCES Department (DeptID); -- Reference: DepartmentFaculty_Faculty (table: FacultyCourses) ALTER TABLE FacultyCourses ADD CONSTRAINT DepartmentFaculty_Faculty FOREIGN KEY (FacultyID) REFERENCES Faculty (FacultyID); -- Reference: FacultyCourses_DepartmentCourses (table: FacultyCourses) ALTER TABLE FacultyCourses ADD CONSTRAINT FacultyCourses_DepartmentCourses FOREIGN KEY (DeptCoursesID) REFERENCES DepartmentCourses (DeptCoursesID); -- Reference: Lecture_Classroom (table: Lecture) ALTER TABLE Lecture ADD CONSTRAINT Lecture_Classroom FOREIGN KEY (ClassID) REFERENCES Classroom (ClassID); -- Reference: Lecture_FacultyCourses (table: Lecture) ALTER TABLE Lecture ADD CONSTRAINT Lecture_FacultyCourses FOREIGN KEY (DeptFacultyID) REFERENCES FacultyCourses (DeptFacultyID); -- Reference: Student_Department (table: Student) ALTER TABLE Student ADD CONSTRAINT Student_Department FOREIGN KEY (DeptID) REFERENCES Department (DeptID); -- End of file. <file_sep>using System; using System.Collections.Generic; using System.Globalization; namespace Hospital_management { public class patientAppointment { public int SNo = 1; public string Checkup_Name; public string Date_Timing; public string Correct_time; //public object Patient_name { get; private set; } static bool DateCheck(string stringdate) { // Define the acceptable date formats and check if entered date is valid string[] formats = { "d/MM/yyyy", "dd/MM/yyyy", "d/M/yyyy" }; string bdate = stringdate; DateTime parsedDate; try { //Conversion from string to Date time bool isValidFormat = DateTime.TryParseExact(stringdate, formats, new CultureInfo("ta-IN"), DateTimeStyles.None, out parsedDate); if (isValidFormat) { // If date is valid, check whether the given year is more than the year Today if (parsedDate<DateTime.Now) { Console.WriteLine("Appointment date must be appropriate"); return false; } else { //end do while Loop return true; } } else { //if not a valid date, give an error Console.WriteLine("Wrong Date format"); return false; } } catch (FormatException) { //Catch format exception errors on date return false; } } static int CalculateAge(string dateOfbirth) { DateTime birthDay = DateTime.Parse(dateOfbirth); int years = DateTime.Now.Year-birthDay.Year; return years; } static int Calculatemonth(string dateOfbirth) { DateTime birthDay = DateTime.Parse(dateOfbirth); int month = DateTime.Now.Month-birthDay.Month; return month; } static double Calculatedate(string dateOfbirth) { DateTime birthDay = DateTime.Parse(dateOfbirth); double date = (DateTime.Now.Date-birthDay.Date).TotalDays; return date; } public void GetOrder(List<Tuple<int, string>> department, int userOption, List<patientAppointment> Patient_name) { patientAppointment patientdetails = new patientAppointment(); foreach (Tuple<int, string> tuple in department) //loop inside the Tuple { if (tuple.Item1 == userOption) { patientdetails.Checkup_Name = tuple.Item2; // order.Price = tuple.Item3; } } Console.WriteLine("Enter the date of appointment:"); do { //Prompt and obtain user input //get Date of Birth Console.Write("Date of Appointment: (dd/mm/yyyy): "); patientdetails.Date_Timing = Console.ReadLine(); //validate date input if empty and if satisfies formatting conditions if (!string.IsNullOrEmpty (patientdetails.Date_Timing) && DateCheck( patientdetails.Date_Timing )) { //end loop break; } //Ask the user to repeatedly enter the value until a valid value has been entered } while (true); patientdetails.Correct_time = patientdetails.Date_Timing; Patient_name.Add(patientdetails); } public void Display(List<patientAppointment> Patient_name) { //long TotalCost = 0; int Option = 0; string Getoption; bool Confirmresult = true; Console.Clear(); Console.WriteLine("-----------------------FrontLine Hospital appointment -----------------------"); Console.WriteLine("------------------------------------------------------------------------------");//Displaying the order Console.WriteLine($"{"SNo",13}" + "\t" + $"{"Checkup_Name",13}" + "\t" +"\t"+$"{"Appointment Date",13}"); Console.WriteLine("------------------------------------------------------------------------------"); Console.WriteLine(); SNo = 1; foreach (patientAppointment i in Patient_name) { i.SNo = SNo; Console.WriteLine($"{i.SNo,10} \t {i.Checkup_Name,10}{i.Correct_time,10}"); SNo += 1; } Console.WriteLine("------------------------------------------------------------------------------"); Console.WriteLine("Which Operation you want to perform "); Console.WriteLine("1. Confirm"); Console.WriteLine("2. Update"); Console.WriteLine("3. Delete"); Console.WriteLine("4. Continue!"); Console.WriteLine("Enter your Option"); do { Getoption = Console.ReadLine(); while (!int.TryParse(Getoption, out Option)) { Console.WriteLine("This is not a number!"); Getoption = Console.ReadLine(); } if ((Option != 1) && (Option != 2) && (Option != 3) && (Option != 4)) { Console.WriteLine("Enter PROPER operation"); Confirmresult = true; } else Confirmresult = false; } while (Confirmresult == true); switch (Option) //Switch case for chosing what to do { case 1: Appointment.Confirm(Patient_name); break; case 2: Appointment.Update(Patient_name); break; case 3: Appointment.Delete(Patient_name); break; } } internal static void RemoveAll(Func<object, bool> p) { throw new NotImplementedException(); } } }<file_sep> var totalpass; var totalfail; var count1 = 0, count2 = 0, count3 = 0; var totalstudents; var totalpasspercent; var pass = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]; var fail = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]; var sum = new Array(); var average = new Array(); var m1 = new Array(); var m2 = new Array(); var m3 = new Array(); var m4 = new Array(); var N = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]; var Grades = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]; var Sections = new Array(); var passpercent = ["0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"]; var x = 0; function myFunction() { x = document.getElementById("grades").value; document.getElementById("data2").value = x; y = document.getElementById("sections").value; document.getElementById("data3").value = y; } function readmarks() { Grades[x] = document.getElementById("grades").value; Sections[x] = document.getElementById("sections").value; m1[x] = parseInt(document.getElementById('mark1').value, 10); m2[x] = parseInt(document.getElementById('mark2').value, 10); m3[x] = parseInt(document.getElementById('mark3').value, 10); m4[x] = parseInt(document.getElementById('mark4').value, 10); validateForm(); //alert("submitted"); x++; } function validateForm() { var x = document.myForm.mark1.value; var y = document.myForm.mark2.value; var z = document.myForm.mark3.value; var u = document.myForm.mark4.value; if (x == "" || y == "" || z == "" || u == "") { alert("Please enter all the fields") } else if (x < 1 || x > 100) { alert("Enter valid mark for english"); return false; } else if (y < 1 || y > 100) { alert("Enter valid mark for maths"); return false; } else if (z < 1 || z > 100) { alert("Enter valid mark for science"); return false; } else if (u < 1 || u > 100) { alert("Enter valid mark for social"); return false; } else { alert("Details submitted successfully"); averagecalc(); return true; } } function averagecalc() { sum[x] = m1[x] + m2[x] + m3[x] + m4[x]; document.getElementById("mark5").value = sum[x]; average[x] = sum[x] / 4; document.getElementById("mark6").value = average[x]; if (average[x] >= 60) { pass[Grades[x]]++; N[Grades[x]]++; count1++; count3++; } else { fail[Grades[x]]++; N[Grades[x]]++; count2++; count3++; } //cleartext(); passpercent[Grades[x]] = ((pass[Grades[x]] / N[Grades[x]]) * 100).toFixed(2); totalpass = count1; totalfail = count2; totalstudents = count3; totalpasspercent = ((count1 / count3) * 100).toFixed(2); } function display_array() { var myTable = "<h1>Final Results</h1>"; myTable += "<table border='5'><tr><td style='width: 100px; color: red;'>Grades</td>"; myTable += "<td style='width: 100px; color: red; text-align: right;'>No of students</td>"; myTable += "<td style='width: 100px; color: red; text-align: right;'>Pass</td>"; myTable += "<td style='width: 100px; color: red; text-align: right;'>Fail</td>"; myTable += "<td style='width: 100px; color: red; text-align: right;'>Average</td></tr>"; for (var i = 1; i <= 12; i++) { myTable += "<tr><td style='width: 100px;'>Grade" + i + "</td>"; myTable += "<td style='width: 100px; text-align: right;'>" + N[i] + "</td>"; myTable += "<td style='width: 100px; text-align: right;'>" + pass[i] + "</td>"; myTable += "<td style='width: 100px; text-align: right;'>" + fail[i] + "</td>"; myTable += "<td style='width: 100px; text-align: right;'>" + passpercent[i] + "</td></tr>"; } myTable += "</table>"; myTable += "<h3>Total passed students:" + count1 + "</h3>"; myTable += "<h3>Total failed students:" + count2 + "</h3>"; myTable += "<h3>Total students are:" + count3 + "</h3>"; if(count3==0) { totalpasspercent=0; myTable += "<h3>Total Pass percentage:" + totalpasspercent + "</h3>"; } else{ myTable += "<h3>Total Pass percentage:" + totalpasspercent + "</h3>"; } document.getElementById("Result").innerHTML = myTable; } function cleartext() { document.getElementById('data1').value = " "; document.getElementById('mark1').value = " "; document.getElementById('mark2').value = " "; document.getElementById('mark3').value = " "; document.getElementById('mark4').value = " "; document.getElementById('mark5').value = " "; document.getElementById('mark6').value = " "; }
6f1bd6702c32e6c36a7ceafd308b0bb2c629592a
[ "JavaScript", "SQL", "C#" ]
27
JavaScript
Aparna-Psiog/IMPACT_ASSIGNMENT
5fd4b9d6618f133bf5e9add4f6044d535f8db6ad
d09fcf9f9d07586c59a561a3eca97570d04e5b35
refs/heads/master
<file_sep>package com.works.foodtownproject; import java.sql.PreparedStatement; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import util.DB; @Controller public class ExitController { @RequestMapping(value = "/exit", method = RequestMethod.GET) public String exit(HttpServletResponse request) { DB db = new DB(); IncludeController.page = "/exit"; Cookie cookie = new Cookie("user_remember", ""); cookie.setMaxAge(0); request.addCookie(cookie); try { String query = "TRUNCATE cart"; PreparedStatement pre = db.connect(query); pre.executeUpdate(); System.out.println("Deletion Successful"); } catch (Exception e) { System.err.println("Deletion Error : " + e); } return "redirect:/"; } } <file_sep>package model; // Generated 05.Eki.2019 21:16:32 by Hibernate Tools 5.2.12.Final import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * Admin generated by hbm2java */ @Entity @Table(name="admin") public class Admin implements java.io.Serializable { private Integer adminid; private String adminname; private String adminmail; private String adminpassword; private String adminpasscode; public Admin() { } public Admin(String adminname, String adminmail, String adminpassword, String adminpasscode) { this.adminname = adminname; this.adminmail = adminmail; this.adminpassword = <PASSWORD>; this.adminpasscode = <PASSWORD>; } @Id @GeneratedValue(strategy=IDENTITY) @Column(name="adminid", unique=true, nullable=false) public Integer getAdminid() { return this.adminid; } public void setAdminid(Integer adminid) { this.adminid = adminid; } @Column(name="adminname", nullable=false) public String getAdminname() { return this.adminname; } public void setAdminname(String adminname) { this.adminname = adminname; } @Column(name="adminmail", nullable=false) public String getAdminmail() { return this.adminmail; } public void setAdminmail(String adminmail) { this.adminmail = adminmail; } @Column(name="adminpassword", nullable=false) public String getAdminpassword() { return this.adminpassword; } public void setAdminpassword(String adminpassword) { this.adminpassword = <PASSWORD>; } @Column(name="adminpasscode", nullable=false) public String getAdminpasscode() { return this.adminpasscode; } public void setAdminpasscode(String adminpasscode) { this.adminpasscode = <PASSWORD>code; } } <file_sep>package com.works.admin; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import model.Admin; import util.DB; import util.Password; @Controller @RequestMapping("/admin") public class LoginadminController { DB db = new DB(); @RequestMapping(value = "/", method = RequestMethod.GET) public String loginadmin(HttpServletRequest req) { if (req.getCookies() != null) { Cookie[] cookies = req.getCookies(); for (Cookie item : cookies) { if (item.getName().equals("admin_cookie")) { String usid = Password.decrypt(item.getValue(), 4); System.out.println("Cookie Uid : " + usid); return "redirect:/admin/dashboard"; } } } return "admin/login"; } @RequestMapping(value = "/login", method = RequestMethod.POST) public String loginadminPost(Admin adm, Model model, HttpServletRequest req, @RequestParam(defaultValue = "off") String remember, HttpServletResponse res) { try { String query = "select * from admin where adminmail = ? and adminpassword = ? "; PreparedStatement pre = db.connect(query); pre.setString(1, adm.getAdminmail()); pre.setString(2, adm.getAdminpassword()); ResultSet rs = pre.executeQuery(); if (rs.next()) { adm.setAdminid(rs.getInt("adminid")); adm.setAdminname(rs.getString("adminname")); req.getSession().setAttribute("adminid", adm); if (remember.equals("on")) { Cookie cookie = new Cookie("admin_cookie", Password.encryption("" + adm.getAdminid(), 4)); cookie.setMaxAge(60 * 60 * 24); res.addCookie(cookie); } return "redirect:/admin/dashboard"; } else { model.addAttribute("error", "Wrong Username or Password"); } } catch (Exception e) { System.err.println("login error : " + e); model.addAttribute("error", "Connection Error"); } return "admin/login"; } @RequestMapping(value = "/exit", method = RequestMethod.GET) public String exit(HttpServletRequest req, HttpServletResponse res) { Cookie cookie = new Cookie("admin_cookie", ""); cookie.setMaxAge(0); res.addCookie(cookie); req.getSession().invalidate(); return "redirect:/admin/"; } } <file_sep>package model; // Generated 05.Eki.2019 21:16:32 by Hibernate Tools 5.2.12.Final import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * Blog generated by hbm2java */ @Entity @Table(name = "blog") public class Blog implements java.io.Serializable { private Integer blogid; private String blogtitle; private String blogtext; private String blogimage; private String blogauthorimage; private String blogauthor; private String blogtextparagraph; public Blog() { } public Blog(String blogtitle, String blogtext, String blogimage, String blogauthorimage, String blogauthor) { this.blogtitle = blogtitle; this.blogtext = blogtext; this.blogimage = blogimage; this.blogauthorimage = blogauthorimage; this.blogauthor = blogauthor; } public Blog(String blogtitle, String blogtext, String blogimage, String blogauthorimage, String blogauthor, String blogtextparagraph) { this.blogtitle = blogtitle; this.blogtext = blogtext; this.blogimage = blogimage; this.blogauthorimage = blogauthorimage; this.blogauthor = blogauthor; this.blogtextparagraph = blogtextparagraph; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "blogid", unique = true, nullable = false) public Integer getBlogid() { return this.blogid; } public void setBlogid(Integer blogid) { this.blogid = blogid; } @Column(name = "blogtitle", nullable = false) public String getBlogtitle() { return this.blogtitle; } public void setBlogtitle(String blogtitle) { this.blogtitle = blogtitle; } @Column(name = "blogtext", nullable = false) public String getBlogtext() { return this.blogtext; } public void setBlogtext(String blogtext) { this.blogtext = blogtext; } @Column(name = "blogimage", nullable = false) public String getBlogimage() { return this.blogimage; } public void setBlogimage(String blogimage) { this.blogimage = blogimage; } @Column(name = "blogauthorimage", nullable = false) public String getBlogauthorimage() { return this.blogauthorimage; } public void setBlogauthorimage(String blogauthorimage) { this.blogauthorimage = blogauthorimage; } @Column(name = "blogauthor", nullable = false) public String getBlogauthor() { return this.blogauthor; } public void setBlogauthor(String blogauthor) { this.blogauthor = blogauthor; } @Column(name = "blogtextparagraph") public String getBlogtextparagraph() { return this.blogtextparagraph; } public void setBlogtextparagraph(String blogtextparagraph) { this.blogtextparagraph = blogtextparagraph; } } <file_sep>package com.works.admin; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.Contact; import model.Neworder; import model.Product; import model.User; import util.HibernateUtil; import util.Util; @Controller @RequestMapping("/admin") public class OrderListController { SessionFactory sf = HibernateUtil.getSessionFactory(); @RequestMapping(value = "/orderlist", method = RequestMethod.GET) public String orderlist(HttpServletRequest req, Model model) { Session sesi = sf.openSession(); List<Product> productcount = sesi.createQuery("from Product").list(); List<User> usercount = sesi.createQuery("from User").list(); List<Neworder> ordercount = sesi.createQuery("from Neworder").list(); List<Contact> contactcount = sesi.createQuery("from Contact").list(); model.addAttribute("productcount", productcount.size()); model.addAttribute("usercount", usercount.size()); model.addAttribute("ordercount", ordercount.size()); model.addAttribute("contactcount", contactcount.size()); List<Neworder> orderlist = sesi.createQuery("from Neworder").list(); model.addAttribute("orderlist", orderlist); return Util.control(req, "orderlist"); } @RequestMapping(value = "/orderdelivered/{orderid}") public String orderDelivered(@PathVariable int orderid, HttpServletRequest req) { Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); Neworder ord = sesi.load(Neworder.class, orderid); ord.setOrderstatus("Delivered"); sesi.update(ord); tr.commit(); return Util.control(req, "redirect:/admin/orderlist"); } @RequestMapping(value = "/orderready/{orderid}") public String orderReady(@PathVariable int orderid, HttpServletRequest req) { Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); Neworder ord = sesi.load(Neworder.class, orderid); ord.setOrderstatus("Ready to Deliver"); sesi.update(ord); tr.commit(); return Util.control(req, "redirect:/admin/orderlist"); } } <file_sep># SpringOrderProject This project containes Spring MVC, JDBC and Hibernate. In the admin panel, customers, products, blogs can be added and deleted. Can read messages from contact us. New admin can add and edit. Foodtown can review the menu and products, and if ordered, can order. Also can send a message to the admins. ## Admin Panel ![admin](https://user-images.githubusercontent.com/45119193/66271105-f23c7c00-e862-11e9-8005-751bba4a7b67.png) ## FoodTown HomePage ![home](https://user-images.githubusercontent.com/45119193/66271114-1435fe80-e863-11e9-9e9e-c53b5f7ac75f.png) ## FoodTown LoginPage ![login](https://user-images.githubusercontent.com/45119193/66271125-27e16500-e863-11e9-810c-96007d4a9ff2.png) ## FoodTown Cart ![cart](https://user-images.githubusercontent.com/45119193/66271132-3039a000-e863-11e9-91cb-5f95242ca43b.png) ## FoodTown Contact Us ![contact](https://user-images.githubusercontent.com/45119193/66271136-3891db00-e863-11e9-860b-105b3d925e83.png) <file_sep>package com.works.foodtownproject; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.Contact; import util.HibernateUtil; @Controller public class ContactusController { SessionFactory sf = HibernateUtil.getSessionFactory(); @RequestMapping(value = "/contactus", method = RequestMethod.GET) public String contactus() { IncludeController.page = "/"; return "site/contactus"; } @RequestMapping(value = "/contactusInsert", method = RequestMethod.POST) public String contactusInsert(Contact us) { IncludeController.page = "/"; Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); int id = (Integer) sesi.save(us); if (id > 0) { System.out.println("contactusInsert successful"); } tr.commit(); return "redirect:/"; } } <file_sep>-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Anamakine: 127.0.0.1 -- Üretim Zamanı: 06 Eki 2019, 16:10:22 -- Sunucu sürümü: 10.4.6-MariaDB -- PHP Sürümü: 7.3.8 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Veritabanı: `foodtownproject` -- -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `admin` -- CREATE TABLE `admin` ( `adminid` int(11) NOT NULL, `adminname` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `adminmail` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `adminpassword` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `adminpasscode` varchar(255) COLLATE utf8_turkish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; -- -- Tablo döküm verisi `admin` -- INSERT INTO `admin` (`adminid`, `adminname`, `adminmail`, `adminpassword`, `adminpasscode`) VALUES (1, 'Admin', '<EMAIL>', '<PASSWORD>', ''), (15, 'Admin-2', '<EMAIL>', '<PASSWORD>', ''); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `blog` -- CREATE TABLE `blog` ( `blogid` int(11) NOT NULL, `blogtitle` varchar(255) CHARACTER SET utf8 COLLATE utf8_turkish_ci NOT NULL, `blogtext` varchar(255) CHARACTER SET utf8 COLLATE utf8_turkish_ci NOT NULL, `blogimage` varchar(255) CHARACTER SET utf8 COLLATE utf8_turkish_ci NOT NULL, `blogauthorimage` varchar(255) CHARACTER SET utf8 COLLATE utf8_turkish_ci NOT NULL, `blogauthor` varchar(255) CHARACTER SET utf8 COLLATE utf8_turkish_ci NOT NULL, `blogtextparagraph` varchar(255) CHARACTER SET utf8 COLLATE utf8_turkish_ci DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Tablo döküm verisi `blog` -- INSERT INTO `blog` (`blogid`, `blogtitle`, `blogtext`, `blogimage`, `blogauthorimage`, `blogauthor`, `blogtextparagraph`) VALUES (1, 'Simple Macaroni and Cheese', '\"A very quick and easy fix to a tasty side-dish. Fancy, designer mac and cheese often costs forty or fifty dollars to prepare when you have so many exotic and expensive cheeses, but they aren\'t always the best tasting. This recipe is cheap and tasty.\"\r\n\r\n', 'https://images.media-allrecipes.com/userphotos/720x405/5445825.jpg', 'https://pbs.twimg.com/profile_images/378800000536961438/56b3a93250f5fd475f1c7eee27a9f389_400x400.jpeg', '<NAME>', 'Bring a large pot of lightly salted water to a boil. Cook elbow macaroni in the boiling water, stirring occasionally until cooked through but firm to the bite, 8 minutes. Drain.\r\n\r\n\r\nMelt butter in a saucepan over medium heat; stir in flour, salt, and pep'), (2, 'Slow Cooker Salisbury Steak', '\"This recipe goes together quickly and does not need a lot of time in the slow cooker. It\'s a delicious way to add flavor to ground beef and the children love it! The gravy is delightful served over mashed potatoes.\"', 'https://i.imgyukle.com/2019/09/23/oe3kBc.jpg', 'https://pbs.twimg.com/profile_images/378800000536961438/56b3a93250f5fd475f1c7eee27a9f389_400x400.jpeg', '<NAME>', 'In a large bowl, mix together the ground beef, onion soup mix, bread crumbs, and milk using your hands. Shape into 8 patties.\r\nHeat the oil in a large skillet over medium-high heat. Dredge the patties in flour just to coat, and quickly brown on both sides'), (3, 'Mushroom Slow Cooker Roast Beef', '\"This is tender, fall-off-the-bone roast beef with mushrooms. It\'s perfect as-is. Shred the leftovers for cheese steak sandwiches.\"', 'https://i.imgyukle.com/2019/09/23/oeW470.jpg', 'https://pbs.twimg.com/profile_images/378800000536961438/56b3a93250f5fd475f1c7eee27a9f389_400x400.jpeg', '<NAME>', 'Place the mushrooms in the bottom of a slow cooker; set the roast atop the mushrooms; sprinkle the onion soup mix over the beef and pour the beer over everything; season with black pepper. Set slow cooker to LOW; cook 9 to 10 hours until the meat is easil'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `cart` -- CREATE TABLE `cart` ( `cartid` int(11) NOT NULL, `productname` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `productprice` double NOT NULL, `orderstatus` varchar(255) COLLATE utf8_turkish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `category` -- CREATE TABLE `category` ( `categoryid` int(11) NOT NULL, `categoryname` varchar(255) COLLATE utf8_turkish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; -- -- Tablo döküm verisi `category` -- INSERT INTO `category` (`categoryid`, `categoryname`) VALUES (1, 'Burger'), (2, 'Pizza'), (3, 'Vegetarian'), (4, 'Drink'), (5, 'Dessert'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `contact` -- CREATE TABLE `contact` ( `contactid` int(11) NOT NULL, `contactname` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `contactmail` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `contacttext` varchar(255) COLLATE utf8_turkish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; -- -- Tablo döküm verisi `contact` -- INSERT INTO `contact` (`contactid`, `contactname`, `contactmail`, `contacttext`) VALUES (7, 'User', '<EMAIL>', 'New Contact'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `neworder` -- CREATE TABLE `neworder` ( `orderid` int(11) NOT NULL, `ordername` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `productname` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `orderstatus` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `orderprice` double NOT NULL, `ordernote` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `orderphone` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `orderaddress` varchar(255) COLLATE utf8_turkish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; -- -- Tablo döküm verisi `neworder` -- INSERT INTO `neworder` (`orderid`, `ordername`, `productname`, `orderstatus`, `orderprice`, `ordernote`, `orderphone`, `orderaddress`) VALUES (21, 'User', 'Strawberry Cake', 'Ready to Deliver', 15, 'New Order\r\n', '05554443322', 'Ankara'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `product` -- CREATE TABLE `product` ( `productid` int(11) NOT NULL, `categoryid` int(11) NOT NULL, `productname` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `productprice` double NOT NULL, `producttext` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `productimage` varchar(255) COLLATE utf8_turkish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; -- -- Tablo döküm verisi `product` -- INSERT INTO `product` (`productid`, `categoryid`, `productname`, `productprice`, `producttext`, `productimage`) VALUES (1, 1, 'Double Animal Style', 13, 'Double Animal Style Burger with 260gr beef and cheddar. Serves with french fries.', 'https://i.imgyukle.com/2019/09/23/oetPuo.jpg'), (2, 1, 'Le Pigeon Burger', 13, 'Le Pigeon Burger with lettuce and chicken beef inside. Serves with french fries.', 'https://i.imgyukle.com/2019/09/23/oe9smN.jpg'), (3, 2, 'Pizza Alla Napolitana', 16, 'Pizza with red pepper, lettuce and mushroom.', 'https://i.imgyukle.com/2019/09/23/oefQ9N.jpg'), (4, 2, 'Pizza Marinara', 17, 'Pizza Marinara with red pepper, tomato and bacon.', 'https://i.imgyukle.com/2019/09/23/oef5jv.jpg'), (5, 3, 'Pilachu Fruit', 12, 'Salad with cheese, mushroom and pineapple.', 'https://i.imgyukle.com/2019/09/23/oefaYp.jpg'), (6, 3, 'Choloride', 13, 'Salad with corn, lemon and onion.', 'https://i.imgyukle.com/2019/09/23/oefL9M.jpg'), (7, 5, 'Oreo Cake', 16, 'Cake with oreo chocolate and orange.', 'https://i.imgyukle.com/2019/09/23/oefXF8.jpg'), (8, 5, 'Strawberry Cake', 15, 'Cake with cream and strawberry', 'https://i.imgyukle.com/2019/09/23/oefBPH.jpg'), (9, 4, 'Orange Juice', 7, '', 'https://i.imgyukle.com/2019/09/23/oefpYA.jpg'), (10, 4, 'Lemonade', 6, '', 'https://i.imgyukle.com/2019/09/23/oefGfI.jpg'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `user` -- CREATE TABLE `user` ( `userid` int(11) NOT NULL, `username` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `usermail` varchar(255) COLLATE utf8_turkish_ci NOT NULL, `userpassword` varchar(255) COLLATE utf8_turkish_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_turkish_ci; -- -- Tablo döküm verisi `user` -- INSERT INTO `user` (`userid`, `username`, `usermail`, `userpassword`) VALUES (7, 'User', '<EMAIL>', '<PASSWORD>'), (10, 'User-2', '<EMAIL>', '<PASSWORD>'); -- -- Dökümü yapılmış tablolar için indeksler -- -- -- Tablo için indeksler `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`adminid`); -- -- Tablo için indeksler `blog` -- ALTER TABLE `blog` ADD PRIMARY KEY (`blogid`); -- -- Tablo için indeksler `cart` -- ALTER TABLE `cart` ADD PRIMARY KEY (`cartid`); -- -- Tablo için indeksler `category` -- ALTER TABLE `category` ADD PRIMARY KEY (`categoryid`); -- -- Tablo için indeksler `contact` -- ALTER TABLE `contact` ADD PRIMARY KEY (`contactid`); -- -- Tablo için indeksler `neworder` -- ALTER TABLE `neworder` ADD PRIMARY KEY (`orderid`); -- -- Tablo için indeksler `product` -- ALTER TABLE `product` ADD PRIMARY KEY (`productid`); -- -- Tablo için indeksler `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`userid`); -- -- Dökümü yapılmış tablolar için AUTO_INCREMENT değeri -- -- -- Tablo için AUTO_INCREMENT değeri `admin` -- ALTER TABLE `admin` MODIFY `adminid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=16; -- -- Tablo için AUTO_INCREMENT değeri `blog` -- ALTER TABLE `blog` MODIFY `blogid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- Tablo için AUTO_INCREMENT değeri `cart` -- ALTER TABLE `cart` MODIFY `cartid` int(11) NOT NULL AUTO_INCREMENT; -- -- Tablo için AUTO_INCREMENT değeri `category` -- ALTER TABLE `category` MODIFY `categoryid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- Tablo için AUTO_INCREMENT değeri `contact` -- ALTER TABLE `contact` MODIFY `contactid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- Tablo için AUTO_INCREMENT değeri `neworder` -- ALTER TABLE `neworder` MODIFY `orderid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22; -- -- Tablo için AUTO_INCREMENT değeri `product` -- ALTER TABLE `product` MODIFY `productid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=17; -- -- Tablo için AUTO_INCREMENT değeri `user` -- ALTER TABLE `user` MODIFY `userid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>package com.works.foodtownproject; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.Product; import util.HibernateUtil; @Controller public class MenupizzaController { SessionFactory sf = HibernateUtil.getSessionFactory(); @RequestMapping(value = "/menupizza", method = RequestMethod.GET) public String menuPizza(Model model) { Session sesi = sf.openSession(); List<Product> productdata = sesi.createQuery("from Product").list(); model.addAttribute("productdata", productdata); return "site/menupizza"; } } <file_sep>package model; // Generated 05.Eki.2019 21:16:32 by Hibernate Tools 5.2.12.Final import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import static javax.persistence.GenerationType.IDENTITY; import javax.persistence.Id; import javax.persistence.Table; /** * Neworder generated by hbm2java */ @Entity @Table(name = "neworder") public class Neworder implements java.io.Serializable { private Integer orderid; private String ordername; private String productname; private String orderstatus; private double orderprice; private String ordernote; private String orderphone; private String orderaddress; public Neworder() { } public Neworder(String ordername, String productname, String orderstatus, double orderprice, String ordernote, String orderphone, String orderaddress) { this.ordername = ordername; this.productname = productname; this.orderstatus = orderstatus; this.orderprice = orderprice; this.ordernote = ordernote; this.orderphone = orderphone; this.orderaddress = orderaddress; } @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "orderid", unique = true, nullable = false) public Integer getOrderid() { return this.orderid; } public void setOrderid(Integer orderid) { this.orderid = orderid; } @Column(name = "ordername", nullable = false) public String getOrdername() { return this.ordername; } public void setOrdername(String ordername) { this.ordername = ordername; } @Column(name = "productname", nullable = false) public String getProductname() { return this.productname; } public void setProductname(String productname) { this.productname = productname; } @Column(name = "orderstatus", nullable = false) public String getOrderstatus() { return this.orderstatus; } public void setOrderstatus(String orderstatus) { this.orderstatus = orderstatus; } @Column(name = "orderprice", nullable = false, precision = 22, scale = 0) public double getOrderprice() { return this.orderprice; } public void setOrderprice(double orderprice) { this.orderprice = orderprice; } @Column(name = "ordernote", nullable = false) public String getOrdernote() { return this.ordernote; } public void setOrdernote(String ordernote) { this.ordernote = ordernote; } @Column(name = "orderphone", nullable = false) public String getOrderphone() { return this.orderphone; } public void setOrderphone(String orderphone) { this.orderphone = orderphone; } @Column(name = "orderaddress", nullable = false) public String getOrderaddress() { return this.orderaddress; } public void setOrderaddress(String orderaddress) { this.orderaddress = orderaddress; } } <file_sep>package com.works.foodtownproject; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.User; import util.HibernateUtil; import util.Password; @Controller public class RegisterController { SessionFactory sf = HibernateUtil.getSessionFactory(); @RequestMapping(value = "/register", method = RequestMethod.GET) public String register(HttpServletRequest req, User us) { IncludeController.page = "/register"; if (req.getCookies() != null) { Cookie[] cookies = req.getCookies(); for (Cookie item : cookies) { if (item.getName().equals("user_remember")) { String userid = Password.decrypt(item.getValue(), 4); System.out.println("Cookie userid : " + userid); req.getSession().setAttribute("user_id", userid); return "redirect:/"; } } } return "site/register"; } @RequestMapping(value = "/userInsert", method = RequestMethod.POST) public String userInsert(User us, HttpServletResponse res) { IncludeController.page = "/register"; Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); int id = (Integer) sesi.save(us); if (id > 0) { tr.commit(); Cookie cookie = new Cookie("user_remember", Password.encryption("" + us.getUserid(), 4)); cookie.setMaxAge(60 * 60 * 24); res.addCookie(cookie); return "redirect:/"; } else return "redirect:/register"; } } <file_sep>package com.works.foodtownproject; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.Blog; import model.Product; import util.HibernateUtil; @Controller public class HomeController { SessionFactory sf = HibernateUtil.getSessionFactory(); @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Model model) { IncludeController.page = "/"; Session sesi = sf.openSession(); List<Blog> blogdata = sesi.createQuery("from Blog").list(); List<Product> productdata = sesi.createQuery("from Product").list(); model.addAttribute("productdata", productdata); model.addAttribute("blogdata", blogdata); return "site/home"; } } <file_sep>package com.works.admin; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.Contact; import model.Neworder; import model.Product; import model.User; import util.HibernateUtil; import util.Util; @Controller @RequestMapping("/admin") public class AddProductController { SessionFactory sf = HibernateUtil.getSessionFactory(); @RequestMapping(value = "/addproduct", method = RequestMethod.GET) public String addproduct(HttpServletRequest req, Model model) { Session sesi = sf.openSession(); List<Product> productcount = sesi.createQuery("from Product").list(); List<User> usercount = sesi.createQuery("from User").list(); List<Neworder> ordercount = sesi.createQuery("from Neworder").list(); List<Contact> contactcount = sesi.createQuery("from Contact").list(); model.addAttribute("productcount", productcount.size()); model.addAttribute("usercount", usercount.size()); model.addAttribute("ordercount", ordercount.size()); model.addAttribute("contactcount", contactcount.size()); return Util.control(req, "addproduct"); } @RequestMapping(value = "/addproduct", method = RequestMethod.POST) public String addProduct(HttpServletRequest req, Product pr) { Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); sesi.save(pr); tr.commit(); return Util.control(req, "redirect:/admin/productlist"); } } <file_sep>package com.works.foodtownproject; import java.sql.PreparedStatement; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import model.Cart; import model.Neworder; import util.DB; import util.HibernateUtil; @Controller public class OrderController { SessionFactory sf = HibernateUtil.getSessionFactory(); DB db = new DB(); @RequestMapping(value = "/order", method = RequestMethod.GET) public String order(Model model) { IncludeController.page = "order"; Session sesi = sf.openSession(); List<Cart> carts = sesi.createQuery("from Cart").list(); model.addAttribute("cartdata", carts); double total = 0; for (Cart item : carts) { total = total + item.getProductprice(); } model.addAttribute("total", total); return "site/order"; } @RequestMapping(value = "/order", method = RequestMethod.POST) public String neworder(Neworder us) { IncludeController.page = "/order"; Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); int id = (Integer) sesi.save(us); if (id > 0) { System.out.println("neworder Success"); } tr.commit(); try { String query = "TRUNCATE cart"; PreparedStatement pre = db.connect(query); pre.executeUpdate(); System.out.println("Delete Success"); } catch (Exception e) { System.err.println("Delete Error : " + e); } return "redirect:/order"; } @RequestMapping(value = "/delete/{cartid}", method = RequestMethod.GET) public String orderDelete(@PathVariable int cartid) { Session sesi = sf.openSession(); Transaction tr = sesi.beginTransaction(); Cart cart = sesi.load(Cart.class, cartid); sesi.delete(cart); tr.commit(); return "redirect:/order"; } }
bdf31a1f4d8f6f2bd3a0e1609bf037b027996269
[ "Markdown", "Java", "SQL" ]
14
Java
serdarsanu/SpringOrderProject
5d41dab6a58364b4257c30ba63a2d7f224ce0b27
da8e15f2d7df6cbd0a1298998cfe4e4e15b7be36
refs/heads/main
<file_sep># OpenWeatherApplication ## Index * About this project * Deployed Site * Technologies Used * Deployment * Author ## About this project To get this application of the ground I employed the use of OpenWeathers API in order to retrieve current weather conditions of the locations the users insert into the search bar. Using AJAX calls and the like I parsed the information into a current weather container and a 5 day future forecast set of cards for the user to gain information from. ## Deployed Site * Site <img src="./assets/images/Capture.PNG"> * Search Function <img src="http://g.recordit.co/4bpQyUcUDp.gif" alt="Search Function Demo"> https://joeyflygare.github.io/OpenWeatherApplication/ ## Technologies Used The tech I used on this site is fairly straightforward. I used Bootstraps CSS library as well a Jquery and OpenWeathers API kit. ## Deployment To contribute to this site please pull the code form GitHub in order to clone the project to your local machine. ## Author <NAME> - Yours Truly - Always going never stopping<file_sep> var btnClick = false; $("#searchCity").on("click", function () { btnClick = true; createWeatherData(); }); $("#history").on("click", function () { btnClick = true; createWeatherData(); }); function createWeatherData() { if (localStorage.length !== 0 && !$("#location").val() && !btnClick) { var userInput = localStorage.getItem(localStorage.length - 1); } else if (event.target.matches("button") || event.target.matches("i") && btnClick) { event.preventDefault(); var userInput = $("#location").val().toLowerCase().trim(); } else if (event.target.matches("li") && btnClick) { var userInput = event.target.getAttribute("cityData").toLowerCase().trim();; } else { return; } if (userInput === "") { return; } let localStorageBool = false; if (localStorage.length === 0) { localStorage.setItem(0, userInput); createSearchHistory(); localStorageBool = true; } else { for (let i = 0; i < localStorage.length; i++) { if (localStorage.getItem(i) === userInput) { localStorageBool = true; } } } if (!localStorageBool) { localStorage.setItem(localStorage.length, userInput); createSearchHistory(); } let APIKey = "ef8d3deaadba22efae141ac1cdaa4f1c"; let queryURL = "https://api.openweathermap.org/data/2.5/weather?q=" + userInput + "&appid=" + APIKey; $.ajax({ url: queryURL, method: "GET" }).then(function (response) { let currentDateUnix = response.dt; let currentDateMilliseconds = currentDateUnix * 1000; let currentDateConverted = new Date(currentDateMilliseconds).toLocaleDateString( "en-US"); // get icon let currentWeatherIcon = response.weather[0].icon; let tempF = ((response.main.temp - 273.15) * 1.80 + 32).toFixed(1); let lat = response.coord.lat; let lon = response.coord.lon; $("#cityName").text(response.name + " (" + currentDateConverted + ")"); $("#cityName") .append($("<img>").attr({ src: "https://openweathermap.org/img/wn/" + currentWeatherIcon + "@2x.png", alt: "icon representation of weather conditions" })); $("#temp").text("Temperature: " + tempF + "\u00B0F"); $("#humid").text("Humidity: " + response.main.humidity + "%"); $("#windSpeed").text("Wind Speed: " + ((response.wind.speed) * 2.237).toFixed(1) + " MPH"); let forecastQueryURL = "https://api.openweathermap.org/data/2.5/onecall?lat=" + lat + "&lon=" + lon + "&exclude=current,minutely,hourly&appid=" + APIKey; $.ajax({ url: forecastQueryURL, method: "GET" }).then(function (responseForecast) { $(".uvIndex").text("UV Index: " + responseForecast.daily[0].uvi); createUVIndexColor(responseForecast.daily[0].uvi); $(".forecast").empty(); for (let i = 1; i < 6; i++) { $(".forecast-date-" + i).append(new Date(responseForecast.daily[i].dt * 1000) .toLocaleDateString("en-US") + "<br>"); $(".forecast-" + i).append($("<img>").attr({ src: "https://openweathermap.org/img/wn/" + responseForecast .daily[i].weather[0].icon + "@2x.png", alt: "icon representation of weather conditions" })); $(".forecast-" + i).append("<br>Temp: " + ((responseForecast.daily[i].temp .day - 273.15) * 1.80 + 32).toFixed(2) + " \u00B0F<br>"); $(".forecast-" + i).append("Humidity: " + responseForecast.daily[i] .humidity + "%<br>"); } }); console.log(response) }); $("#location").val(""); } function createUVIndexColor(x) { if (x >= 1.00 && x <= 2.99) { $("#uvBG").attr("style", "background-color:rgb(67, 185, 30);"); } else if (x >= 3.00 && x <= 5.99) { $("#uvBG").attr("style", "background-color:rgb(252, 199, 33);"); } else if (x >= 6.00 && x <= 7.99) { $("#uvBG").attr("style", "background-color:rgb(251, 116, 27);"); } else if (x >= 8.00 && x <= 10.99) { $("#uvBG").attr("style", "background-color:rgb(248, 17, 22);"); } else { $("#uvBG").attr("style", "background-color:rgb(134, 111, 255);"); } } function createSearchHistory() { $("#history").empty(); let newString = ""; for (let i = 0; i < localStorage.length; i++) { newString = capLetters(localStorage.getItem(i)); let cityLi = $("<li>"); cityLi.attr("cityData", newString); cityLi.addClass("list-group-item"); cityLi.text(newString); $("#history").append(cityLi); } } function capLetters(str) { let arrayStr = str.split(" "); let capLetter = ""; let newString = ""; for (let i = 0; i < arrayStr.length; i++) { capLetter = arrayStr[i][0].toUpperCase(); newString += capLetter + arrayStr[i].slice(1, arrayStr[i].length) + " "; } return newString.trim(); } if (localStorage.length !== 0) { createSearchHistory(); createWeatherData(); } $(document).ajaxError(function () { alert("Location not in database!"); localStorage.removeItem(localStorage.length - 1); createSearchHistory(); });
8ae61c97852a89840bdb0cadf3a4922d4864814f
[ "Markdown", "JavaScript" ]
2
Markdown
JoeyFlygare/OpenWeatherApplication
042e198d37b94d2175ffcafc08bb40503089b96b
cd36778a87315bd55616842b4f8d2c77db7507e3
refs/heads/master
<file_sep>var qs = decodeURI(window.location.search) .replace('?', '') .split('&') .map(param => param.split('=')) .reduce((values, [ key, value ]) => { values[ key ] = value return values }, {});
de1341e83a242e458ed9c2fa5eda89ca82e5208d
[ "JavaScript" ]
1
JavaScript
lightcouncil/Snippets
1d8426b4d9afe47bafcd7f29ac92e7ec90576632
43d8f329f1c24aae29ad1a31d1bed0870c4306c8
refs/heads/master
<repo_name>tiesmaster/bag_importer-for_mongo<file_sep>/xslt/import_opr.sh #!/bin/sh echo 'db.street.drop();' |mongo bag time \ for x in 9999OPR08112011-0000*xml do xsltproc import_opr.xsl $x |mongo bag done <file_sep>/README.md bag_importer-for_mongo ====================== [![Join the chat at https://gitter.im/tiesmaster/bag_importer-for_mongo](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/tiesmaster/bag_importer-for_mongo?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) BAG importer for mongodb
9bb77cfa93691c98046b9989a32fe8a2a8f8b499
[ "Markdown", "Shell" ]
2
Shell
tiesmaster/bag_importer-for_mongo
cd40419c3e99462938e90966622ec8ee3f09aa38
f1cdae3850733e0a8cb339ed7fd0d53672e0100b
refs/heads/master
<file_sep>class EntriesController < ApplicationController def index # respond_with Entry.all @entries = Entry.all render json: @entries end def show @entry = Entry.find(params[:id]) render json: @entry end def create @entry = Entry.create(entry_params) render json: @entry end def update @entry = Entry.update(params[:id], entry_params) render json: @entry end def destroy Entry.destroy(params[:id]) render json: "Entry destroyed" end private def entry_params params.require(:entry).permit! end end <file_sep># Raffler This is the code for [Railscasts #405](http://railscasts.com/episodes/405-angularjs) adjusted to work with Rails 5 (beta3) and AngularJS 1.5-ish.
07989a3bfe5ed112f0d888afc837e03e600d363c
[ "Markdown", "Ruby" ]
2
Ruby
hayesr/raffler
0ac4c40ee65d69d0d916cb6de7e4c42c438ec287
f14e0a205ffcd8823854fb67760bef03eba62333
refs/heads/main
<file_sep>import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; @Injectable() export class ContactService { constructor(private http: HttpClient) { } sendMessage(email: String, sujet: String, message: String, ) { console.log("email : " + email); console.log("sujet : " + sujet); console.log("message : " + message); } }<file_sep>import { HttpClient } from "@angular/common/http"; import { Injectable } from "@angular/core"; @Injectable() export class RestaurantService { restaurants : any[] = []; constructor(private http: HttpClient) { this.findAllRestaurantFromApi(); } findAllRestaurantFromApi() { this.restaurants = [ { name: 'Mcdo', description: 'description mcdo', dateCreation: new Date() }, { name: '<NAME>', description: 'description lyon', dateCreation: new Date() }, { name: '<NAME>', description: 'description king', dateCreation: new Date() }, ] } getRestaurant() { return this.restaurants; } }<file_sep> <h1 class="text-center font-weight-bold mt-5">Nos collaborateurs</h1> <hr style="width: 20%; background: red"> <div class="mt-5"> <h4>Nos collaborateurs</h4> <ul *ngFor="let r of restaurants" class="list-group"> <app-collaborateur [name]="r.name"></app-collaborateur> </ul> <hr> <section id="services" class="bg-light pt-100 pb-70"> <div class="container"> <div class="row align-items-center"> <div class="col-lg-5"> <h2 class="title"><span>Rejoignez</span> Nous et devenez un de nos collaborateurs</h2> <p class=" mt-3 ">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aut optio velit inventore, expedita quo laboriosam possimus ea consequatur vitae, doloribus consequuntur ex. Nemo assumenda laborum vel, labore ut velit dignissimos.</p> <a routerLink="/contact" class="btn btn-primary my-5">Nous contactez</a> </div> <div class="col-lg-7"> <app-collabarez-info></app-collabarez-info> </div> </div> </div> </section> </div><file_sep>import { Component, OnInit } from '@angular/core'; import { faMapMarked, faPhone, faEnvelopeOpen } from '@fortawesome/free-solid-svg-icons'; @Component({ selector: 'app-contact-info', templateUrl: './contact-info.component.html', styleUrls: ['./contact-info.component.css'] }) export class ContactInfoComponent implements OnInit { faMapMarked = faMapMarked; faPhone = faPhone; faEnvelopeOpen = faEnvelopeOpen; constructor() { } ngOnInit(): void { } } <file_sep>import { Component, OnInit } from '@angular/core'; import { RestaurantService } from '../services/RestaurantService'; @Component({ selector: 'app-collaborez', templateUrl: './collaborez.component.html', styleUrls: ['./collaborez.component.css'] }) export class CollaborezComponent implements OnInit { restaurants: any[] = []; constructor(private restaurantService: RestaurantService) { } ngOnInit(): void { this.restaurants = this.restaurantService.getRestaurant(); } } <file_sep>import { formatCurrency } from '@angular/common'; import { Component, OnInit } from '@angular/core'; import { NgForm } from '@angular/forms'; import { ContactService } from '../services/ContactService'; import { faEnvelopeSquare, faTag, faPencilAlt } from '@fortawesome/free-solid-svg-icons'; @Component({ selector: 'app-contact-form', templateUrl: './contact-form.component.html', styleUrls: ['./contact-form.component.css'] }) export class ContactFormComponent implements OnInit { faEnvelopeSquare = faEnvelopeSquare; faTag = faTag; faPencilAlt = faPencilAlt; sending: boolean = false; sendDone: boolean = false; constructor(private contactService: ContactService) { } ngOnInit(): void { } submited(form: NgForm) { this.sending = true; this.contactService.sendMessage(form.value['email'], form.value['sujet'], form.value['message']); setTimeout( () => { this.sending = false; this.sendDone = true; }, 2000 ); } } <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-collabarez-info', templateUrl: './collabarez-info.component.html', styleUrls: ['./collabarez-info.component.css'] }) export class CollabarezInfoComponent implements OnInit { constructor() { } ngOnInit(): void { } } <file_sep>import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { AboutComponent } from './about/about.component'; import { FormsModule } from '@angular/forms'; import { RestaurantService } from './services/RestaurantService'; import { ContactComponent } from './contact/contact.component'; import { HomeComponent } from './home/home.component'; import { ContactFormComponent } from './contact-form/contact-form.component'; import { HttpClientModule } from '@angular/common/http' import { ContactService } from './services/ContactService'; import { CollaborezComponent } from './collaborez/collaborez.component'; import { CollaborateurComponent } from './collaborateur/collaborateur.component'; import { FontAwesomeModule } from '@fortawesome/angular-fontawesome'; import { ContactInfoComponent } from './contact-info/contact-info.component'; import { CollabarezInfoComponent } from './collabarez-info/collabarez-info.component'; import { FooterComponent } from './footer/footer.component'; @NgModule({ declarations: [ AppComponent, AboutComponent, ContactComponent, HomeComponent, ContactFormComponent, CollaborezComponent, CollaborateurComponent, ContactInfoComponent, CollabarezInfoComponent, FooterComponent ], imports: [ BrowserModule, AppRoutingModule, FormsModule, HttpClientModule, FontAwesomeModule ], providers: [ RestaurantService, ContactService, ], bootstrap: [AppComponent] }) export class AppModule { }
2b0843b3ff187ddd9cad9965519f3ea131a87468
[ "TypeScript", "HTML" ]
8
TypeScript
taimourya/PFA_ReservationAndLivraison_WebSite
70521d912f687845a03c3356fe76d4e196b67b6d
e40acfe151e8172e9f2d83289839eff5fdb8fd2c
refs/heads/master
<file_sep>const express = require('express'); var router = express.Router(); const mongoose = require('mongoose'); const Albums = mongoose.model('Albums'); var axios = require('axios'); router.get('/', (req, res) => { res.render("album/addOrEdit", { viewTitle: "Coloque o titulo do Album:" }); }); router.post('/', (req, res) => { if (req.body._id == '') salvarAlbum(req, res); else atualizarAlbum(req, res); }); function salvarAlbum(req, res) { var albums = new Albums(); albums.title = req.body.title; albums.idusuario = req.body.idusuario; albums.save((err, doc) => { if (!err) res.redirect('/albums/list'); else { if (err.name == 'ValidationError') { handleValidationErorr(err, req.body); res.render("album/addOrEdit", { viewTitle: "Coloque o titulo do Album:", albums: req.body }); } else console.log('Error ao salvar:' + err); } }); } function atualizarAlbum(req, res) { Albums.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => { if (!err) { res.redirect('albums/list'); } else { if (err.name == 'ValidationError') { handleValidationErorr(err, req.body); res.render("album/addOrEdit", { viewTitle: 'Atualizar Album', albums: req.body }); } } }); } router.get('/list', (req, res) => { Albums.find((err, docs) => { if (!err) { res.render("album/list", { list: docs }); } else { console.log('Erro ao puxar a lista de Albums: ' + err); } }); }); function handleValidationErorr(err, body) { for (field in err.errors) { switch (err.errors[field].path) { case 'title': body['titleError'] = err.errors[field].message; break; default: break; } } } router.get('/delete/:id', (req, res) => { Albums.findByIdAndRemove(req.params.id, (err, doc) => { if (!err) { res.redirect('/albums/list'); } else { console.log('Erro ao deletar : ' + err); } }); }); router.get('/import', (req, res) => { axios .get("http://jsonplaceholder.typicode.com/albums") .then(function (raw) { for (var dados of raw.data) { var albums = new Albums(); albums.title = dados.title; albums.idusuario = dados.userId; albums.save((err, doc) => { if (!err) console.log("add sucess"); else { if (err.name == 'ValidationError') { } else console.log('Error ao salvar:' + err); } }); } res.redirect('/albums/list'); }).catch(function (error) { if (err) console.log("Erro ao consumir API: " + error); }); }); router.get('/:id', (req, res) => { Albums.findById(req.params.id, (err, doc) => { if (!err) { res.render("album/addOrEdit", { viewTitle: "Atualizar Album", albums: doc }); } }); }); module.exports = router;<file_sep>const mongoose = require('mongoose'); //criando conexão com o banco mongoose.connect('mongodb://localhost:27017/AlbumsDB',{useNewUrlParser:true}, (err)=>{ //testando se teve erro ou não de conexão e printando o erro no console if(!err) { console.log('Conectou!!.')} else {console.log('Erro na conexão com o Banco:'+err )} }); require('./albums.model');<file_sep>const mongoose = require('mongoose'); var albumsSchema = new mongoose.Schema({ title: { type: String, required: 'Campo Obrigatório!' }, idusuario: { type: String } }); mongoose.model('Albums', albumsSchema);<file_sep># CRUD,REST NodeJs CRUD E REST UTILIZANDO NODEJS, MONGODB, AXIOS.
77b44884335dc8de44f60c50d43360fdb310075e
[ "JavaScript", "Markdown" ]
4
JavaScript
Thi4gon/CRUD-REST-NodeJs
ee5ce2355fc8f75722d5ab22a78e0ec0ba874f3b
b88ef5ea49ceb98793681ee382932c377b2071e5
refs/heads/master
<file_sep>package com.example.ryutasakamoto.readfelica; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Created by ryuta.sakamoto on 2014/12/01. */ public class DatabaseOpenHelper extends SQLiteOpenHelper { private static final String TAG = "DatabaseOpenHelper"; private static final String SRC_DATABASE_NAME = "StationCode.db"; // assetsフォルダにあるdbのファイル名 private static final String DATABASE_NAME = "myDB"; // コピー先のDB名 private static final int DATABASE_VERSION = 1; private final Context context; private final File databasePath; private boolean createDatabase = false; public DatabaseOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.context = context; this.databasePath = context.getDatabasePath(DATABASE_NAME); } @Override public synchronized SQLiteDatabase getWritableDatabase() { SQLiteDatabase database = super.getWritableDatabase(); if (createDatabase) { try { database = copyDatabase(database); } catch (IOException e) { Log.wtf(TAG, e); // TODO: エラー処理 } } return database; } private SQLiteDatabase copyDatabase(SQLiteDatabase database) throws IOException { // dbがひらきっぱなしなので、書き換えできるように閉じる database.close(); // コピー! InputStream input = context.getAssets().open(SRC_DATABASE_NAME); OutputStream output = new FileOutputStream(databasePath); copy(input, output); createDatabase = false; // dbを閉じたので、また開く return super.getWritableDatabase(); } @Override public void onCreate(SQLiteDatabase db) { super.onOpen(db); // getWritableDatabase()したときに呼ばれてくるので、 // 初期化する必要があることを保存する this.createDatabase = true; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { onUpgrade(db, oldVersion, newVersion); } // CopyUtilsからのコピペ private static int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[1024 * 4]; int count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } }<file_sep>package com.example.ryutasakamoto.readfelica; import android.app.Application; import android.os.StrictMode; import com.example.ryutasakamoto.readfelica.util.DBUtil; /** * Created by ryuta.sakamoto on 2014/12/01. */ public class ReadFelicaApplication extends Application { private static ReadFelicaApplication sInstance; private DBUtil mSuicaDBUtil; public ReadFelicaApplication(){ sInstance = this; mSuicaDBUtil = new DBUtil(this); try { }catch (Exception ex) { throw new RuntimeException(ex); } } public static ReadFelicaApplication getInstance() { return sInstance; } public DBUtil getSuicaDBUtil() { return mSuicaDBUtil; } @Override public void onCreate() { super.onCreate(); StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); } }<file_sep>package com.example.ryutasakamoto.readfelica.util; /** * Created by ryuta.sakamoto on 2014/11/27. */ import java.nio.ByteBuffer; import java.util.Arrays; /** * 各種ユーティリティを提供します * * @author Kazzz * @date 2011/01/24 * @since Android API Level 4 * */ public final class Util { private Util() {} /** * intをバイト配列にします。 * * @param a 整数をセット * @return byte[] byte配列が戻ります */ public static byte[] toBytes(int a) { byte[] bs = new byte[4]; bs[3] = (byte) (0x000000ff & (a)); bs[2] = (byte) (0x000000ff & (a >>> 8)); bs[1] = (byte) (0x000000ff & (a >>> 16)); bs[0] = (byte) (0x000000ff & (a >>> 24)); return bs; } /** * バイトの配列をintにします。 * * @param bytes バイト配列をセット * @return int 整数が戻ります */ public static int toInt(byte... b) { if ( b == null || b.length == 0 ) throw new IllegalArgumentException(); if ( b.length == 1 ) return b[0] & 0xFF; if ( b.length == 2 ) { int i = 0; i |= b[0] & 0xFF; i <<= 8; i |= b[1] & 0xFF; return i; } if ( b.length == 3 ) { int i = 0; i |= b[0] & 0xFF; i <<= 8; i |= b[1] & 0xFF; i <<= 8; i |= b[2] & 0xFF; return i; } return ByteBuffer.wrap(b).getInt(); } /** * byte配列を16進数文字列で戻します * * @param data データをセット * @return 文字列が戻ります */ public static String getHexString(byte data) { return getHexString(new byte[]{data}); } /** * byte配列を16進数文字列で戻します * * @param byteArray byte配列をセット * @return 文字列が戻ります */ public static String getHexString(byte[] byteArray, int... split) { StringBuilder builder = new StringBuilder(); byte[] target = null; if ( split.length <= 1 ) { target = byteArray; } else if ( split.length < 2 ) { target = Arrays.copyOfRange(byteArray, 0, 0 + split[0]); } else { target = Arrays.copyOfRange(byteArray, split[0], split[0] + split[1]); } for (byte b : target) { builder.append(String.format("%02x", b).toUpperCase()); } return builder.toString(); } /** * byte配列を2進数文字列で戻します * * @param data byteデータをセット * @return 文字列が戻ります */ public static String getBinString(byte data) { return getBinString(new byte[]{data}); } /** * byte配列を2進数文字列で戻します * * @param byteArray byte配列をセット * @return 文字列が戻ります */ public static String getBinString(byte[] byteArray, int... split) { StringBuilder builder = new StringBuilder(); byte[] target = null; if ( split.length <= 1 ) { target = byteArray; } else if ( split.length < 2 ) { target = Arrays.copyOfRange(byteArray, 0, 0 + split[0]); } else { target = Arrays.copyOfRange(byteArray, split[0], split[0] + split[1]); } for (byte b : target) { builder.append(String.format("%8s" , Integer.toBinaryString(b & 0xFF)).replaceAll(" ", "0")); } return builder.toString(); } }
226a9ca13c29de55bb360e195f9944a1d97e9ca6
[ "Java" ]
3
Java
gonta/ReadFelica1127
34b7c1022b4e0b92ac440f0d8bcfa282a522bd86
d92ebf852f5b15db019bac238f68d280c93e84d6
refs/heads/master
<repo_name>artuntun/kinect-gestures<file_sep>/loadFile.py from collections import deque import numpy as np class SkeletonFrame(): """This class store data for each Skeletonframe""" def __init__(self, line): tokens = line.split() self.label = tokens[0] self.hand_left = np.array(tokens[1:4], dtype=np.float32) self.elbow_left = np.array(tokens[4:7], dtype=np.float32) self.elbow_right= np.array(tokens[7:10], dtype=np.float32) self.hand_right = np.array(tokens[10:13], dtype=np.float32) self.neck = np.array(tokens[13:16], dtype=np.float32) self.spine = np.array(tokens[16:19], dtype=np.float32) def load_skeleton(file): """Read Data from file and generate a list of essays""" with open(file, 'r') as f: essay_list = list(f) skeleton_queue = deque() trial_queue = deque() for line in essay_list: if line == "\r\n": trial_queue.append(skeleton_queue) skeleton_queue = deque() else: skeleton_queue.append(SkeletonFrame(line)) return trial_queue def center_normalize_coordenates(trial_queue): """Center all the coordenates at the origin and normalize with a factor of 0.15""" norm = 0.15 #Normalaize factor spine_sum = np.array([0.0,0.0,0.0], dtype=np.float32) for p,essay_aux in enumerate(trial_queue): #GET CENTROID and mean distance between neck and spine of the current essay distance_sum = 0.0 for i,ske in enumerate(trial_queue[p]): distance = np.linalg.norm(ske.neck - ske.spine) distance_sum += distance spine_sum += ske.spine centroid = spine_sum / (i+1) mean = distance_sum / (i+1) normalizer = mean/norm spine_sum = [0.0,0.0,0.0] #substract CENTROID and normalize each coordenate for i,ske_frame in enumerate(trial_queue[p]): trial_queue[p][i].spine = (trial_queue[p][i].spine - centroid)/normalizer trial_queue[p][i].hand_left = (trial_queue[p][i].hand_left - centroid)/normalizer trial_queue[p][i].hand_right = (trial_queue[p][i].hand_right - centroid)/normalizer trial_queue[p][i].elbow_left = (trial_queue[p][i].elbow_left - centroid)/normalizer trial_queue[p][i].elbow_right = (trial_queue[p][i].elbow_right - centroid)/normalizer trial_queue[p][i].neck = (trial_queue[p][i].neck - centroid)/normalizer return trial_queue def extract_attributes(trial_queue, n=6): """extracting attributes from data""" attributes_queue = [] label_list = [] for p,essay_aux in enumerate(trial_queue): samples = len(essay_aux) div = int(samples/n) select = 0 buffer_queue = [] buffer_queue2 = [] for x in xrange(0,n): buffer_queue.append(essay_aux[select]) select += div for x in xrange(0,n-1): dif_hand_left = buffer_queue[x+1].hand_left - buffer_queue[x].hand_left dif_hand_right = buffer_queue[x+1].hand_right - buffer_queue[x].hand_right dif_elbow_left = buffer_queue[x+1].elbow_left - buffer_queue[x].elbow_left dif_elbow_right = buffer_queue[x+1].elbow_right - buffer_queue[x].elbow_right attributes_frame = np.array([dif_hand_left,dif_hand_right,dif_elbow_left,dif_elbow_right]) buffer_queue2.append(attributes_frame) attributes_queue.append(buffer_queue2) label_list.append(essay_aux[-1].label) #only necessary one label from all frames return attributes_queue, label_list def load_data(file_path): """return data normalized and attributes extracted. Also converted to numpy arrays for suiting with sklearn""" data_set = load_skeleton(file_path) processed_data = center_normalize_coordenates(data_set) data_o, labels_o = extract_attributes(processed_data) labels = np.array(labels_o) data_aux = np.array(data_o) data = data_aux.reshape(len(labels),60) return data, labels def show_info(labels): dic_labels = {labels[0]: 0} #init dic of all labels and times is repeated for label in labels: if label in dic_labels: dic_labels[label] = dic_labels[label] + 1 else: dic_labels.update({label: 1}) print "------------------------DATA INFORMATION-----------------------------" print "There is ", len(labels), " samples.. " for key in dic_labels: print "{0} samples of {1}" .format(dic_labels[key], key) <file_sep>/Scripts/removecarriegereturn.py def remove_carriege(file): """Read Data from file and generate a list of essays""" with open(file, 'r') as f: essay_list = list(f) count = "0" with open(file, 'w') as f: for line in essay_list: if line != "\n": f.write(line) else: f.write("\r\n") remove_carriege("skeletonData.txt") print "Done" <file_sep>/Scripts/parsingcommas.py # -*- coding: utf-8 -*- """ Created on Fri May 15 18:33:19 2015 @author: arturo """ print "starting parsing" with open('skeletonData.txt', 'r') as data: plaintext = data.read() plaintext = plaintext.replace(',', '.') print "Finish parsing" <file_sep>/classifiers.py import numpy as np # print "Prediction time:", t1-t0,"s" import matplotlib.pyplot as plt import loadFile # Custom library from sklearn.svm import SVC from sklearn.naive_bayes import GaussianNB from sklearn.neighbors import KNeighborsClassifier from sklearn import tree from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier,ExtraTreesClassifier,BaggingClassifier,AdaBoostClassifier from sklearn.cross_validation import StratifiedKFold from sklearn.grid_search import GridSearchCV from sklearn.metrics import accuracy_score from sklearn.metrics import make_scorer # To make a scorer for the GridSearch. from collections import deque from sklearn.metrics import accuracy_score plt.close('all') Data_Prep = 1 SVM_cl = 0 KNN_cl = 1 GNB_cl = 1 Tree_cl = 0 LDA_cl = 0 #%%load kinect normalized data data, labels = loadFile.load_data("skeletonData.txt") loadFile.show_info(labels) #print data info ################################################################# #################### DATA PREPROCESSING ######################### ################################################################# if (Data_Prep == 1): from sklearn import preprocessing from sklearn import cross_validation #randomize the samples index and divide between Training and Testing data Xtrain, Xtest, Ytrain, Ytest = cross_validation.train_test_split(data, labels, test_size = 0.2, random_state=0) #Standarize the features with train data: zero mean and unit variance scaler = preprocessing.StandardScaler().fit(Xtrain) Xtrain = scaler.transform(Xtrain) Xtest = scaler.transform(Xtest) ################################################################# ###################### CLASSIFIERS ############################## ################################################################# if (Tree_cl == 1): param_grid = dict() param_grid.update({'max_features':[None,'auto']}) param_grid.update({'max_depth':np.arange(1,21)}) param_grid.update({'min_samples_split':np.arange(2,11)}) gtree = GridSearchCV(DecisionTreeClassifier(),param_grid,scoring='precision',cv=StratifiedKFold(Ytrain, n_folds = 5),refit=True,n_jobs=-1) gtree.fit(Xtrain,Ytrain) scores = np.empty((6)) scores[0] = gtree.score(Xtrain,Ytrain) scores[1] = gtree.score(Xtest,Ytest) print "---------------------Decission Tree Clasifier--------------" print('Decision Tree, train: {0:.02f}% '.format(scores[0]*100)) print('Decision Tree, test: {0:.02f}% '.format(scores[1]*100)) if (LDA_cl == 1): from sklearn.lda import LDA lda = LDA() lda.fit(Xtrain,Ytrain) scores = np.empty((4)) scores[0] = lda.score(Xtrain,Ytrain) scores[1] = lda.score(Xtest,Ytest) print "---------------------Linear Discriminant Analysis---------------------------" print('LDA, train: {0:.02f}% '.format(scores[0]*100)) print('LDA, test: {0:.02f}% '.format(scores[1]*100)) if (GNB_cl == 1): nb = GaussianNB() nb.fit(Xtrain,Ytrain) scores = np.empty((4)) scores[0] = nb.score(Xtrain,Ytrain) scores[1] = nb.score(Xtest,Ytest) print "---------------------Naive Bayes Classifier------------------" # print "Prediction time:", t1-t0, "s" print('Gaussian Naive Bayes, train: {0:.02f}% '.format(scores[0]*100)) print('Gaussian Naive Bayes, test: {0:.02f}% '.format(scores[1]*100)) if (SVM_cl == 1): # Parameters for the validation C = np.logspace(-3,3,10) p = np.arange(2,5) gamma = np.array([0.125,0.25,0.5,1,2,4])/200 # Create dictionaries with the Variables for the validation ! # We create the dictinary for every TYPE of SVM we are gonna use. param_grid_linear = dict() param_grid_linear.update({'kernel':['linear']}) param_grid_linear.update({'C':C}) param_grid_pol = dict() param_grid_pol.update({'kernel':['poly']}) param_grid_pol.update({'C':C}) param_grid_pol.update({'degree':p}) param_grid_rbf = dict() param_grid_rbf.update({'kernel':['rbf']}) param_grid_rbf.update({'C':C}) param_grid_rbf.update({'gamma':gamma}) param = [{'kernel':'linear','C':C}] param_grid = [param_grid_linear,param_grid_pol,param_grid_rbf] # Validation is useful for validating a parameter, it uses a subset of the # training set as "test" in order to know how good the generalization is. # The folds of "StratifiedKFold" are made by preserving the percentage of samples for each class. stkfold = StratifiedKFold(Ytrain, n_folds = 5) # The score function is the one we want to minimize or maximize given the label and the predicted. acc_scorer = make_scorer(accuracy_score) # GridSearchCV implements a CV over a variety of Parameter values !! # In this case, over C fo the linear case, C and "degree" for the poly case # and C and "gamma" for the rbf case. # The parameters we have to give it are: # 1-> Classifier Object: SVM, LR, RBF... or any other one with methods .fit and .predict # 2 -> Subset of parameters to validate. C # 3 -> Type of validation: K-fold # 4 -> Scoring function. sklearn.metrics.accuracy_score gsvml = GridSearchCV(SVC(class_weight='auto'),param_grid_linear, scoring = acc_scorer,cv = stkfold, refit = True,n_jobs=-1) gsvmp = GridSearchCV(SVC(class_weight='auto'),param_grid_pol, scoring = acc_scorer,cv = stkfold, refit = True,n_jobs=-1) gsvmr = GridSearchCV(SVC(class_weight='auto'),param_grid_rbf, scoring =acc_scorer,cv = stkfold, refit = True,n_jobs=-1) gsvml.fit(Xtrain,Ytrain) gsvmp.fit(Xtrain,Ytrain) gsvmr.fit(Xtrain,Ytrain) trainscores = [gsvml.score(Xtrain,Ytrain),gsvmp.score(Xtrain,Ytrain),gsvmr.score(Xtrain,Ytrain)] testscores = [0,0,0,0] testscores[0] = gsvml.score(Xtest,Ytest) testscores[1] = gsvmp.score(Xtest,Ytest) testscores[2] = gsvmr.score(Xtest,Ytest) testscores[3] = gsvmr.score(Xtrain,Ytrain) maxtrain = np.amax(trainscores) maxtest = np.amax(testscores) print "---------------------Support Vector Classifier---------------" print('Linear SVM(C = {0:.02f}), score: {1:.02f}% '.format(gsvml.best_params_['C'], testscores[0]*100)) print('Poly SVM(C = {0:.02f}, degree = {1:.02f}), score: {2:.02f}% '.format(gsvmp.best_params_['C'], gsvmp.best_params_['degree'], testscores[1]*100)) print('rbf SVM(C = {0:.02f}, gamma = {1:.02f}), score: {2:.02f}% '.format(gsvmr.best_params_['C'],gsvmr.best_params_['gamma'] , testscores[2]*100) ) ################################################# #### PLOTTING GRID Search SCORES ####### ################################################# #GRID SEARCH plotting for ploy kernel grid_scores_gsvmp = {} #scores and C values for each degree value tested for i in range(len(gsvmp.grid_scores_)): degree_aux = gsvmp.grid_scores_[i][0]['degree'] c_aux = gsvmp.grid_scores_[i][0]['C'] score = gsvmp.grid_scores_[i][1] if degree_aux not in grid_scores_gsvmp: grid_scores_gsvmp[degree_aux] = {'scores':[], 'C':[]} grid_scores_gsvmp[degree_aux]['scores'].append(score) grid_scores_gsvmp[degree_aux]['C'].append(c_aux) plt.figure() plt.plot(grid_scores_gsvmp[2]['C'],grid_scores_gsvmp[2]['scores'],c='g',lw=2,aa=True, label='degree = 2') plt.plot(grid_scores_gsvmp[3]['C'],grid_scores_gsvmp[3]['scores'],c='b',lw=2,aa=True, label='degree = 3') plt.plot(grid_scores_gsvmp[4]['C'],grid_scores_gsvmp[4]['scores'],c='r',lw=2,aa=True, label='degree = 4') plt.title('Grid precission for C in SVM_poly') plt.xlabel('C') plt.ylabel('Mean training precission') plt.xscale('log') plt.legend(loc=4) plt.grid() plt.show() #GRID SEARCH plotting for rbf kernel grid_scores_gsvmr = {} for i in range(len(gsvmr.grid_scores_)): score = gsvmr.grid_scores_[i][1] gammas = float("{0:.6f}".format(gsvmr.grid_scores_[i][0]['gamma'])) c_aux = gsvmr.grid_scores_[i][0]['C'] if gammas not in grid_scores_gsvmr: grid_scores_gsvmr[gammas] = {'scores':[], 'C':[]} grid_scores_gsvmr[gammas]['scores'].append(score) grid_scores_gsvmr[gammas]['C'].append(c_aux) plt.figure() plt.plot(grid_scores_gsvmr[0.01]['C'],grid_scores_gsvmr[0.01]['scores'],c='g',lw=2,aa=True, label='gamma = 0.01') plt.plot(grid_scores_gsvmr[0.005]['C'],grid_scores_gsvmr[0.005]['scores'],c='r',lw=2,aa=True, label='gamma = 0.005') plt.plot(grid_scores_gsvmr[0.000625]['C'],grid_scores_gsvmr[0.000625]['scores'],c='b',lw=2,aa=True, label='gamma = 0.000625') plt.plot(grid_scores_gsvmr[0.02]['C'],grid_scores_gsvmr[0.02]['scores'],c='y',lw=2,aa=True, label='gamma = 0.02') plt.title('Grid precission for C in SVM_rbf') plt.xlabel('C') plt.ylabel('Mean training precission') plt.xscale('log') plt.legend(loc=4) plt.grid() plt.show() if (KNN_cl == 1): # Perform authomatic grid search params = [{'n_neighbors':np.arange(1,11)}] gknn = GridSearchCV(KNeighborsClassifier(),params,scoring='f1_weighted',cv=StratifiedKFold(Ytrain, n_folds = 5),refit=True,n_jobs=-1) gknn.fit(Xtrain,Ytrain) scores = np.empty((4)) scores[0] = gknn.score(Xtrain,Ytrain) scores[1] = gknn.score(Xtest,Ytest) print "---------------------K-NN Classifier---------------------------" # print "Prediction time:", t1-t0,"s" print('{0}-NN, train: {1:.02f}% '.format(gknn.best_estimator_.n_neighbors,scores[0]*100)) #print('{0}-NN, test: {1:.02f}% '.format(gknn.best_estimator_.n_neighbors,scores[1]*100)) ##### Scores in validation, training and testing data for each K-nn tested tested_Ks = [val[0]['n_neighbors'] for val in gknn.grid_scores_] # K tested in GridSearch scores_validation = [val[1] for val in gknn.grid_scores_] #Scores at validation scores_training = [] scores_testing = [] for x in tested_Ks: testing_clf = KNeighborsClassifier(n_neighbors = x, weights='uniform') testing_clf.fit(Xtrain,Ytrain) scores_testing.append(testing_clf.score(Xtest,Ytest)) scores_training.append(testing_clf.score(Xtrain,Ytrain)) #Plot evolution of parameters performance plt.figure() plt.plot(tested_Ks,scores_validation,c='g',lw=2,aa=True, label='Validation') plt.plot(tested_Ks,scores_training,c='b',lw=2,aa=True, label='Training') plt.plot(tested_Ks,scores_testing,c='r',lw=2,aa=True, label= 'Testing') plt.plot(np.argmax(scores)+1,np.amax(scores),'v') plt.title('Grid precission for k in kNN') plt.xlabel('k') plt.ylabel('Mean training precission') plt.legend() plt.grid() plt.show() # print cross_validate(gknn,Xtest,Ytest)
591e183f954c7fb52dd57b20c8b693a7d7ffc468
[ "Python" ]
4
Python
artuntun/kinect-gestures
b0b617a3cc95454640da7dd12044fd744b87b4d0
92b5a0e064201a3cf9b37490d6c9a1d697a3c5e0
refs/heads/master
<repo_name>gswierczek/better_old<file_sep>/src/main/java/com/codistica/better/model/Bet.java package com.codistica.better.model; /** * Author <NAME> * Created on 2017-11-16 * Contact <EMAIL> */ public class Bet { private Pick pick; private Double odds; private BetStatus betStatus; } <file_sep>/src/main/java/com/codistica/better/model/Coupon.java package com.codistica.better.model; import java.math.BigDecimal; import java.util.List; /** * Author <NAME> * Created on 2017-11-16 * Contact <EMAIL> */ public class Coupon { private BigDecimal stake; private List<Bet> bets; } <file_sep>/src/main/java/com/codistica/better/model/Bank.java package com.codistica.better.model; import java.math.BigDecimal; /** * Author <NAME> * Created on 2017-11-16 * Contact <EMAIL> */ public class Bank { private BigDecimal balance; }
3fbee2751199844c8b5a56e87bed9840748fe842
[ "Java" ]
3
Java
gswierczek/better_old
40fe78469dd990be63c5a6ce5fd76e7d8d32c2e7
3c5811306f3793531959c7d3a29b774a7ce9e353
refs/heads/master
<repo_name>shyd/google-photos<file_sep>/REST/PhotoFrame/Dockerfile FROM node:13 WORKDIR /usr/src/app COPY . . RUN npm install RUN mkdir -p /data/sessions RUN mkdir -p /data/persist-storage VOLUME ["/data"] EXPOSE 8080 CMD [ "node", "app.js" ] <file_sep>/REST/PhotoFrame/static/js/config.js function loadConfig() { $.ajax({ type: 'GET', url: '/getConfig', dataType: 'json', success: (data) => { $('#input-duration').val(data.config.duration); $('#input-interval').val(data.config.interval); $('#input-update').val(data.config.update); $('#input-cycles').val(data.config.cycles); console.log('Loaded config.'); }, error: (data) => { hideLoadingDialog(); handleError('Could not load queue', data) } }) }; function saveConfig() { showLoadingDialog(); $.ajax({ type: 'POST', url: '/saveConfig', dataType: 'json', data: { config: { duration: $('#input-duration').val(), interval: $('#input-interval').val(), update: $('#input-update').val(), cycles: $('#input-cycles').val() } }, success: (data) => { console.log('Config saved.'); window.location = '/config'; hideLoadingDialog(); }, error: (data) => { handleError('Couldn\'t save config', data); } }); } $(document).ready(() => { // Load the queue of photos selected by the user for the photo loadConfig(); $('#button-save').on('click', (e) => { e.preventDefault(); console.log('clicked'); saveConfig(); }); // Clicking log out opens the log out screen. $('#logout').on('click', (e) => { window.location = '/logout'; }); }); <file_sep>/REST/PhotoFrame/docker-compose.yml version: '3' services: photo-frame: image: shyd/google-photos ports: - "8080:8080" env_file: - photo-frame.env restart: unless-stopped volumes: - photo-frame-data:/data volumes: photo-frame-data:
0a323938f4ce97b3eeb45fcad5f2bf787324c100
[ "JavaScript", "Dockerfile", "YAML" ]
3
Dockerfile
shyd/google-photos
aeb3bd237ac5f7049b9e8ba79356712338a04cb4
e8640070b66ce297fd4f37a94e77b203e75c6953
refs/heads/master
<repo_name>545zhou/identify_fraud_from_Enron_emails<file_sep>/poi_id.py #!/usr/bin/python import sys import pickle sys.path.append("../tools/") from feature_format import featureFormat, targetFeatureSplit from tester import test_classifier, dump_classifier_and_data ### Task 1: Select what features you'll use. ### features_list is a list of strings, each of which is a feature name. ### The first feature must be "poi". ### To select which features I should choose, I used two methods. ### One method is learned from previous project. I'll draw the histogram of each feature, with the entried being divided to "poi" and "nopoi". ### By looking into the histograms, I can see if there is a pattern and decide if that features should be chosen to do the prediction. ### Another method is to use the sklearn.feature_selection module as instructed in the class. ### By combining the result from these two method, I can hava an idea which features are important. ### I at first select all the possible features in the beginning and then plot histgrams of each feature ### to investigate the correlation between features and "poi". Then I choose a few important features. ### The feature "email_address" is a string not a number, so I remove it in the first place. features_list_without_poi = ['salary', 'deferral_payments', 'total_payments', 'loan_advances', 'bonus', 'restricted_stock_deferred', 'deferred_income', 'total_stock_value', 'expenses', 'exercised_stock_options', 'other', 'long_term_incentive', 'restricted_stock', 'director_fees','to_messages', 'from_poi_to_this_person', 'from_messages', 'from_this_person_to_poi', 'shared_receipt_with_poi'] features_list = features_list_without_poi[:] features_list.insert(0, 'poi') ### Load the dictionary containing the dataset data_dict = pickle.load(open("final_project_dataset.pkl", "r") ) ### At the first glance of the data, I found this is a person called "TOTAL". It's obivious that this entry should be removed. data_dict.pop("TOTAL") feature_value_list_poi = [] feature_value_list_nopoi = [] for i in range(0, 19): feature_value_list_poi.append([]) feature_value_list_nopoi.append([]) features_with_NaN = {'salary': 0, 'deferral_payments': 0, 'total_payments': 0, 'loan_advances': 0, 'bonus': 0, 'restricted_stock_deferred': 0, 'deferred_income': 0, 'total_stock_value': 0, 'expenses': 0, 'exercised_stock_options': 0, 'other': 0, 'long_term_incentive': 0, 'restricted_stock': 0, 'director_fees': 0,'to_messages': 0, 'from_poi_to_this_person': 0, 'from_messages': 0, 'from_this_person_to_poi': 0, 'shared_receipt_with_poi': 0} for person in data_dict.values(): for i in range(0, 19): if person['poi'] == True: if person[features_list_without_poi[i]] != 'NaN': feature_value_list_poi[i].append(person[features_list_without_poi[i]]) else: feature_value_list_poi[i].append(0); features_with_NaN[features_list_without_poi[i]] += 1 else: if person[features_list_without_poi[i]] != 'NaN': feature_value_list_nopoi[i].append(person[features_list_without_poi[i]]) else: feature_value_list_nopoi[i].append(0); features_with_NaN[features_list_without_poi[i]] += 1 import pylab as pl pl.close('all') ### Now draw the histogram of each feature with people being diveded into two groups "poi" and "no poi". ### I found that for features "loan_advances", "restricted_stock_deferred" and "director_fees", ### there is none or only one entry in "poi" group. So these are not important features. I will skip them. k = 0 for i in range(0, 19): if( features_list_without_poi[i] == "loan_advances" or features_list_without_poi[i] == "restricted_stock_deferred" or features_list_without_poi[i] == "director_fees"): continue pl.figure(k / 4 + 1) pl.subplot(2, 2, k % 4 + 1) k = k + 1 pl.hist(feature_value_list_poi[i], bins = 50, histtype='bar', normed=True, color='r', label='poi') pl.hist(feature_value_list_nopoi[i], bins = 50, histtype='bar', normed=True, alpha = 0.5, color='b', label='no poi') pl.legend() pl.title(features_list_without_poi[i]) ### From the generated plots, I choose 6 subplots in which I think we can see the distributions of "poi" and "no poi" are different. ### These 6 subplots are corresponding to 6 features: 'bonus', 'salary', 'expenses', 'to_messages', 'shared_receipt_with_poi', and 'exercised_stock_options'. ### But the features are not decided yet. Let's check the second method using the sklearn.feature_selection module. data = featureFormat(data_dict, features_list, remove_all_zeroes=False, sort_keys = True) labels, features = targetFeatureSplit(data) from sklearn import cross_validation features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(features, labels, test_size = 0.3, random_state = 42) ###I want to order the featurs according to their importance. from sklearn.feature_selection import SelectPercentile, f_classif selector = SelectPercentile(f_classif, percentile = 100) selector.fit(features_train, labels_train) important_features_with_score = zip(features_list_without_poi, selector.scores_) important_features_with_score.sort(key = lambda x: x[1], reverse = True) ## Print the features according to their importance. for item in important_features_with_score: print item ### From the above printed result, we see 6 most important features are "'bonus','exercised_stock_options', ### 'total_stock_value', 'salary','total_payments', 'shared_receipt_with_poi'. ### Using method 2 to select features are more objective. We now know the important features. But this selection process is not over yet. ### Later I'm going to remove outliers and recalculate the importance of features and then decide which features I will select. ### Task 2: Remove outliers ### I would draw 5 histograms corresponding 5 features to check the outlier. ### By looking at feature "total_stock_value", I found there is one pearson called "<NAME>" having negative total_stock_value. This entry should be deleted. data_dict.pop("<NAME>") ### After removing the outliers, lets check the importance of features again data = featureFormat(data_dict, features_list, remove_all_zeroes=False, sort_keys = True) labels, features = targetFeatureSplit(data) from sklearn import cross_validation features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(features, labels, test_size = 0.3, random_state = 42) selector = SelectPercentile(f_classif, percentile = 100) selector.fit(features_train, labels_train) important_features_with_score = zip(features_list_without_poi, selector.scores_) important_features_with_score.sort(key = lambda x: x[1], reverse = True) ## Print the features according to their importance. print "After removing outliers, let us check the importance of features calculated by SelectedPercntile again" for item in important_features_with_score: print item features_sorted_by_score = [] for i in range(0, 19): features_sorted_by_score.append(important_features_with_score[i][0]) ### Now use decision tree to calculate the importance from sklearn import tree clf = tree.DecisionTreeClassifier(random_state=42) clf = clf.fit(features, labels) feature_importances_by_DT = zip(features_list_without_poi, clf.feature_importances_) feature_importances_by_DT.sort(key = lambda x: x[1], reverse = True) print "Check the importance of features calculated by Decision Tree" for item in feature_importances_by_DT: print item features_sorted_by_score_by_DT = [] for i in range(0, 19): features_sorted_by_score_by_DT.append(feature_importances_by_DT[i][0]) ### Check how many features I should select ### For GaussianNB #uncomment to run #from sklearn.naive_bayes import GaussianNB #for i in range(1, 19): # important_features = features_sorted_by_score[0:i] # important_features.insert(0, 'poi') # # clf = GaussianNB() # print i # test_classifier(clf, data_dict, important_features) ### For Decision Tree #uncomment to run #for i in range(1, 19): # important_features = features_sorted_by_score_by_DT[0:i] # important_features.insert(0, 'poi') # # clf = tree.DecisionTreeClassifier() # print i # test_classifier(clf, data_dict, important_features) important_features = ['bonus', 'salary','shared_receipt_with_poi','deferred_income','exercised_stock_options','total_stock_value', 'expenses'] important_features.insert(0, 'poi') important_features_by_DT = ['exercised_stock_options', 'bonus'] important_features_by_DT.insert(0, 'poi') ### Task 3: Create new feature(s) ### Store to my_dataset for easy export below. ### In the lecture, instructor was using the ratio of 'from_poi_to_this_person' / 'to_messages' ### and ratio of 'from_this_perston_to_poi' / 'from_messages' to show how to create new features. I want to try some thing new. ### The feature I created is called 'long_term_centive_ratio'. Its defination is 'long_term_centive' divided by 'total_payments'. my_dataset = data_dict for person in my_dataset.values(): if (person['total_payments'] != 'NaN' and person['long_term_incentive'] != 'NaN' and person['total_payments'] != 0): person['long_term_incentive_ratio'] = float(person['long_term_incentive']) / person['total_payments'] else: person['long_term_incentive_ratio'] = 0; ### What I think is that for 'poi's, the 'long_term_centive_ratio' may be higher than 'nopoi's. ### To verify my thought, let me draw a histogram using the new created feature and also check if adding this feature increase the final preision or recall. ratio_value_list_poi = [] ratio_value_list_nopoi = [] for person in my_dataset.values(): if person['poi'] == True: ratio_value_list_poi.append(person['long_term_incentive_ratio']) else: ratio_value_list_nopoi.append(person['long_term_incentive_ratio']) pl.figure(5) pl.hist(ratio_value_list_poi, bins = 200, histtype='bar', normed=True, color='r', label='poi') pl.hist(ratio_value_list_nopoi, bins = 50, histtype='bar', normed=True, alpha = 0.5, color='b', label='no poi') pl.legend() pl.title('long_term_incentive_ratio') ### From the histogram, it seems 'poi's are more likely to have higher "long_term_incentive_ratio". ### Moreover, when I use this ratio in the given GaussianNB() classifier to test prediction, I found the performance with this new feature is better. So I will use it. important_features.append('long_term_incentive_ratio') #important_features_by_DT.append('long_term_incentive_ratio') ### Extract features and labels from dataset for local testing data = featureFormat(my_dataset, features_list, sort_keys = True) labels, features = targetFeatureSplit(data) ### Task 4: Try a varity of classifiers ### Please name your classifier clf for easy export below. ### Note that if you want to do PCA or other multi-stage operations, ### you'll need to use Pipelines. For more info: ### http://scikit-learn.org/stable/modules/pipeline.html ### The classifiers I will try are Naivie Bayes, SVM and Decision Tree. from sklearn.naive_bayes import GaussianNB from sklearn.pipeline import Pipeline from sklearn.svm import SVC from sklearn import tree from sklearn.decomposition import PCA print "Testing Naive Bayes classifier" ### Naive Bayes method doesn't require rescaling the features. clf = GaussianNB() # Provided to give you a starting point. Try a varity of classifiers. test_classifier(clf, my_dataset, important_features) print "Testing SVM classifier" #clf = SVC() #test_classifier(clf, my_dataset, important_features) ### There is an error when runing SVM, so I will skip it. print "SVM classifier does not work on the dataset, so skip it" print "Testing Decision Tree classifier" ### Decision also does not need rescaling the features. clf = tree.DecisionTreeClassifier(random_state=42) test_classifier(clf, my_dataset, important_features_by_DT) ### Task 5: Tune your classifier to achieve better than .3 precision and recall ### using our testing script. ### Because of the small size of the dataset, the script uses stratified ### shuffle split cross validation. For more info: ### http://scikit-learn.org/stable/modules/generated/sklearn.cross_validation.StratifiedShuffleSplit.html ### I decide to use Decision Tree to be the classifier to make my final decision. Although the accuracy of GaussianNB() is a little higher than DecisionTreeClassifier(), ### the DecisionTreeClassifier() gives me more balanced precision and recall values. DecisionTreeClassifier() also has the potential to improve by tuning the parameters. ### uncomment to run, it will take a few minutes #for pca_n_component in [None, 1, 2]: # for dt_min_samples_split in [2, 4, 6, 8]: # for dt_max_depth in [None, 5, 10, 15]: # print [pca_n_component, dt_min_samples_split, dt_max_depth] # clf = Pipeline([('pca', PCA(n_components = pca_n_component)), ('dt', tree.DecisionTreeClassifier(min_samples_split = dt_min_samples_split,max_depth = dt_max_depth, random_state= 42))]) # test_classifier(clf, my_dataset, important_features_by_DT) features_list = important_features_by_DT clf = Pipeline([('pca', PCA(n_components = 2)), ('dt', tree.DecisionTreeClassifier(min_samples_split = 8,max_depth = 5, random_state= 42))]) test_classifier(clf, my_dataset, features_list) ### Dump your classifier, dataset, and features_list so ### anyone can run/check your results. dump_classifier_and_data(clf, my_dataset, features_list)
b95d356216ba91fc988ac23759df190d18d85d4d
[ "Python" ]
1
Python
545zhou/identify_fraud_from_Enron_emails
5a1d787cec35634e505fb357f7da023ae8828346
52d608006b63f414e6a7c0826e91b626ebe7ec98
refs/heads/master
<file_sep># python Leave any hint about task 2 because i could not understand it, but I am working on it. anyway please give any recommendations especially about task4. thanks) <file_sep>import os try: input_path = input(r"path: ") # absolute path to file base_path = os.path.normpath(input_path) with open(base_path) as f: reader = f.readlines() except FileNotFoundError: print(r'you must write absolute path like: "D:\Users\Voldemort\*.txt"') temporary_list = [r for read in reader for r in read.split()] filtered_list = [lis.replace(':', '') for lis in temporary_list] sorted_list = [int(sort) for sort in filtered_list] hours = [hour for hour in range(800, 2100, 100)] divided_hours = [[], [], [], [], [], [], [], [], [], [], [], []] for numb in range(12): for element in sorted_list: if hours[numb + 1] > element > hours[numb]-1: divided_hours[numb].append(element) visitor_hourly = [len(items) for items in divided_hours] index_of_max = visitor_hourly.index(max(visitor_hourly)) list_copy = sorted(divided_hours[index_of_max]).copy() # Fix me def final(tmp_list): ''' :param tmp_list: list consisting integers :return: concatenated with ':' list objects of str type ''' tmp = [] for item in tmp_list: it = str(item) if len(it) > 3: it = it[0:2]+':'+it[2:] tmp.append(it) else: it = it[0:1]+':'+it[1:] tmp.append(it) return tmp[0]+' '+tmp[-1] print(final(list_copy), '\n') <file_sep>import os input_path = input(r" ") # absolute path to file base_path = os.path.normpath(input_path) with open(base_path) as f: reader = f.readlines() temporary_list = [float(r) for read in reader for r in read.split()] sorted_list = sorted(temporary_list) def percentile(iterable, percent): tmp = int(round(percent * len(iterable) + 0.5)) if tmp > 1: return iterable[tmp-2] return iterable[0] def median(n: list): ''' :param n: is eny iterable :return: index of iterable that equals to median if it is 2 items than 1x+2x/2 ''' length = len(n) if length % 10 == 0: bl = (n[int(length / 2)] + n[int(length / 2 - 1)]) / 2 return bl return n[int(length / 2)] print("%.2f" % percentile(sorted_list, 0.9), '\n') print("%.2f" % median(sorted_list), '\n') print("%.2f" % sorted_list[-1], '\n') print("%.2f" % sorted_list[0], '\n') # {"%.2f"%} or {int(n*100)/100} :both non eficient <file_sep>import os import glob input_directory = input(r"directoy: ") # absolute path to files path = glob.glob(input_directory+os.sep+'*.txt') cashbox = [] for p in path: with open(p) as f: reader = f.readlines() temporary_list = [float(r) for read in reader for r in read.split()] cashbox.append(temporary_list) intervals = [] for x in range(16): count = cashbox[0][x] + cashbox[1][x] + cashbox[2][x] + cashbox[3][x] + cashbox[4][x] intervals.append(count) print(intervals.index(max(intervals))+1) # printing interval from 1 to 16
070801d7a56b71d475baf9031c8ae61540310939
[ "Markdown", "Python" ]
4
Markdown
azikoDron/python
425d4622469475a8eb87d82fe97c21ffbc0ffb29
ccef77da2634c9a183c81b245a22b87b9546af08
refs/heads/master
<file_sep>CREATE TABLE users ( id INTEGER PRIMARY KEY, email VARCHAR(50) );<file_sep>package demo.config; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabase; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder; import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableTransactionManagement public class HibernateConfig { @Bean public DataSource dataSource() { EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); EmbeddedDatabase db = builder .setType(EmbeddedDatabaseType.H2) .addScript("create-db.sql") .addScript("insert-data.sql") .build(); return db; } // @Bean(name = "dataSource") // public DriverManagerDataSource dataSource(@Autowired Environment env) { // DriverManagerDataSource ds = new DriverManagerDataSource(); // ds.setDriverClassName("com.mysql.jdbc.Driver"); // ds.setUrl(env.getProperty("database.url")); // ds.setUsername(env.getProperty("database.username")); // ds.setPassword(env.getProperty("database.password")); // return ds; // } @Bean(name = "sessionFactory") public SessionFactory sessionFactory() { LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource()); builder.scanPackages("demo.*").addProperties(getHibernateProperties()); return builder.buildSessionFactory(); } private Properties getHibernateProperties() { Properties prop = new Properties(); prop.put("hibernate.format_sql", "true"); prop.put("hibernate.show_sql", "true"); prop.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); return prop; } @Bean public HibernateTransactionManager txManager() { return new HibernateTransactionManager(sessionFactory()); } } <file_sep>log4j.rootLogger=INFO, stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{MM/dd/yyyy HH:mm:ss} | %-5p | [%-5L] | [%35.35C{3}] - %m%n<file_sep>INSERT INTO users VALUES (1, '<EMAIL>'); INSERT INTO users VALUES (2, '<EMAIL>'); INSERT INTO users VALUES (3, '<EMAIL>');
ed4ecdd563535543aa68032e2f75bf3062822dbb
[ "Java", "SQL", "INI" ]
4
SQL
tanpatrick/legacy-spring-hibernate-demo
3ee31cfff2a370a6e0fbd558628b8f6a26336676
d9aa8c10dfac7d4e35b1c58af169efc0960d2e98
refs/heads/master
<repo_name>vitland/telegram_bot<file_sep>/index.js var TelegramBot = require('node-telegram-bot-api'); var token = '<KEY>' const bot = new TelegramBot(token, { polling: true }); bot.on('message', msg => { console.log(msg) const { chat: { id }} = msg bot.sendMessage(id, 'Pong ' + msg.from.username) })
b4a789cdd9cbebc076e2e7a6d78563bbac4e5fcc
[ "JavaScript" ]
1
JavaScript
vitland/telegram_bot
18a06bcfeaecccead3235b09ac69a912d2136f59
679e4a2b06fe19b8ab7cb20cf89916090cfe8a19
refs/heads/master
<file_sep>$(document).ready(function () { AOS.init({ // Global settings: container: "#how-does-it-work", // Settings that can be overridden on per-element basis, by `data-aos-*` attributes: offset: 50, // offset (in px) from the original trigger point delay: 0, // values from 0 to 3000, with step 50ms duration: 1000, // values from 0 to 3000, with step 50ms easing: 'ease-in-out', // default easing for AOS animations once: false, // whether animation should happen only once - while scrolling down mirror: true, // whether elements should animate out while scrolling past them anchorPlacement: 'bottom-bottom', // defines which position of the element regarding to window should trigger the animation }); // const vh = document.body.clientHeight, // vw = document.body.clientWidth; $('#scroll-content').WS_ScroLi({ validEnd: { status: true, icon: 'fas fa-check' }, // you can enter any selector you want and assign it an icon from fontawesome library sections: [ // ['#how-does-it-work', ''], ['#step1', 'fa fa-info'], ['#step2', 'fa fa-id-card-o'], ['#step3', 'fa fa-mobile'], ], position: { x: ['left', 20], y: ['top', 100] }, icon: { size: 60, borderWidth: 1, borderRadius: 100, color: '#FF541A', colorPast: '#FF6E0B', colorOff: 'grey' }, line: { height: 30, width: 3, color: '#FF6E0B', colorPast: '#FF6E0B', colorOff: 'grey', } }); function isElementInViewport(element) { return element.getBoundingClientRect().bottom <= (window.innerHeight || document. documentElement.clientHeight) } document.body.addEventListener("scroll", function() { if (isElementInViewport(document.getElementById('customize-header'))) { console.log("hide"); document.getElementById('WS-ScroLi').style.display = "none"; } }); document.getElementById("pageToggle").addEventListener("click", function() { if(document.getElementById("pageToggle").checked) { $(".business-container").css("display", "none"); $(".customer-container").css("display", "block"); $("section").css("background-color", "rgb(23,17,66)"); } else { $(".customer-container").css("display", "none"); $(".business-container").css("display", "block"); $("section").css("background-color", "rgb(241,241,241)"); } }); });
6e5f838d07a74a18d8e79b8db15c0b371dd3c75a
[ "JavaScript" ]
1
JavaScript
junh4533/qronus-website
10a23c6b1860323c8fd0d06170f2322c69ad36d7
642ef522fbc58bae4fb90ea602c01c157234e673
refs/heads/master
<repo_name>174381115/private-study<file_sep>/HotLoadClass/src/com/ruijie/classloader/MyClassLoader.java package com.ruijie.classloader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; public class MyClassLoader extends ClassLoader { // 要加载的java类的classpath路径 private String classPath; public MyClassLoader(String classPath) { super(ClassLoader.getSystemClassLoader()); this.classPath = classPath; } @Override protected Class<?> findClass(String name) throws ClassNotFoundException { byte[] data = this.loadClassData(name); if(data == null) { System.out.println("未找到类文件"); throw new ClassNotFoundException("FileName: " + name); } return defineClass(name, data, 0, data.length); } private byte[] loadClassData(String name) { try { name = name.replace(".", "/"); FileInputStream is = new FileInputStream(new File(classPath + name + ".class")); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int b = 0; while ((b = is.read()) != -1) { bos.write(b); } is.close(); return bos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } } <file_sep>/HotLoadClass/src/com/ruijie/classloader/app/BaseManager.java package com.ruijie.classloader.app; public interface BaseManager { void logic(); }
b44560080d1cfa4752da54f2b00d6c4c20f44beb
[ "Java" ]
2
Java
174381115/private-study
dc1ae3cb683065240c9591ea3412880fb24f2304
522490ccfd431133c095adf242a108a75a7af60a
refs/heads/master
<file_sep>var mongoose = require("mongoose") const studentSchema = new mongoose.Schema( { studentname:{type:String}, rollno:{type:Number}, admissionno:{type:Number}, college:{type:String}, } ) var studentModel=mongoose.model('students',studentSchema); module.exports={studentModel}
281282714d34569ba898da6f63e76d155ba4c913
[ "JavaScript" ]
1
JavaScript
meghats123/mynodejsstudentapp
b3e851845008699c96e30d9cdb862b13b766f89f
f50beb1b283c61a3a8104db6f57f0340275af704
refs/heads/master
<file_sep>package com.no.company.workfordayserver.entities; import javax.persistence.*; import java.util.Set; @Entity @Table(name = "vacancy") public class Vacancy { @Id @GeneratedValue private long id; @OneToMany(mappedBy = "vacancy") private Set<Dispute> disputes; public long getId() { return id; } public void setId(long id) { this.id = id; } public Set<Dispute> getDisputes() { return disputes; } public void setDisputes(Set<Dispute> disputes) { this.disputes = disputes; } } <file_sep>package com.no.company.workfordayserver.entities; import javax.persistence.*; import java.util.Date; @Entity @Table(name = "payments") public class Payment { @Id @GeneratedValue private long id; private Date date; private double price; @ManyToOne @JoinColumn(name = "id_from") private Card cardFrom; @ManyToOne @JoinColumn(name = "id_to") private Card cardTo; public long getId() { return id; } public void setId(long id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Card getCardFrom() { return cardFrom; } public void setCardFrom(Card cardFrom) { this.cardFrom = cardFrom; } public Card getCardTo() { return cardTo; } public void setCardTo(Card cardTo) { this.cardTo = cardTo; } } <file_sep>spring.datasource.driver-class-name=org.postgresql.Driver spring.jpa.hibernate.ddl-auto=create spring.datasource.url=jdbc:postgresql://localhost:5432/workforday spring.datasource.username=workforday spring.datasource.password=<PASSWORD><file_sep>package com.no.company.workfordayserver.repos; import com.no.company.workfordayserver.entities.Vacancy; import org.springframework.data.jpa.repository.JpaRepository; public interface VacancyRepository extends JpaRepository<Vacancy, Long> { }
72d3c4ea5b1909e4056e599019549738f1ed44de
[ "Java", "INI" ]
4
Java
MykolaHodovychenko/workfordayserver
74bd4742ea74052993200d047ac2e23acca0656e
3c5878f6903c637666b1c50f434ae85a510e8f20
refs/heads/master
<repo_name>avisri/rids-play<file_sep>/es_update_when_notified.sh #!/bin/bash set -o errexit id=${1:? need proper id } counters=${2:-`cat $id`} master=${3:-`hostname -s`} date=`date +%s` curl -XPOST localhost:9200/rids/clients/$id -d '{ "@timestamp":'$date', "ridscounters" : "'$counters'", "lastupdate_master" : "'$master'" }' #vim set ts=3 tw=3 sw=3 <file_sep>/update_from_es.py #!/usr/bin/env python from datetime import datetime import json from elasticsearch import Elasticsearch import glob import socket import os rids_dir="../rids/" rids_dir_files=rids_dir+"[0-9]*[0-9]" hostname=socket.gethostname() def write_data(data): print "writing data:" print 'json/'+ data['_id']+ '.json' with open('json/'+ data['_id']+'.json', 'w') as f: json.dump(data, f) def write_rids(data,): print "writing rid file:" print rids_dir+ data['_id'] with open(rids_dir+data['_id'], 'w') as f: print "writing " + data['_source']['ridscounters'] f.write(data['_source']['ridscounters']) f.close() def read_data(data): with open('json/'+ data['_id']+'.json', 'r') as f: return(json.load(f)) def update_rids(data): print "updating rids" write_rids(data) es = Elasticsearch() # create an index in elasticsearch, ignore status code 400 (index already exists) #es.indices.create(index='my-index', ignore=400) # datetimes will be serialized #es.index(index="my-index", doc_type="test-type", id=42, body={"any": "data", "timestamp": datetime.now()}) # but not deserialized clients=glob.glob(rids_dir_files) print clients for id in clients: data=es.get(index="rids", doc_type="clients",id=os.path.basename(id)) print data #check only if last update master is not this host if data['_source']['lastupdate_master'] != hostname : #check save version , if not there save it first #write if rids has been updated try: sdata = read_data(data) print "read sucess " #print sdata if data['_version'] > sdata ['_version']: write_data(data) update_rids(data) elif (data['_version'] == sdata ['_version'] and data['_source']['ridscounters'] != sdata['_source'] ['ridscounters']): print "same version different values" update_rids(data) else: print "same version %s, not updating rids" %(data['_version']) except IOError: write_data(data) sdata = data print "read failure " #print sdata #update the rids file with new counters update_rids(data) # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
8bf27a32e3343341888b424e79c4c4e3c787a1b1
[ "Python", "Shell" ]
2
Shell
avisri/rids-play
3f575ca26d998102942b53fe20e52a13cbb4c8f0
200d405d75e3e15985343f3bc40742621f5693ee
refs/heads/master
<repo_name>onegodless/TreasureCaveWindows<file_sep>/hero.py #! -*- coding: utf-8 -*- ''' Created on Jan 26, 2018 @author: <NAME> ''' class Hero(object): ''' classdocs ''' def __init__(self, strength = 10, hp = 100): self.__strength = strength self.__hp = hp self.__heroPos = [1,1] def getHeroPos(self): return self.__heroPos def setHeroPos(self, heroPos): self.__heroPos = heroPos <file_sep>/play.py #! -*- coding: utf-8 -*- ''' Created on Jan 25, 2018 @author: <NAME> ''' import os from tittleScreen import TittleScreen from map import Map from control import Control if __name__ == '__main__': clear = lambda: os.system('cls')#lambda function to clear the srceen. tittle = TittleScreen() tittle.startScreen() clear() mapInstance = Map() mapInstance.generateMap() instanceControl = Control() while True: heroMove = instanceControl.userMovement() mapInstance.updateMap(heroMove) <file_sep>/map.py #! -*- coding: utf-8 -*- ''' Created on Jan 26, 2018 @author: <NAME> ''' import sys import os from hero import Hero class Map(object): ''' classdocs ''' initialMap = [[0,0,0,0,0,0,0], #0 represents a wall (#), 1 represents the floor (-) and 2 is the hero(@). [0,1,1,1,1,1,3], [0,1,1,1,1,1,0], [0,1,1,1,1,1,0], [0,3,0,0,0,0,0]] caveMap = [[0,0,0,0,0,0], #0 represents a wall (#), 1 represents the floor (-) and 2 is the hero(@). [3,1,1,1,4,0], [0,1,1,1,1,0], [0,0,0,0,0,0]] currentMap = initialMap def __init__(self): self.instanceHero = Hero() def generateMap(self, parameterMap=initialMap): #converts the integers of map into ASCII symbols. for x in range(len(parameterMap)): print "\n" for y in range(len(parameterMap[x])): if parameterMap[x][y] == 0: sys.stdout.write('#')#wall. sys.stdout.write(' ') #I had to insert spaces between each symbol, so the map won't be deformed on the screen. elif parameterMap[x][y] == 2: sys.stdout.write('@') #@ is the hero's symbol. sys.stdout.write(' ') elif parameterMap[x][y] == 3: #This is a door. sys.stdout.write('+') sys.stdout.write(' ') elif parameterMap[x][y] == 4: sys.stdout.write('D') #this represents the monster. sys.stdout.write(' ') else: sys.stdout.write('-')#floor. sys.stdout.write(' ') def updateMap(self, heroMove): instanceHeroPos = self.instanceHero.getHeroPos() updateInstanceHeroPosX = instanceHeroPos[0] + heroMove[0] updateInstanceHeroPosY = instanceHeroPos[1] + heroMove[1] clear = lambda: os.system('cls') clear() #the screen is wiped everytime the map updates. if self.currentMap[updateInstanceHeroPosX][updateInstanceHeroPosY] == 0: print "you've reached the wall" elif self.currentMap[updateInstanceHeroPosX][updateInstanceHeroPosY] == 3: self.currentMap = self.caveMap self.instanceHero.setHeroPos([1,1]) self.generateMap(self.currentMap) else: self.currentMap[updateInstanceHeroPosX][updateInstanceHeroPosY] = 2 heroPos = [updateInstanceHeroPosX, updateInstanceHeroPosY] self.instanceHero.setHeroPos(heroPos) self.generateMap(self.currentMap) <file_sep>/control.py #! -*- coding: utf-8 -*- ''' Created on Jan 26, 2018 @author: <NAME> ''' class Control(object): ''' classdocs ''' def __init__(self): ''' Constructor ''' def userMovement(self): movement = raw_input('where to?') if movement == 'd': heroMove = [0,1] return heroMove elif movement == 's': heroMove = [1,0] return heroMove<file_sep>/drawObjects.py #! -*- coding: utf-8 -*- ''' Created on Jan 26, 2018 @author: <NAME> ''' class DrawObjects(object): ''' classdocs ''' pass
3c9c7ebe3f115ce5794a78c15fc8c2b13e66de07
[ "Python" ]
5
Python
onegodless/TreasureCaveWindows
2f51d455b9bdf15208197f25d36c125990585338
18a66cebd46f4288567916cdc41f60e5de82cd6b
refs/heads/master
<file_sep>#!/bin/sh set -e cabal exec sigkill clean cabal exec sigkill build cabal exec sigkill deploy git push
a23308c4c579c5f8e2cde2d9031c69e25133a8da
[ "Shell" ]
1
Shell
endgame/sigkill.dk
85bb1c735802699364931e166a39c9abb07a22b1
561b6dbb214c26e26cfa6f4b364f083490935bb6
refs/heads/master
<repo_name>marhub/graphqlite<file_sep>/src/AnnotationReader.php <?php declare(strict_types=1); namespace TheCodingMachine\GraphQLite; use Doctrine\Common\Annotations\AnnotationException; use Doctrine\Common\Annotations\Reader; use InvalidArgumentException; use ReflectionClass; use ReflectionMethod; use ReflectionParameter; use RuntimeException; use TheCodingMachine\GraphQLite\Annotations\AbstractRequest; use TheCodingMachine\GraphQLite\Annotations\Decorate; use TheCodingMachine\GraphQLite\Annotations\Exceptions\ClassNotFoundException; use TheCodingMachine\GraphQLite\Annotations\Exceptions\InvalidParameterException; use TheCodingMachine\GraphQLite\Annotations\ExtendType; use TheCodingMachine\GraphQLite\Annotations\Factory; use TheCodingMachine\GraphQLite\Annotations\MiddlewareAnnotationInterface; use TheCodingMachine\GraphQLite\Annotations\MiddlewareAnnotations; use TheCodingMachine\GraphQLite\Annotations\ParameterAnnotationInterface; use TheCodingMachine\GraphQLite\Annotations\ParameterAnnotations; use TheCodingMachine\GraphQLite\Annotations\SourceFieldInterface; use TheCodingMachine\GraphQLite\Annotations\Type; use Webmozart\Assert\Assert; use function array_diff_key; use function array_filter; use function array_key_exists; use function array_map; use function array_merge; use function array_values; use function assert; use function get_class; use function in_array; use function reset; use function strpos; use function strrpos; use function substr; class AnnotationReader { /** @var Reader */ private $reader; // In this mode, no exceptions will be thrown for incorrect annotations (unless the name of the annotation we are looking for is part of the docblock) public const LAX_MODE = 'LAX_MODE'; // In this mode, exceptions will be thrown for any incorrect annotations. public const STRICT_MODE = 'STRICT_MODE'; /** * Classes in those namespaces MUST have valid annotations (otherwise, an error is thrown). * * @var string[] */ private $strictNamespaces; /** * If true, no exceptions will be thrown for incorrect annotations in code coming from the "vendor/" directory. * * @var string */ private $mode; /** * @param string $mode One of self::LAX_MODE or self::STRICT_MODE * @param string[] $strictNamespaces */ public function __construct(Reader $reader, string $mode = self::STRICT_MODE, array $strictNamespaces = []) { $this->reader = $reader; if (! in_array($mode, [self::LAX_MODE, self::STRICT_MODE], true)) { throw new InvalidArgumentException('The mode passed must be one of AnnotationReader::LAX_MODE, AnnotationReader::STRICT_MODE'); } $this->mode = $mode; $this->strictNamespaces = $strictNamespaces; } /** * @param ReflectionClass<T> $refClass * * @template T of object */ public function getTypeAnnotation(ReflectionClass $refClass): ?Type { try { $type = $this->getClassAnnotation($refClass, Type::class); assert($type instanceof Type || $type === null); if ($type !== null && $type->isSelfType()) { $type->setClass($refClass->getName()); } } catch (ClassNotFoundException $e) { throw ClassNotFoundException::wrapException($e, $refClass->getName()); } return $type; } /** * @param ReflectionClass<T> $refClass * * @template T of object */ public function getExtendTypeAnnotation(ReflectionClass $refClass): ?ExtendType { try { $extendType = $this->getClassAnnotation($refClass, ExtendType::class); assert($extendType instanceof ExtendType || $extendType === null); } catch (ClassNotFoundException $e) { throw ClassNotFoundException::wrapExceptionForExtendTag($e, $refClass->getName()); } return $extendType; } public function getRequestAnnotation(ReflectionMethod $refMethod, string $annotationName): ?AbstractRequest { $queryAnnotation = $this->getMethodAnnotation($refMethod, $annotationName); assert($queryAnnotation instanceof AbstractRequest || $queryAnnotation === null); return $queryAnnotation; } /** * @param ReflectionClass<T> $refClass * * @return SourceFieldInterface[] * * @template T of object */ public function getSourceFields(ReflectionClass $refClass): array { /** @var SourceFieldInterface[] $sourceFields */ $sourceFields = $this->getClassAnnotations($refClass, SourceFieldInterface::class); return $sourceFields; } public function getFactoryAnnotation(ReflectionMethod $refMethod): ?Factory { $factoryAnnotation = $this->getMethodAnnotation($refMethod, Factory::class); assert($factoryAnnotation instanceof Factory || $factoryAnnotation === null); return $factoryAnnotation; } public function getDecorateAnnotation(ReflectionMethod $refMethod): ?Decorate { $decorateAnnotation = $this->getMethodAnnotation($refMethod, Decorate::class); assert($decorateAnnotation instanceof Decorate || $decorateAnnotation === null); return $decorateAnnotation; } /** * Only used in unit tests/ * * @deprecated Use getParameterAnnotationsPerParameter instead * * @throws AnnotationException */ public function getParameterAnnotations(ReflectionParameter $refParameter): ParameterAnnotations { $method = $refParameter->getDeclaringFunction(); Assert::isInstanceOf($method, ReflectionMethod::class); /** @var ParameterAnnotationInterface[] $parameterAnnotations */ $parameterAnnotations = $this->getMethodAnnotations($method, ParameterAnnotationInterface::class); $name = $refParameter->getName(); $filteredAnnotations = array_values(array_filter($parameterAnnotations, static function (ParameterAnnotationInterface $parameterAnnotation) use ($name) { return $parameterAnnotation->getTarget() === $name; })); return new ParameterAnnotations($filteredAnnotations); } /** * @param ReflectionParameter[] $refParameters * * @return array<string, ParameterAnnotations> * * @throws AnnotationException */ public function getParameterAnnotationsPerParameter(array $refParameters): array { if (empty($refParameters)) { return []; } $firstParam = reset($refParameters); $method = $firstParam->getDeclaringFunction(); Assert::isInstanceOf($method, ReflectionMethod::class); /** @var ParameterAnnotationInterface[] $parameterAnnotations */ $parameterAnnotations = $this->getMethodAnnotations($method, ParameterAnnotationInterface::class); /** * @var array<string, array<int, ParameterAnnotations>> */ $parameterAnnotationsPerParameter = []; foreach ($parameterAnnotations as $parameterAnnotation) { $parameterAnnotationsPerParameter[$parameterAnnotation->getTarget()][] = $parameterAnnotation; } // Let's check that the referenced parameters actually do exist: $parametersByKey = []; foreach ($refParameters as $refParameter) { $parametersByKey[$refParameter->getName()] = true; } $diff = array_diff_key($parameterAnnotationsPerParameter, $parametersByKey); if (! empty($diff)) { foreach ($diff as $parameterName => $parameterAnnotations) { throw InvalidParameterException::parameterNotFound($parameterName, get_class($parameterAnnotations[0]), $method); } } return array_map(static function (array $parameterAnnotations) { return new ParameterAnnotations($parameterAnnotations); }, $parameterAnnotationsPerParameter); } public function getMiddlewareAnnotations(ReflectionMethod $refMethod): MiddlewareAnnotations { /** @var MiddlewareAnnotationInterface[] $middlewareAnnotations */ $middlewareAnnotations = $this->getMethodAnnotations($refMethod, MiddlewareAnnotationInterface::class); return new MiddlewareAnnotations($middlewareAnnotations); } /** * Returns a class annotation. Does not look in the parent class. * * @param ReflectionClass<T> $refClass * * @template T of object */ private function getClassAnnotation(ReflectionClass $refClass, string $annotationClass): ?object { $type = null; try { $type = $this->reader->getClassAnnotation($refClass, $annotationClass); } catch (AnnotationException $e) { switch ($this->mode) { case self::STRICT_MODE: throw $e; case self::LAX_MODE: if ($this->isErrorImportant($annotationClass, $refClass->getDocComment() ?: '', $refClass->getName())) { throw $e; } else { return null; } default: throw new RuntimeException("Unexpected mode '" . $this->mode . "'."); // @codeCoverageIgnore } } return $type; } /** @var array<string, (object|null)> */ private $methodAnnotationCache = []; /** * Returns a method annotation and handles correctly errors. */ private function getMethodAnnotation(ReflectionMethod $refMethod, string $annotationClass): ?object { $cacheKey = $refMethod->getDeclaringClass()->getName() . '::' . $refMethod->getName() . '_' . $annotationClass; if (array_key_exists($cacheKey, $this->methodAnnotationCache)) { return $this->methodAnnotationCache[$cacheKey]; } try { return $this->methodAnnotationCache[$cacheKey] = $this->reader->getMethodAnnotation($refMethod, $annotationClass); } catch (AnnotationException $e) { switch ($this->mode) { case self::STRICT_MODE: throw $e; case self::LAX_MODE: if ($this->isErrorImportant($annotationClass, $refMethod->getDocComment() ?: '', $refMethod->getDeclaringClass()->getName())) { throw $e; } else { return null; } default: throw new RuntimeException("Unexpected mode '" . $this->mode . "'."); // @codeCoverageIgnore } } } /** * Returns true if the annotation class name is part of the docblock comment. */ private function isErrorImportant(string $annotationClass, string $docComment, string $className): bool { foreach ($this->strictNamespaces as $strictNamespace) { if (strpos($className, $strictNamespace) === 0) { return true; } } $shortAnnotationClass = substr($annotationClass, strrpos($annotationClass, '\\') + 1); return strpos($docComment, '@' . $shortAnnotationClass) !== false; } /** * Returns the class annotations. Finds in the parents too. * * @param ReflectionClass<T> $refClass * @param class-string<A> $annotationClass * * @return A[] * * @throws AnnotationException * * @template T of object * @template A of object */ public function getClassAnnotations(ReflectionClass $refClass, string $annotationClass): array { $toAddAnnotations = []; do { try { $allAnnotations = $this->reader->getClassAnnotations($refClass); $toAddAnnotations[] = array_filter($allAnnotations, static function ($annotation) use ($annotationClass): bool { return $annotation instanceof $annotationClass; }); } catch (AnnotationException $e) { if ($this->mode === self::STRICT_MODE) { throw $e; } if ($this->mode === self::LAX_MODE) { if ($this->isErrorImportant($annotationClass, $refClass->getDocComment() ?: '', $refClass->getName())) { throw $e; } } } $refClass = $refClass->getParentClass(); } while ($refClass); if (! empty($toAddAnnotations)) { return array_merge(...$toAddAnnotations); } return []; } /** @var array<string, array<object>> */ private $methodAnnotationsCache = []; /** * Returns the method's annotations. * * @param class-string<T> $annotationClass * * @return array<int, T> * * @throws AnnotationException * * @template T of object */ public function getMethodAnnotations(ReflectionMethod $refMethod, string $annotationClass): array { $cacheKey = $refMethod->getDeclaringClass()->getName() . '::' . $refMethod->getName() . '_s_' . $annotationClass; if (isset($this->methodAnnotationsCache[$cacheKey])) { return $this->methodAnnotationsCache[$cacheKey]; } $toAddAnnotations = []; try { $allAnnotations = $this->reader->getMethodAnnotations($refMethod); $toAddAnnotations = array_filter($allAnnotations, static function ($annotation) use ($annotationClass): bool { return $annotation instanceof $annotationClass; }); } catch (AnnotationException $e) { if ($this->mode === self::STRICT_MODE) { throw $e; } if ($this->mode === self::LAX_MODE) { if ($this->isErrorImportant($annotationClass, $refMethod->getDocComment() ?: '', $refMethod->getDeclaringClass()->getName())) { throw $e; } } } $this->methodAnnotationsCache[$cacheKey] = $toAddAnnotations; return $toAddAnnotations; } } <file_sep>/src/Parameters/InjectUserParameter.php <?php declare(strict_types=1); namespace TheCodingMachine\GraphQLite\Parameters; use GraphQL\Type\Definition\ResolveInfo; use TheCodingMachine\GraphQLite\Security\AuthenticationServiceInterface; /** * A parameter filled from the current user. */ class InjectUserParameter implements ParameterInterface { /** @var AuthenticationServiceInterface */ private $authenticationService; public function __construct(AuthenticationServiceInterface $authenticationService) { $this->authenticationService = $authenticationService; } /** * @param array<string, mixed> $args * @param mixed $context * * @return mixed */ public function resolve(?object $source, array $args, $context, ResolveInfo $info) { return $this->authenticationService->getUser(); } } <file_sep>/src/Middlewares/ResolverInterface.php <?php declare(strict_types=1); namespace TheCodingMachine\GraphQLite\Middlewares; /** * A class that represents a callable on an object. * * @internal */ interface ResolverInterface { public function getObject(): object; public function toString(): string; /** * @param mixed $args * * @return mixed */ public function __invoke(...$args); } <file_sep>/tests/Mappers/Root/BaseTypeMapperTest.php <?php namespace TheCodingMachine\GraphQLite\Mappers\Root; use phpDocumentor\Reflection\DocBlock; use phpDocumentor\Reflection\Fqsen; use phpDocumentor\Reflection\Types\Array_; use phpDocumentor\Reflection\Types\Nullable; use phpDocumentor\Reflection\Types\Object_; use phpDocumentor\Reflection\Types\Resource_; use ReflectionMethod; use TheCodingMachine\GraphQLite\AbstractQueryProviderTest; use TheCodingMachine\GraphQLite\GraphQLRuntimeException; use TheCodingMachine\GraphQLite\Mappers\CannotMapTypeException; class BaseTypeMapperTest extends AbstractQueryProviderTest { public function testNullableToGraphQLInputType(): void { $baseTypeMapper = new BaseTypeMapper(new FinalRootTypeMapper($this->getTypeMapper()), $this->getTypeMapper(), $this->getRootTypeMapper()); $this->expectException(CannotMapTypeException::class); $this->expectExceptionMessage("don't know how to handle type ?\Exception"); $baseTypeMapper->toGraphQLInputType(new Nullable(new Object_(new Fqsen('\\Exception'))), null, 'foo', new ReflectionMethod(BaseTypeMapper::class, '__construct'), new DocBlock()); } public function testToGraphQLOutputTypeException(): void { $baseTypeMapper = new BaseTypeMapper(new FinalRootTypeMapper($this->getTypeMapper()), $this->getTypeMapper(), $this->getRootTypeMapper()); $this->expectException(CannotMapTypeException::class); $this->expectExceptionMessage("type-hinting against DateTime is not allowed. Please use the DateTimeImmutable type instead."); $baseTypeMapper->toGraphQLInputType(new Object_(new Fqsen('\\DateTime')), null, 'foo', new ReflectionMethod(BaseTypeMapper::class, '__construct'), new DocBlock()); } public function testUnmappableOutputArray(): void { $baseTypeMapper = new BaseTypeMapper(new FinalRootTypeMapper($this->getTypeMapper()), $this->getTypeMapper(), $this->getRootTypeMapper()); $this->expectException(CannotMapTypeException::class); $this->expectExceptionMessage("don't know how to handle type resource"); $mappedType = $baseTypeMapper->toGraphQLOutputType(new Array_(new Resource_()), null, new ReflectionMethod(BaseTypeMapper::class, '__construct'), new DocBlock()); } public function testUnmappableInputArray(): void { $baseTypeMapper = new BaseTypeMapper(new FinalRootTypeMapper($this->getTypeMapper()), $this->getTypeMapper(), $this->getRootTypeMapper()); $this->expectException(CannotMapTypeException::class); $this->expectExceptionMessage("don't know how to handle type resource"); $mappedType = $baseTypeMapper->toGraphQLInputType(new Array_(new Resource_()), null, 'foo', new ReflectionMethod(BaseTypeMapper::class, '__construct'), new DocBlock()); } } <file_sep>/tests/Mappers/Parameters/HardCodedParameter.php <?php namespace TheCodingMachine\GraphQLite\Mappers\Parameters; use GraphQL\Type\Definition\ResolveInfo; use TheCodingMachine\GraphQLite\Parameters\ParameterInterface; class HardCodedParameter implements ParameterInterface { private $value; /** * @param mixed $value */ public function __construct($value) { $this->value = $value; } public function resolve(?object $source, array $args, $context, ResolveInfo $info) { return $this->value; } }<file_sep>/src/Middlewares/MagicPropertyResolver.php <?php declare(strict_types=1); namespace TheCodingMachine\GraphQLite\Middlewares; use TheCodingMachine\GraphQLite\GraphQLRuntimeException; use Webmozart\Assert\Assert; use function get_class; use function is_object; use function method_exists; /** * A class that represents a magic property of an object. * The object can be modified after class invocation. * * @internal */ class MagicPropertyResolver implements ResolverInterface { /** @var string */ private $propertyName; /** @var object|null */ private $object; public function __construct(string $propertyName) { $this->propertyName = $propertyName; } public function setObject(object $object): void { $this->object = $object; } public function getObject(): object { Assert::notNull($this->object); return $this->object; } /** * @param mixed $args * * @return mixed */ public function __invoke(...$args) { if ($this->object === null) { throw new GraphQLRuntimeException('You must call "setObject" on MagicPropertyResolver before invoking the object.'); } if (! method_exists($this->object, '__get')) { throw MissingMagicGetException::cannotFindMagicGet(get_class($this->object)); } return $this->object->__get($this->propertyName); } public function toString(): string { $class = $this->getObject(); if (is_object($class)) { $class = get_class($class); } return $class . '::__get(\'' . $this->propertyName . '\')'; } } <file_sep>/tests/Fixtures/Integration/Controllers/ProductController.php <?php namespace TheCodingMachine\GraphQLite\Fixtures\Integration\Controllers; use ArrayIterator; use DateTimeImmutable; use Porpaginas\Arrays\ArrayResult; use TheCodingMachine\GraphQLite\Annotations\Query; use TheCodingMachine\GraphQLite\Fixtures\Integration\Models\Contact; use TheCodingMachine\GraphQLite\Fixtures\Integration\Models\Product; use TheCodingMachine\GraphQLite\Fixtures\Integration\Models\ProductTypeEnum; use TheCodingMachine\GraphQLite\Fixtures\Integration\Models\SpecialProduct; class ProductController { /** * @Query() * @return Product[] */ public function getProducts(): ArrayResult { return new ArrayResult([ new Product('Foo', 42.0, ProductTypeEnum::NON_FOOD()), ]); } /** * This is supposed to return an array of products... but it returns an array of array of Products. * Useful to test error messages. * * @Query() * @return Product[] */ public function getProductsBadType(): array { return [ [ new Product('Foo', 42.0, ProductTypeEnum::NON_FOOD()), new Product('Foo', 42.0, ProductTypeEnum::NON_FOOD()), ], ]; } /** * @Query() */ public function echoProductType(ProductTypeEnum $productType): ProductTypeEnum { return $productType; } /** * @Query() */ public function echoDate(DateTimeImmutable $date): DateTimeImmutable { return $date; } /** * @Query(name="getProduct") * @return \TheCodingMachine\GraphQLite\Fixtures\Integration\Models\Product|\TheCodingMachine\GraphQLite\Fixtures\Integration\Models\SpecialProduct */ public function getProduct() { return new SpecialProduct('Special box', 10.99); } /** * @Query(name="getProducts2") * @return (\TheCodingMachine\GraphQLite\Fixtures\Integration\Models\Product|\TheCodingMachine\GraphQLite\Fixtures\Integration\Models\SpecialProduct)[] */ public function getProducts2(): ArrayIterator { return new ArrayIterator([new SpecialProduct('Special box', 10.99), new SpecialProduct('Special box', 10.99)]); } } <file_sep>/tests/Mappers/Root/NullableTypeMapperAdapterTest.php <?php namespace TheCodingMachine\GraphQLite\Mappers\Root; use GraphQL\Type\Definition\NonNull; use phpDocumentor\Reflection\DocBlock; use ReflectionMethod; use TheCodingMachine\GraphQLite\AbstractQueryProviderTest; use TheCodingMachine\GraphQLite\Fixtures\TestObject; use TheCodingMachine\GraphQLite\Fixtures\TestObject2; use TheCodingMachine\GraphQLite\Mappers\CannotMapTypeException; class NullableTypeMapperAdapterTest extends AbstractQueryProviderTest { public function testMultipleCompound(): void { $compoundTypeMapper = $this->getRootTypeMapper(); $result = $compoundTypeMapper->toGraphQLOutputType($this->resolveType(TestObject::class.'|'.TestObject2::class.'|null'), null, new ReflectionMethod(__CLASS__, 'testMultipleCompound'), new DocBlock()); $this->assertNotInstanceOf(NonNull::class, $result); } public function testOnlyNull(): void { $compoundTypeMapper = $this->getRootTypeMapper(); $this->expectException(CannotMapTypeException::class); $this->expectExceptionMessage('type-hinting against null only in the PHPDoc is not allowed.'); $compoundTypeMapper->toGraphQLOutputType($this->resolveType('null'), null, new ReflectionMethod(__CLASS__, 'testMultipleCompound'), new DocBlock()); } public function testOnlyNull2(): void { $compoundTypeMapper = $this->getRootTypeMapper(); $this->expectException(CannotMapTypeException::class); $this->expectExceptionMessage('type-hinting against null only in the PHPDoc is not allowed.'); $compoundTypeMapper->toGraphQLInputType($this->resolveType('null'), null, 'foo', new ReflectionMethod(__CLASS__, 'testMultipleCompound'), new DocBlock()); } }
5b8880fc806b79c1173a7b819daa894416373cdd
[ "PHP" ]
8
PHP
marhub/graphqlite
4fe8fcbfa07340803b0cb252872ad99de44413fc
eedd5a2abc39789831edb58c7acddc81e59e7d32
refs/heads/master
<repo_name>miguelmoreno/experiments-SingleArmClockHTML5<file_sep>/scripts/clock.js var stageWidth = 420; var stageHeight = 320; var stage; var layer = new Kinetic.Layer(); var mainImage = new Image(); var hourImage = new Image(); var minuteImage = new Image(); var secondImage = new Image(); var timeText; var minuteRadial; var isToggle = true; var hourGroup = new Kinetic.Group({ x: (stageWidth / 2), y: (stageHeight / 2) }); var minuteGroup = new Kinetic.Group({ x: 0, y: -50 }); var secondGroup = new Kinetic.Group({ x: 0, y: -67 }); var hourShadow; var minuteShadow; var secondShadow; var clockAnimation = new Kinetic.Animation(function (frame) { var date = new Date(); var hours = date.getHours(); var minutes = date.getMinutes(); var seconds = date.getSeconds(); var milliseconds = date.getMilliseconds(); var hourFull = hours * 30.00; var hourFraction = minutes * 0.50; var hourAngle = hourFull + hourFraction; var hourAdjust = (isToggle)? angleAdjust(hourAngle, hourGroup.getRotationDeg()):0.5; hourGroup.rotateDeg(hourAdjust); hourShadow.rotateDeg(hourAdjust); var minuteFull = (minutes * 6.00); var minuteFraction = (seconds * 0.10); var minuteAngle = minuteFull + minuteFraction - hourAngle; var minuteAdjust = (isToggle)? angleAdjust(minuteAngle, minuteGroup.getRotationDeg()):3; minuteGroup.rotateDeg(minuteAdjust); minuteShadow.rotateDeg(hourAdjust + minuteAdjust); var secondFull = seconds * 6.00; var secondFraction = (milliseconds / 1000.00) * 6.00; var secondAngle = (secondFull + secondFraction) - minuteAngle - hourAngle; var secondAdjust = (isToggle)? angleAdjust(secondAngle, secondGroup.getRotationDeg()):6; secondGroup.rotateDeg(secondAdjust); secondShadow.rotateDeg(hourAdjust + minuteAdjust + secondAdjust); timeText.setText("Current time: " + ((hours < 10) ? "0" + hours : hours) + ":" + ((minutes < 10) ? "0" + minutes : minutes) + ":" + ((seconds < 10) ? "0" + seconds : seconds) + ":" + milliseconds); }, layer); function toggle() { isToggle = !isToggle; } function angleAdjust(desired, current) { return (current < desired) ? desired - current : 360 - (current - desired); } function init() { stage = new Kinetic.Stage({ container: 'experimentcontainer', width: stageWidth, height: stageHeight }); timeText = new Kinetic.Text({ x: 15, y: 15, text: "0", fontSize: 12, fill: 'black' }); layer.add(timeText); mainImage.onload = function () { var hourRadial = renderRadial( this, (stageWidth / 2) - (this.width / 2), (stageHeight / 2) - (this.height / 2), [0, 0]); layer.add(hourRadial); // Hour arm ---------------------------- // var hourArm = renderClockArm( [ (stageWidth / 2), (stageHeight / 2), (stageWidth / 2), (stageHeight / 2) - (this.height / 4) ], 'red', 8, 0, 0, [(stageWidth / 2), (stageHeight / 2)], 1); hourGroup.add(hourArm); layer.add(hourGroup); // Hour shadow -------------------------- // hourShadow = renderClockArm( [0, -8, 0, 0], 'red', 5, (stageWidth / 2), (stageHeight / 2), [0, 95], 0.4); layer.add(hourShadow); // Minutes arm ------------------------- // var minuteRadial = new Kinetic.Circle({ x: 0, y: -50, radius: 75, stroke: 'black', strokeWidth: 1, opacity: 0.2 }); hourGroup.add(minuteRadial); var minuteArm = renderClockArm( [0, 0, 0, 0 - this.height / 3], 'blue', 6, 0, 0, [0, 0], 1); minuteGroup.add(minuteArm); hourGroup.add(minuteGroup); // Minute shadow -------------------------- // minuteShadow = renderClockArm( [0, -8, 0, 0], 'blue', 5, (stageWidth / 2), (stageHeight / 2), [0, 95], 0.4); layer.add(minuteShadow); // Seconds arm -------------------------- // var secondRadial = new Kinetic.Circle({ x: 0, y: -67.6, radius: 50, stroke: 'black', strokeWidth: 1, opacity: 0.2 }); minuteGroup.add(secondRadial); var secondArm = renderClockArm( [0, 0, 0, 0 - this.height / 5], 'green',4 , 0, 0, [0, 0], 1); secondGroup.add(secondArm); minuteGroup.add(secondGroup); // Second shadow -------------------------- // secondShadow = renderClockArm( [0, -8, 0, 0], 'green', 5, (stageWidth / 2), (stageHeight / 2), [0, 95], 0.4); layer.add(secondShadow); stage.add(layer); clockAnimation.start(); }; mainImage.src = "images/Clock_Face_Main.png"; } function renderRadial(img, x, y, offset) { return new Kinetic.Image({ x: x, y: y, image: img, offset: offset }); } function renderClockArm(points, stroke, strokeWidth, x, y, offset, opacity) { return new Kinetic.Line({ points: points, stroke: stroke, strokeWidth: strokeWidth, lineCap: 'round', lineJoin: 'round', x: x, y: y, offset: offset, opacity: opacity }); } jQuery(function ($) { init(); });<file_sep>/README.md # experiments-SingleArmClockHTML5 Single Arm Clock in HTML 5 ### Description The [Continue Time clock](http://www.sandermulder.com/continue_time.html) is an modern, one-of-a-kind, physical wall clock by artist <NAME>. This experiment tries to emulate the functionality of this peculiar clock. I decided to use the KineticJS framework, since it handles a lot of the manual work to working with Canvas objects. ### Demo: See it in action here: [Single Arm Clock HTML 5](https://www.miguelmoreno.net/experiment-now-in-html-5-single-arm-clock/) ### Usage: Clone and run **index.html** ![Clock with hour, minute and second arm in one](http://i.imgur.com/doEyjP4.png)
5866739652be060b473d248aec0590f4c69a1228
[ "JavaScript", "Markdown" ]
2
JavaScript
miguelmoreno/experiments-SingleArmClockHTML5
6ea8bca63eb2b8b168a010905c415f924ac56f0e
cf7eb22e1a1cf04e2edc08c177fd46c629e00ff7
refs/heads/master
<file_sep>import java.util.Scanner; public class MainATM { public static void main(String[] args) { Scanner input = new Scanner(System.in); double amount, balance = -1; String accountName; int choice = -1; long accountNumberSource, accountNumberDestination, accountNumber; while (choice != 0) { System.out.println("Welcome to ATM. Please choose your option:" + "\n1. Create account" + "\n2. Transfer money to another account" + "\n3. Show account info" + "\n0. Exit"); choice = input.nextInt(); if (choice == 1) { input.nextLine(); System.out.print("Enter account name: "); accountName = input.nextLine(); System.out.print("Enter your balance: "); balance = input.nextDouble(); while (balance < 0) { System.out.print("The balance must be positive!\nEnter your balance: "); balance = input.nextDouble(); } Account account = new Account(accountName, balance); System.out.println( "\nThe account with the account number " + account.getAccountNumber() + " has been created!"); } else if (choice == 2) { if (Account.numberOfAccounts() == 0 || Account.numberOfAccounts() == 1) { System.out.println("\nThere are no active accounts or there is only one account!"); } else { System.out.print("\nEnter the account number for the source account: "); accountNumberSource = input.nextLong(); if (Account.getAccountByAccountNumber(accountNumberSource) == null) System.out.println("\nThat account doesn't exist!"); else { System.out.print("Enter the account number for the destination account: "); accountNumberDestination = input.nextLong(); if (Account.getAccountByAccountNumber(accountNumberDestination) == null) System.out.println("\nThat account doesn't exist!"); else { System.out.print("Enter the amount: "); amount = input.nextDouble(); Transaction.transferMoney(Account.getAccountByAccountNumber(accountNumberSource), Account.getAccountByAccountNumber(accountNumberDestination), amount); System.out.println(); } } } } else if (choice == 3) { if (Account.numberOfAccounts() == 0) System.out.println("\nThere are no active accounts!"); else { System.out.print("Enter account number: "); accountNumber = input.nextLong(); if (Account.getAccountByAccountNumber(accountNumber) != null) Account.getAccountByAccountNumber(accountNumber).showAccountInfo(); else System.out.println("\nThat account doesn't exist!"); } } } input.close(); System.out.println("\nThank you for using Deez Atm!"); } } <file_sep>import java.util.ArrayList; public class Account extends CreateAccount { protected static ArrayList<Account> accounts = new ArrayList<Account>(); protected Account() { } Account(String accountName, double balance) { super(accountName, balance); accounts.add(this); } public void showAccountInfo() { System.out.println("Account number: " + this.getAccountNumber() + "\nAccount name: " + this.getAccountName() + "\nBalance: " + this.getBalance() + "$"); } public static Account getAccountByAccountNumber(long accountNumber) { if (accounts.size() == 0) { System.out.println("There are no created accounts!"); } else { for (Account acc : accounts) { if (acc.getAccountNumber() == accountNumber) return acc; } } return null; } public static int numberOfAccounts() { return accounts.size(); } }
6804b6fa8a4d9feb028413bceac8c5b8c34293de
[ "Java" ]
2
Java
esmajic/ATMzero
fa97190ef544ef282ab81509b843780a631b4e48
01fdccbfbf25d6547237c7583e3a88cea46de32a
refs/heads/master
<file_sep>import React, { Component } from 'react'; import Inicio from './Home/Inicio' import ListaCategorias from './Categorias/Lista-Categorias' import ListaPerguntas from './Perguntas/Lista-Perguntas' import Resultado from './Resultados/Resultado' import {BrowserRouter,Route} from 'react-router-dom' import './App.css' class App extends Component { render() { return ( <BrowserRouter> <div className="App_Root"> <h1 className='App_title'> Jogo de perguntas e respostas </h1> <Route path='/' exact component={Inicio} /> <Route path='/categorias' component={ListaCategorias} /> <Route path='/perguntas/:cat_id' component={ListaPerguntas} /> <Route path='/resultado' component={Resultado} /> </div> </BrowserRouter> ); } } export default App; <file_sep>import React,{Component} from 'react' import {Link} from 'react-router-dom' import {Menu, Image, Dropdown} from 'semantic-ui-react' import {auth} from '../config' const CHAVE_STORAGE_NOME = 'Quiz_user_name'; const CHAVE_STORAGE_FOTO = 'Quiz_user_photo'; export default class Header extends Component{ tamanho = { width: 48, heigth: 48 } user = { name: localStorage.getItem(CHAVE_STORAGE_NOME), // auth.currentUser().displayName image: localStorage.getItem(CHAVE_STORAGE_FOTO) // auth.currentUser().photoURL } LogOff(){ auth.signOut() .then( () => { localStorage.removeItem(CHAVE_STORAGE_NOME); localStorage.removeItem(CHAVE_STORAGE_FOTO) console.log('LogOff realizado com sucesso.') } ) .catch(err => { console.log('Erro em LogOff..!') }) } render(){ this.items = []; if(this.props.home) this.items.push(<Menu.Item as={Link} to='/'>Home</Menu.Item>); if(this.props.categoria) this.items.push(<Menu.Item as={Link} to='/categorias'>Categorias</Menu.Item>); return( <Menu> <Menu.Item><Image src='/img/Logo.png' style={this.tamanho} /></Menu.Item> {this.items.map(item => item)} <Menu.Menu position='right'> <Menu.Item> <Image avatar src={this.user.image} /> </Menu.Item> <Dropdown text={this.user.name}> <Dropdown.Menu> <Dropdown.Item onClick={this.LogOff}>Sair</Dropdown.Item> </Dropdown.Menu> </Dropdown> </Menu.Menu> </Menu> ); } } <file_sep>import React,{Component} from 'react' import {List} from 'semantic-ui-react' import Resposta from './Resposta' import Cabecalho from '../Home/Cabecalho' export default class Resultado extends Component{ constructor(props){ super(props) this.state={ lista: [] } } render(){ return ( <div> <Cabecalho home={true} categoria={true} perguntas={true} // resultado={true} /> <h2>Seus resultados</h2> <p>Confira seu desempenho nessa categoria</p> <List celled> {this.props.location.state.lista.map( item => <Resposta titulo={item.titulo} isCorrect={item.isCorrect} alternativa={item.alternativa} /> )} <h3>Total: {this.props.location.state.pontos} ponto(s)</h3> </List> </div> ) } }<file_sep>from datetime import date,datetime class Validacao: def Nome_OK(self): if self.valor == "": self.msg_erro = "Campo vazio não permitido." return False else: self.msg_erro = "" return True def Idade_OK(self): try: born = datetime.strptime( self.valor, '%d/%m/%Y' ).date() except: self.msg_erro = "Formato incorreto - Esperado: dd/mm/yyyy" return False today = datetime.today() idade = today.year - born.year - ((today.month, today.day) < (born.month, born.day)) if (idade in range(18,70)): self.msg_erro = "" return True else: self.msg_erro = "Idade fora da faixa (18-70)" return False def CPF_OK(self): value = self.valor #### # Validação de CPF # By <NAME> <<EMAIL>> #### if len(set(list(value))) == 1: self.msg_erro = "Digitos duplicados." return False def calcdv(numb): result = int() lista = [i for i in range(9, -1, -1)] seq = reversed(((lista*2)[:len(numb)])) for digit, base in zip(numb, seq): result += int(digit)*int(base) dv = result % 11 return (dv < 10) and dv or 0 numb, xdv = value[:-2], value[-2:] dv1 = calcdv(numb) dv2 = calcdv(numb + str(dv1)) ok = ('%d%d' % (dv1, dv2) == xdv and True or False) if ok: self.msg_erro = "" return True else: self.msg_erro = "Digito invalido." return False def Sexo_OK(self): if (self.valor.upper() in ['F','M']): self.msg_erro = "" return True else: self.msg_erro = "Permitido somente M ou F." return False def __init__(self,campo,obj): func = { 'data_nascimento': Validacao.Idade_OK, 'CPF': Validacao.CPF_OK, 'nome': Validacao.Nome_OK, 'sexo': Validacao.Sexo_OK } if campo in func: if not campo in obj: self.msg_erro = "Campo obrigatorio" self.correta = False else: self.valor = obj[campo] self.correta = func[campo](self) else: self.correta = True # Exemplo : V = Validacao('idade',13) // V.correta = False <file_sep>import firebase from 'firebase' import Rebase from 're-base' export const DATABASE_URL = "https://curso-de-react-julio-cascalles.firebaseio.com" const firebaseInfo = firebase.initializeApp({ apiKey: "<KEY>", authDomain: "curso-de-react-julio-cascalles.firebaseapp.com", databaseURL: DATABASE_URL, projectId: "curso-de-react-julio-cascalles", storageBucket: "curso-de-react-julio-cascalles.appspot.com", messagingSenderId: "1046541855135" }); const db = firebase.database(firebaseInfo); const config = Rebase.createClass(db); export const facebook = new firebase.auth.FacebookAuthProvider(); export const github = new firebase.auth.GithubAuthProvider(); export const auth = firebase.auth(); export default config;<file_sep>import React, {Component} from 'react' import { Grid, Radio, Message } from 'semantic-ui-react' export default class Alternativa extends Component { constructor(props){ super(props) this.state = { owner: null } } getChecked(){ if(this.state.owner == this.props.owner){ return true }else{ return false } } render(){ return( <Grid.Column> <Message> <Radio label={this.props.resposta} checked={this.getChecked()} onChange={() => this.props.evento(this)} /> </Message> </Grid.Column> ) } //--------------------------- }<file_sep>from app import db import boto3 from boto3.dynamodb.conditions import Key, Attr from app.controllers.Validacao import Validacao class ClienteModel: COLLECTION_NAME = 'cliente_tb' table = db.Table(COLLECTION_NAME) def __init__(self): self.dados = {} self.erros = [] def validaDados(self): required = ['nome','CPF','sexo','data_nascimento'] for key in required: V = Validacao(key,self.dados) if not V.correta: self.erros.append({ key : V.msg_erro }) return (len(self.erros) == 0) def Consulta(self,cpf): if self.Existe(cpf): self.dados['code'] = 200 return self.dados else: return { "status": 'Não encontrado', "code": 404 } def Existe(self,cpf): response = self.table.query( KeyConditionExpression=Key('id') .eq(cpf) ) if response['Count'] > 0: self.dados = response['Items'][0] return True else: return False def Grava(self,request): self.dados = request['cliente'] if not self.validaDados(): return { "status": 'erro', "erros": self.erros, "code": 400 } elif self.Existe(self.dados['CPF']): return { "status": 'Já existe', "dados": self.dados, "code": 405 } else: try: self.table.put_item(Item={ 'id' : self.dados['CPF'], 'CPF' : self.dados['CPF'], 'nome' : self.dados['nome'], 'sexo' : self.dados['sexo'], 'data_nascimento' : self.dados['data_nascimento'] }) return { "status": 'sucesso', "code": 201 } except: return{ "status": 'Falha ao gravar', "code": 500 } <file_sep>import React, {Component} from 'react' import {Grid,Divider} from 'semantic-ui-react' import Alternativa from './Alternativa' export default class Pergunta extends Component{ constructor(props){ super(props) this.state = { alternativaSelecionada: null } this.setAlternativa = this.setAlternativa.bind(this) } setAlternativa(sender){ let last = this.state.alternativaSelecionada if(last){ last.setState({ owner : null }) } this.setState({ alternativaSelecionada: sender }); if(sender) sender.setState({ owner: this.props.titulo }) this.props.onUpdate(sender) } render(){ return ( <div> <Divider /> <p> <h3>{this.props.titulo}</h3> </p> <Grid columns={2}> {this.props.alternativas.map( sub => <Alternativa resposta={sub.resposta} correta={sub.correta} owner={this.props.titulo} evento={this.setAlternativa} /> )} </Grid> </div> ) } //----------------------------- }<file_sep>import React,{Component} from 'react' import Categoria from './Categoria' import {Grid} from 'semantic-ui-react' import Cabecalho from '../Home/Cabecalho' import config from '../config' class ListaCategorias extends Component{ constructor(props){ super(props) this.state={ lista: [] } config.syncState( 'categorias',{ context: this, state: 'lista', asArray: true } ) } render(){ return( <div> <Cabecalho home={true} // categoria={true} perguntas={true} // resultado={true} /> <h2>Lista de Categorias</h2> <p>Selecione a categoria que você quer responder perguntas:</p> <Grid columns={5} divided> { this.state.lista.map( item => <Categoria nome={item.nome} icone={item.icone} id={item.key} /> ) } </Grid> </div> ) } } export default ListaCategorias;<file_sep>import json from app import app from app.models.tables import ClienteModel from flask import jsonify, request @app.route("/consulta_cpf/<id>") def consulta_cpf(id): model = ClienteModel() return jsonify( model.Consulta(id) ) @app.route("/novo_cliente", methods=['post']) def novo_cliente(): model = ClienteModel() return jsonify( model.Grava(json.loads(request.data)) ) <file_sep>import React,{Component} from 'react'; import { Container, Card, Button } from 'semantic-ui-react' import Cabecalho from './Cabecalho' import {auth,facebook,github} from '../config' import {Redirect} from 'react-router-dom' class Inicio extends Component{ constructor(props){ super(props) this.state = this.getUser(null) auth.onAuthStateChanged( (user) => { this.setState( this.getUser(user) ) } ) } getUser(user){ let obj = { name: '', image: '', isLogged: false } if(user){ obj.name = user.displayName; obj.image = user.photoURL localStorage.setItem( 'Quiz_user_name' ,user.displayName) localStorage.setItem( 'Quiz_user_photo' ,user.photoURL) obj.isLogged = true } return obj } FacebookLogin(){ auth.signInWithPopup(facebook) } GithubLogin(){ auth.signInWithPopup(github) } render(){ if(this.state.isLogged){ return <Redirect to='/categorias' /> } return ( <div> <Cabecalho // home={true} // categoria={true} // perguntas={true} // resultado={true} /> <Container> <Card> <Card.Header as="h2"> Quiz </Card.Header> <Card.Meta> Jogo de perguntas e respostas </Card.Meta> <Card.Content> Desafie seus amigos para este jogo. </Card.Content> <Card.Content> <Button color='blue' onClick={this.FacebookLogin} > Login com Facebook </Button> <Button color='green' onClick={this.GithubLogin}> Login com GitHub </Button> </Card.Content> </Card> </Container> </div> ) } } export default Inicio;
0a30c775277cc7a81260da32d492c828eb7eb1ca
[ "JavaScript", "Python" ]
11
JavaScript
jcezarc/cursoReact
6cad411801a8e65cc672a5f3325bae51d96732de
bd9b86c7cca7b252e96cbdffafa66cd56b135720
refs/heads/main
<file_sep>import requests import json from bs4 import BeautifulSoup def get_recipe(url): client = requests.session() client.headers.update({ 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36', }) r = client.get(url) soup = BeautifulSoup(r.text, 'html.parser') all_data = json.loads(soup.find('script', {'id': '__NEXT_DATA__'}).contents[0]) recipeSchema = all_data['props']['pageProps']['recipeSchema'] ingred_info = all_data['props']['pageProps']['ingredients'][0]['ingredients'] res = {} res['name'] = recipeSchema['name'] assert len(recipeSchema['recipeIngredient']) == len(ingred_info) ingred_list = [] for ingredientText, info in zip(recipeSchema['recipeIngredient'], ingred_info): ingred_list.append({ 'ingredientText': ingredientText, 'quantityText': info.get('quantityText', None), 'term': info['term']['display'], }) res['ingredients'] = ingred_list instructions = [] for instr in recipeSchema['recipeInstructions']: temp_soup = BeautifulSoup(instr['text'], 'html.parser') instructions.append(temp_soup.get_text()) res['instructions'] = instructions return res url = input() recipe = get_recipe(url) print(json.dumps(recipe, indent=4))
c8333f55e0b89caa8e06de9a5f25882cec68b607
[ "Python" ]
1
Python
pingpong17/Recipes
3d25a7bcdaa3e021ddc883987a98e96fc7f8790b
6c51b5d74d53a72ce84e05fedaded17827f24a25
refs/heads/master
<file_sep>#! /bin/sh set -e WEAVE_VERSION=${WEAVE_VERSION:-latest} IMAGE_VERSION=${IMAGE_VERSION:-$WEAVE_VERSION} if ! grep -q "FROM.*$WEAVE_VERSION" image/Dockerfile ; then echo "WEAVE_VERSION does not match image/Dockerfile" exit 1 fi # Build helper program go build -i -o image/kube-peers -ldflags "-linkmode external -extldflags -static" ./kube-peers # Extract other files we need NAME=weave-kube-$$ $SUDO docker create --name=$NAME weaveworks/weave:$WEAVE_VERSION $SUDO docker cp $NAME:/home/weave/weaver image $SUDO docker cp $NAME:/weavedb/weavedata.db image $SUDO docker cp $NAME:/etc/ssl/certs/ca-certificates.crt image $SUDO docker rm $NAME # Build the end product $SUDO docker build -t weaveworks/weave-kube:$IMAGE_VERSION image
51c5d4b82482954c82d582c539232a599b1083ca
[ "Shell" ]
1
Shell
bboreham/weave-kube
3c13f502361ce4d01174e52e950057386dc5fe4b
f716163a155cba9edeac50289f1c69a8124affd8
refs/heads/master
<repo_name>PerseveranceGroup/jeep<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/cppcc/mapper/ComDataMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.cppcc.mapper; import com.jeeplus.modules.test.cppcc.entity.ComData; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 政协通讯MAPPER接口 * @author lc * @version 2021-03-15 */ @Mapper @Repository public interface ComDataMapper extends BaseMapper<ComData> { }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/tree/entity/TestTree.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.tree.entity; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonBackReference; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.jeeplus.core.persistence.TreeEntity; import lombok.Data; /** * 组织机构Entity * @author lgf * @version 2021-01-05 */ @Data @JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"}) public class TestTree extends TreeEntity<TestTree> { private static final long serialVersionUID = 1L; public TestTree() { super(); } public TestTree(String id){ super(id); } public TestTree getParent() { return parent; } @Override public void setParent(TestTree parent) { this.parent = parent; } public String getParentId() { return parent != null && parent.getId() != null ? parent.getId() : "0"; } }<file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/resources/datasource-plugin.properties ds.plugin.name = 数据管理 ds.plugin.description = 数据管理插件是一款多数据源插件,<br/>可以为不同的模块指定连接不同的数据库,<br/>也可以通过动态sql查询不同的数据库。 ds.plugin.version = v1.0 ds.plugin.icon = fa fa-database ds.plugin.site = http://www.jeeplus.org <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/interceptor/FlowableHandlerInterceptor.java package com.jeeplus.modules.flowable.interceptor; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.modules.sys.utils.UserUtils; import org.flowable.idm.api.User; import org.flowable.idm.engine.impl.persistence.entity.UserEntityImpl; import org.flowable.ui.common.security.SecurityUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 请求拦截器,Flowable动态设置用户信息 * @author liugaofeng * @version 2018-8-19 * 需要增加拦截器,动态设置Flowable用户信息 * */ public class FlowableHandlerInterceptor implements HandlerInterceptor { public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String servletPath = request.getServletPath(); com.jeeplus.modules.sys.entity.User u = UserUtils.getUser(); if (servletPath.startsWith("/app") || servletPath.startsWith("/idm")) { User currentUserObject = SecurityUtils.getCurrentUserObject(); if (currentUserObject == null || StringUtils.isBlank (currentUserObject.getId ())) { User user = new UserEntityImpl(); user.setId(u.getId()); user.setFirstName(u.getName()); user.setLastName(""); user.setEmail(u.getEmail()); SecurityUtils.assumeUser(user); } } return true; } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/comm/service/ComFilesService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.comm.service; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.test.comm.entity.ComFiles; import com.jeeplus.modules.test.comm.mapper.ComFilesMapper; import static com.jeeplus.modules.test.comm.config.FilesType.NEWS_FILE; /** * 公共Service * @author lh * @version 2021-03-12 */ @Service @Transactional(readOnly = true) public class ComFilesService extends CrudService<ComFilesMapper, ComFiles> { public ComFiles get(String id) { return super.get(id); } public List<ComFiles> findList(ComFiles comFiles) { return super.findList(comFiles); } public Page<ComFiles> findPage(Page<ComFiles> page, ComFiles comFiles) { return super.findPage(page, comFiles); } @Transactional(readOnly = false) public void save(ComFiles comFiles) { super.save(comFiles); } @Transactional(readOnly = false) public void delete(ComFiles comFiles) { super.delete(comFiles); } public List<ComFiles> findListBySourceAOwnerId(ComFiles comFiles) { return mapper.findListBySourceAOwnerId(comFiles); } public int deleteBySource(ComFiles comFiles){ return mapper.deleteBySource(comFiles); }; @Transactional(readOnly = false) public void save(List<ComFiles> comFilesList,String source,String id) { List<ComFiles> oldList = mapper.findList(new ComFiles(id,source)); if(oldList == null||oldList.size()==0){ for (int i= 0;i<comFilesList.size();i++){ ComFiles sf = comFilesList.get(i); sf.setOwnerId(id); sf.setSource(source); super.save(sf); } }else { Map<String,ComFiles> old = new HashMap<>(); for (ComFiles l:oldList) { old.put(l.getId(),l); } for (ComFiles k:comFilesList) { if(k.getId()!=null && k.getId() != "" ){ if(old.get(k.getId()).getId()!="" && old.get(k.getId()).getId() != null){ old.remove(k.getId()); } }else { k.setOwnerId(id); k.setSource(source); super.save(k); } } for (String key: old.keySet()) { super.delete(old.get(key)); } } } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/cppcc/entity/ComComments.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.cppcc.entity; import javax.validation.constraints.NotNull; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 政协通讯评论详情Entity * @author lc * @version 2021-03-15 */ @Data public class ComComments extends DataEntity<ComComments> { private static final long serialVersionUID = 1L; @NotNull(message="排序不能为空") @ExcelField(title="排序", align=2, sort=1) private Integer sort; // 排序 @ExcelField(title="父节点id", align=2, sort=2) private String parentId; // 父节点id @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @NotNull(message="评论时间不能为空") @ExcelField(title="评论时间", align=2, sort=3) private Date commentTime; // 评论时间 @NotNull(message="评论人不能为空") @ExcelField(title="评论人", fieldType=User.class, value="commentUser.name", align=2, sort=4) private User commentUser; // 评论人 private ComData comData; // 政协通讯管理主表id 父类 public ComComments() { super(); } public ComComments(String id){ super(id); } public ComComments(ComData comData){ this.comData = comData; } }<file_sep>/jeeplus-module/committee/src/main/java/com/jeeplus/modules/committee/listener/PublishNoticeExecutionListener.java package com.jeeplus.modules.committee.listener; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.websocket.service.system.SystemInfoSocketHandler; import com.jeeplus.modules.oa.entity.OaNotify; import com.jeeplus.modules.oa.service.OaNotifyService; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.service.UserService; import com.jeeplus.modules.sys.utils.UserUtils; import org.flowable.engine.delegate.DelegateExecution; import org.flowable.engine.delegate.ExecutionListener; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; @Component public class PublishNoticeExecutionListener implements ExecutionListener { public SystemInfoSocketHandler systemInfoSocketHandler() { return new SystemInfoSocketHandler(); } /** * @desc 是否公开发布消息 * @param delegateExecution * @return void * @author tangxin * @date 2021/3/24 */ public void notify(DelegateExecution delegateExecution) { if("奖励审核".equals(delegateExecution.getCurrentFlowElement().getName()) && "end".equals(delegateExecution.getEventName())){ Map vars = delegateExecution.getVariables(); if(vars.containsKey("open") && "true".equals(vars.get("open"))){ StringBuilder title = new StringBuilder("奖励公告"); StringBuilder detail = new StringBuilder(); detail.append("流程标题:").append(vars.get("title")).append("\n") .append("奖励人员:").append(UserUtils.get(vars.get("reward_man").toString()).getName()).append("\n") .append("奖励原因:").append(vars.get("reason")).append("\n") .append("奖励内容:").append(vars.get("content")).append("\n"); sendOaNotice(title.toString(),detail.toString(),null,"2"); } } if("处罚审核".equals(delegateExecution.getCurrentFlowElement().getName()) && "end".equals(delegateExecution.getEventName())){ Map vars = delegateExecution.getVariables(); if(vars.containsKey("open") && "true".equals(vars.get("open"))){ StringBuilder title = new StringBuilder("处罚公告"); StringBuilder detail = new StringBuilder(); detail.append("流程标题:").append(vars.get("title")).append("\n") .append("处罚人员:").append(UserUtils.get(vars.get("punish_man").toString()).getName()).append("\n") .append("处罚原因:").append(vars.get("reason")).append("\n") .append("处罚内容:").append(vars.get("content")).append("\n"); sendOaNotice(title.toString(),detail.toString(),null,"5"); } } } public void sendOaNotice(String title,String detail,String receiverIds,String type){ List<String> userIds = new ArrayList<>(); if(StringUtils.isEmpty(receiverIds)){ userIds = ((UserService)SpringContextHolder.getBean("userService")) .findAllList(new User()).stream().map(User::getId).collect(Collectors.toList()); receiverIds = String.join(",",userIds); } else { userIds = Arrays.asList(receiverIds.split(",")); } OaNotify oaNotify = new OaNotify(); oaNotify.setType(type); oaNotify.setTitle(title); oaNotify.setContent(detail); oaNotify.setStatus("1"); oaNotify.setOaNotifyRecordIds(receiverIds); ((OaNotifyService)SpringContextHolder.getBean("oaNotifyService")) .save(oaNotify); for(String userId:userIds){ systemInfoSocketHandler().sendMessageToUser(UserUtils.get(userId).getLoginName(), "收到新的公告"); } } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/service/MenuService.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.service; import com.google.common.collect.Lists; import com.jeeplus.common.utils.CacheUtils; import com.jeeplus.core.service.TreeService; import com.jeeplus.modules.sys.entity.DataRule; import com.jeeplus.modules.sys.entity.Menu; import com.jeeplus.modules.sys.mapper.MenuMapper; import com.jeeplus.modules.sys.utils.LogUtils; import com.jeeplus.modules.sys.utils.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; /** * 菜单. * * @author jeeplus * @version 2016-12-05 */ @Service @Transactional(readOnly = true) public class MenuService extends TreeService<MenuMapper, Menu> { @Autowired private DataRuleService dataRuleService; public Menu get(String id) { return super.get(id); } public List<Menu> findAllMenu() { return UserUtils.getMenuList(); } public List<Menu> getChildren(String parentId) { return super.getChildren(parentId); } @Transactional(readOnly = false) public void saveMenu(Menu menu) { // 获取父节点实体 menu.setParent(this.get(menu.getParent().getId())); // 获取修改前的parentIds,用于更新子节点的parentIds String oldParentIds = menu.getParentIds(); // 设置新的父节点串 menu.setParentIds(menu.getParent().getParentIds() + menu.getParent().getId() + ","); // 保存或更新实体 super.save(menu); // 更新子节点 parentIds Menu m = new Menu(); m.setParentIds("%," + menu.getId() + ",%"); List<Menu> list = mapper.findByParentIdsLike(m); for (Menu e : list) { e.setParentIds(e.getParentIds().replace(oldParentIds, menu.getParentIds())); mapper.updateParentIds(e); } // 清除用户菜单缓存 UserUtils.removeCache(UserUtils.CACHE_MENU_LIST); UserUtils.removeCache(UserUtils.CACHE_TOP_MENU); // 清除日志相关缓存 CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP); } @Transactional(readOnly = false) public void updateSort(Menu menu) { mapper.updateSort(menu); // 清除用户菜单缓存 UserUtils.removeCache(UserUtils.CACHE_MENU_LIST); UserUtils.removeCache(UserUtils.CACHE_TOP_MENU); // 清除日志相关缓存 CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP); } @Transactional(readOnly = false) public void delete(Menu menu) { // 解除菜单角色关联 List<Map<String, Object>> mrlist = mapper.execSelectSql( "SELECT distinct a.menu_id as id FROM sys_role_menu a left join sys_menu menu on a.menu_id = menu.id WHERE a.menu_id ='" + menu.getId() + "' OR menu.parent_ids LIKE '%," + menu.getId() + ",%'"); for (Map<String, Object> mr : mrlist) { mapper.deleteMenuRole(mr.get("id").toString()); } // 删除菜单关联的数据权限数据,以及解除角色数据权限关联 List<Map<String, Object>> mdlist = mapper.execSelectSql( "SELECT distinct a.id as id FROM sys_datarule a left join sys_menu menu on a.menu_id = menu.id WHERE a.menu_id ='" + menu.getId() + "' OR menu.parent_ids LIKE '%," + menu.getId() + ",%'"); for (Map<String, Object> md : mdlist) { DataRule dataRule = new DataRule(md.get("id").toString()); dataRuleService.delete(dataRule); } mapper.delete(menu); // 清除用户菜单缓存 UserUtils.removeCache(UserUtils.CACHE_TOP_MENU); UserUtils.removeCache(UserUtils.CACHE_MENU_LIST); // 清除日志相关缓存 CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/comm/entity/ComDing.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.comm.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 钉钉推送Entity * @author lh * @version 2021-03-22 */ @Data public class ComDing extends DataEntity<ComDing> { private static final long serialVersionUID = 1L; @ExcelField(title="来源类型", align=2, sort=1) private String sourceType; // 来源类型 @ExcelField(title="来源", align=2, sort=2) private String source; // 来源 @ExcelField(title="推送类型", align=2, sort=3) private String dingType; // 推送类型 @ExcelField(title="钉钉推送", align=2, sort=4) private String dingId; // 钉钉推送 public ComDing() { super(); } public ComDing(String id){ super(id); } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/entity/Condition.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; /** * 流程表达式Entity * @author liugf * @version 2019-09-29 */ public class Condition extends DataEntity<Condition> { private static final long serialVersionUID = 1L; private String name; // 名称 private String expression; // 表达式 public Condition() { super(); } public Condition(String id){ super(id); } @ExcelField(title="名称", align=2, sort=1) public String getName() { return name; } public void setName(String name) { this.name = name; } @ExcelField(title="表达式", align=2, sort=2) public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/cppcc/entity/ComData.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.cppcc.entity; import java.util.Date; import java.util.List; import com.google.common.collect.Lists; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 政协通讯Entity * @author lc * @version 2021-03-15 */ @Data public class ComData extends DataEntity<ComData> { private static final long serialVersionUID = 1L; @ExcelField(title="政协通讯", align=2, sort=1) private String communicationData; // 政协通讯 private Date beginUpdateDate; // 开始 更新时间 private Date endUpdateDate; // 结束 更新时间 private List<ComComments> comCommentsList = Lists.newArrayList(); // 子表列表 public ComData() { super(); } public ComData(String id){ super(id); } }<file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/web/app/AppFileController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.web.app; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.FileUtils; import com.jeeplus.config.properties.FileProperties; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.utils.FileKit; import com.jeeplus.modules.sys.utils.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.Calendar; /** * 文件管理Controller * @author liugf * @version 2018-01-21 */ @RestController @RequestMapping("/app/sys/file") public class AppFileController extends BaseController { @Autowired private FileProperties fileProperties; /** * 移动端上传 * @return * @throws IOException * @throws IllegalStateException */ @RequestMapping("webupload/upload") public AjaxJson webupload( HttpServletRequest request, HttpServletResponse response,MultipartFile file) throws IllegalStateException, IOException { AjaxJson j = new AjaxJson(); String uploadPath = request.getParameter("uploadPath"); Calendar cal = Calendar.getInstance(); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH )+1; String token = UserUtils.getToken(); String fileUrl = FileKit.getAttachmentUrl()+uploadPath+"/"+year+"/"+month+"/"; String fileDir = FileKit.getAttachmentDir()+uploadPath+"/"+year+"/"+month+"/"; // 判断文件是否为空 if (!file.isEmpty()) { String name = file.getOriginalFilename (); if(fileProperties.isAvailable (name)) { // 文件保存路径 // 转存文件 FileUtils.createDirectory (fileDir); String filePath = fileDir + name; File newFile = FileUtils.getAvailableFile (filePath, 0); file.transferTo (newFile); j.put ("id", FileKit.transDirToUrl (newFile.getAbsolutePath ())); j.put ("url", fileUrl + newFile.getName ()); return j; }else{ return AjaxJson.error ("请勿上传非法文件!"); } }else { return AjaxJson.error ("文件不存在!"); } } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/web/ButtonController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.web; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.extension.entity.Button; import com.jeeplus.modules.extension.service.ButtonService; /** * 常用按钮Controller * @author 刘高峰 * @version 2019-10-07 */ @RestController @RequestMapping("/extension/button") public class ButtonController extends BaseController { @Autowired private ButtonService buttonService; @ModelAttribute public Button get(@RequestParam(required=false) String id) { Button entity = null; if (StringUtils.isNotBlank(id)){ entity = buttonService.get(id); } if (entity == null){ entity = new Button(); } return entity; } /** * 常用按钮列表数据 */ @GetMapping("list") public AjaxJson list(Button button, HttpServletRequest request, HttpServletResponse response) { Page<Button> page = buttonService.findPage(new Page<Button>(request, response), button); return AjaxJson.success().put("page",page); } /** * 查看,增加,编辑常用按钮表单页面 * params: * mode: add, edit, view, 代表三种模式的页面 */ @GetMapping("queryById") public AjaxJson queryById(Button button) { return AjaxJson.success().put("button", button); } /** * 保存常用按钮 */ @PostMapping("save") public AjaxJson save(Button button, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(button); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 buttonService.save(button);//保存 return AjaxJson.success("保存常用按钮成功"); } /** * 批量删除常用按钮 */ @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ buttonService.delete(buttonService.get(id)); } return AjaxJson.success("删除常用按钮成功"); } } <file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/java/com/jeeplus/modules/database/datamodel/mapper/DataMetaMapper.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.database.datamodel.mapper; import com.jeeplus.core.persistence.BaseMapper; import com.jeeplus.modules.database.datamodel.entity.DataMeta; import org.springframework.stereotype.Repository; import org.apache.ibatis.annotations.Mapper; /** * 数据资源MAPPER接口 * * @author 刘高峰 * @version 2018-08-07 */ @Mapper @Repository public interface DataMetaMapper extends BaseMapper<DataMeta> { public int deleteByDataSetId(String id); } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/entity/FormDefinition.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; /** * 流程表单Entity * @author 刘高峰 * @version 2020-02-02 */ public class FormDefinition extends DataEntity<FormDefinition> { private static final long serialVersionUID = 1L; private FormCategory category; // 分类 父类 private String name; // 表单名称 private FormDefinitionJson formDefinitionJson = new FormDefinitionJson(); public FormDefinition() { super(); } public FormDefinition(String id){ super(id); } public FormDefinition(FormCategory category){ this.category = category; } public FormCategory getCategory() { return category; } public void setCategory(FormCategory category) { this.category = category; } @ExcelField(title="表单名称", align=2, sort=8) public String getName() { return name; } public void setName(String name) { this.name = name; } public FormDefinitionJson getFormDefinitionJson() { return formDefinitionJson; } public void setFormDefinitionJson(FormDefinitionJson formDefinitionJson) { this.formDefinitionJson = formDefinitionJson; } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/manytomany/entity/Student.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.manytomany.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 学生Entity * @author lgf * @version 2021-01-05 */ @Data public class Student extends DataEntity<Student> { private static final long serialVersionUID = 1L; @ExcelField(title="姓名", align=2, sort=1) private String name; // 姓名 public Student() { super(); } public Student(String id){ super(id); } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/moments/entity/Support.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.moments.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 委员圈点赞Entity * @author lh * @version 2021-03-10 */ @Data public class Support extends DataEntity<Support> { private static final long serialVersionUID = 1L; @ExcelField(title="评论主键", align=2, sort=1) private String pid; // 评论主键 @ExcelField(title="类型点赞1评论2", align=2, sort=2) private Integer type; // 类型点赞1评论2 @ExcelField(title="内容", align=2, sort=3) private String content; // 内容 @ExcelField(title="委员圈", align=2, sort=4) private String shareId; // 委员圈 /** * 是否当前用户,不是则不能修改和删除 */ public String isCurrent; public Support() { super(); } public Support(String id){ super(id); } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/mapper/ButtonMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.mapper; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.jeeplus.modules.extension.entity.Button; /** * 常用按钮MAPPER接口 * @author 刘高峰 * @version 2019-10-07 */ @Mapper @Repository public interface ButtonMapper extends BaseMapper<Button> { }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/treetable/mapper/CarKindMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.treetable.mapper; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.TreeMapper; import org.apache.ibatis.annotations.Mapper; import com.jeeplus.modules.test.treetable.entity.CarKind; /** * 车系MAPPER接口 * @author lgf * @version 2021-01-05 */ @Mapper @Repository public interface CarKindMapper extends TreeMapper<CarKind> { }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/video/mapper/LiveMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.video.mapper; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.jeeplus.modules.test.video.entity.Live; import java.util.List; /** * 直播MAPPER接口 * @author lh * @version 2021-03-17 */ @Mapper @Repository public interface LiveMapper extends BaseMapper<Live> { }<file_sep>/jeeplus-plugins/jeeplus-flowable/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.jeeplus</groupId> <artifactId>jeeplus</artifactId> <version>8.0</version> <relativePath>../../pom.xml</relativePath> </parent> <properties> <flowable.version>6.4.2</flowable.version> <liquibase.version>3.6.2</liquibase.version> </properties> <artifactId>jeeplus-flowable</artifactId> <packaging>jar</packaging> <name>jeeplus-flowable</name> <description>bpm project for jeeplus</description> <dependencies> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-core</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-mail</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-oa</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-admin</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-form</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <dependency> <groupId>org.flowable</groupId> <artifactId>flowable-spring-boot-starter-process-rest</artifactId> <version>${flowable.version}</version> </dependency> <dependency> <groupId>org.flowable</groupId> <artifactId>flowable-json-converter</artifactId> <version>${flowable.version}</version> </dependency> <!--<dependency> <groupId>org.flowable</groupId> <artifactId>flowable-rest</artifactId> <version>${flowable.version}</version> </dependency> <dependency> <groupId>org.flowable</groupId> <artifactId>flowable-ui-modeler-rest</artifactId> <version>${flowable.version}</version> </dependency> --> <dependency> <groupId>org.liquibase</groupId> <artifactId>liquibase-core</artifactId> <version>${liquibase.version}</version> <exclusions> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> </exclusion> <exclusion> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </exclusion> </exclusions> </dependency> <!--流程设计器--> <dependency> <groupId>org.flowable</groupId> <artifactId>flowable-ui-modeler-rest</artifactId> <version>${flowable.version}</version> <exclusions> <exclusion> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> </exclusion> <exclusion> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId> </exclusion> <exclusion> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/webapp</directory> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> <include>**/*.ftl</include> </includes> </resource> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> <excludes> <exclude>**/*.woff</exclude> <exclude>**/*.woff2</exclude> <exclude>**/*.ttf</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <filtering>false</filtering> <includes> <include>**/*.woff</include> <include>**/*.woff2</include> <include>**/*.ttf</include> </includes> </resource> </resources> </build> </project> <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/entity/Button.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; /** * 常用按钮Entity * @author 刘高峰 * @version 2019-10-07 */ public class Button extends DataEntity<Button> { private static final long serialVersionUID = 1L; private String name; // 名称 private String code; // 编码 private String sort; // 排序 public Button() { super(); } public Button(String id){ super(id); } @ExcelField(title="名称", align=2, sort=1) public String getName() { return name; } public void setName(String name) { this.name = name; } @ExcelField(title="编码", align=2, sort=2) public String getCode() { return code; } public void setCode(String code) { this.code = code; } @ExcelField(title="排序", align=2, sort=3) public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/entity/FormDefinitionJson.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; /** * 流程表单Entity * @author 刘高峰 * @version 2020-02-02 */ public class FormDefinitionJson extends DataEntity<FormDefinitionJson> { private static final long serialVersionUID = 1L; private String formDefinitionId; // 表单定义id private String json; // 流程表单结构体 private Integer version; // 版本号 private String status; // 状态 private String isPrimary; // 是否主版本 public FormDefinitionJson() { super(); } public FormDefinitionJson(String id){ super(id); } @ExcelField(title="表单定义id", align=2, sort=5) public String getFormDefinitionId() { return formDefinitionId; } public void setFormDefinitionId(String formDefinitionId) { this.formDefinitionId = formDefinitionId; } @ExcelField(title="流程表单结构体", align=2, sort=6) public String getJson() { return json; } public void setJson(String json) { this.json = json; } @ExcelField(title="版本号", align=2, sort=7) public Integer getVersion() { return version; } public void setVersion(Integer version) { this.version = version; } @ExcelField(title="状态", align=2, sort=8) public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @ExcelField(title="是否主版本", align=2, sort=9) public String getIsPrimary() { return isPrimary; } public void setIsPrimary(String isPrimary) { this.isPrimary = isPrimary; } }<file_sep>/jeeplus-module/committee/src/main/java/com/jeeplus/modules/committee/dto/CommitteeDetailDto.java package com.jeeplus.modules.committee.dto; import lombok.Data; /** * @Desc * @Author tangxin * @Date 2021/3/23 */ @Data public class CommitteeDetailDto { private String committeeId; private Integer integralType; private Integer integral; } <file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/java/com/jeeplus/modules/database/datamodel/mapper/DataParamMapper.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.database.datamodel.mapper; import com.jeeplus.core.persistence.BaseMapper; import com.jeeplus.modules.database.datamodel.entity.DataParam; import org.springframework.stereotype.Repository; import org.apache.ibatis.annotations.Mapper; /** * 数据模型参数MAPPER接口 * * @author 刘高峰 * @version 2018-08-07 */ @Mapper @Repository public interface DataParamMapper extends BaseMapper<DataParam> { public int deleteByDataSetId(String id); } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/vo/HisTaskVo.java package com.jeeplus.modules.flowable.vo; import lombok.Data; import org.flowable.task.api.TaskInfo; import org.flowable.task.api.history.HistoricTaskInstance; import java.util.Date; import java.util.Map; /* 历史任务节点 */ @Data public class HisTaskVo { private String id; private String name; private String assignee; private String executionId; private String taskDefinitionKey; private Date createTime; private Date endTime; private String processDefinitionId; private String processInstanceId; private String processDefinitionName; // 流程名称 private boolean isBack; // 流程是否可以撤回到该节点 private String code; //任务办理状态:1,2 private String comment; //任务评论 private String type; // 操作类型编码 private String status; // 任务办理描述: 同意,驳回 private String level; // 文字颜色 private Map vars; private TaskVo currentTask; // 当前流程节点 public HisTaskVo(HistoricTaskInstance task){ this.id = task.getId (); this.name = task.getName (); this.assignee = task.getAssignee (); this.executionId = task.getExecutionId (); this.taskDefinitionKey = task.getTaskDefinitionKey (); this.createTime = task.getCreateTime (); this.endTime = task.getEndTime (); this.executionId = task.getExecutionId (); this.processDefinitionId = task.getProcessDefinitionId (); this.vars = task.getProcessVariables (); this.processInstanceId = task.getProcessInstanceId (); } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/common/config/FlowDataSourceProcessEngineAutoConfiguration.java package com.jeeplus.common.config; import com.jeeplus.modules.flowable.common.factory.MyActivityBehaviorFactory; import com.jeeplus.modules.flowable.service.ext.FlowIdentityServiceImpl; import org.flowable.idm.engine.IdmEngineConfiguration; import org.flowable.idm.engine.configurator.IdmEngineConfigurator; import org.flowable.spring.SpringProcessEngineConfiguration; import org.flowable.spring.boot.EngineConfigurationConfigurer; import org.flowable.spring.boot.FlowableProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @EnableConfigurationProperties(FlowableProperties.class) public class FlowDataSourceProcessEngineAutoConfiguration implements EngineConfigurationConfigurer<SpringProcessEngineConfiguration> { /** * @author : liugafeng * @date : 2019-07-11 08:50 * <p> * 设置流程图识别中文 */ @Override public void configure(SpringProcessEngineConfiguration engineConfiguration) { engineConfiguration.setActivityFontName("宋体"); engineConfiguration.setLabelFontName("宋体"); engineConfiguration.setAnnotationFontName("宋体"); // engineConfiguration.setDatabaseSchemaUpdate("true"); engineConfiguration.setActivityBehaviorFactory(new MyActivityBehaviorFactory ()); } @Bean public IdmEngineConfigurator idmEngineConfigurator(DataSource dataSource) { IdmEngineConfiguration idmEngineConfiguration = new IdmEngineConfiguration(); idmEngineConfiguration.setDataSource(dataSource); idmEngineConfiguration.setIdmIdentityService(new FlowIdentityServiceImpl()); IdmEngineConfigurator idmEngineConfigurator = new IdmEngineConfigurator(); idmEngineConfigurator.setIdmEngineConfiguration(idmEngineConfiguration); return idmEngineConfigurator; } } <file_sep>/jeeplus-web/src/main/java/com/jeeplus/config/AppInit.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import java.net.InetAddress; /** * Created by jeeplus on 2017/11/30. */ @Component public class AppInit implements CommandLineRunner { @Value("${server.port}") private String port; @Value("${server.servlet.context-path}") private String path; @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>jeeplus 启动成功<<<<<<<<<<<<<"); String ip = InetAddress.getLocalHost().getHostAddress(); System.out.println("Jeeplus Application running at:\n\t" + "- Local: http://localhost:" + port + path + "/\n\t" + "- Network: http://" + ip + ":" + port + path + "/\n\t" + "- swagger: http://" + ip + ":" + port + path + "/doc.html\n" + "----------------------------------------------------------"); } } <file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/java/com/jeeplus/modules/database/datamodel/service/DataMetaService.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.database.datamodel.service; import java.util.List; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.database.datamodel.entity.DataMeta; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.modules.database.datamodel.mapper.DataMetaMapper; /** * 数据资源Service * * @author 刘高峰 * @version 2018-08-07 */ @Service @Transactional(readOnly = true) public class DataMetaService extends CrudService<DataMetaMapper, DataMeta> { public DataMeta get(String id) { return super.get(id); } public List<DataMeta> findList(DataMeta dataMeta) { return super.findList(dataMeta); } public Page findPage(Page page, DataMeta dataMeta) { return super.findPage(page, dataMeta); } @Transactional(readOnly = false) public void save(DataMeta dataMeta) { super.save(dataMeta); } @Transactional(readOnly = false) public void delete(DataMeta dataMeta) { super.delete(dataMeta); } @Transactional(readOnly = false) public void deleteByDsId(String id) { mapper.deleteByDataSetId(id); } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/utils/UserUtils.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.utils; import com.google.common.collect.Lists; import com.jeeplus.common.utils.CacheUtils; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.core.service.BaseService; import com.jeeplus.modules.sys.entity.*; import com.jeeplus.modules.sys.mapper.*; import com.jeeplus.modules.sys.security.util.JWTUtil; import org.apache.shiro.SecurityUtils; import org.apache.shiro.UnavailableSecurityManagerException; import org.apache.shiro.session.InvalidSessionException; import org.apache.shiro.session.Session; import org.apache.shiro.subject.Subject; import java.util.List; import java.util.Map; /** * 用户工具类 * @author jeeplus * @version 2016-12-05 */ public class UserUtils { public static final String USER_CACHE = "userCache"; public static final String USER_CACHE_ID_ = "id_"; public static final String USER_CACHE_LOGIN_NAME_ = "ln"; public static final String USER_CACHE_USER_ID_ = "ui"; public static final String USER_CACHE_LIST_BY_OFFICE_ID_ = "oid_"; public static final String CACHE_ROLE_LIST = "roleList"; public static final String CACHE_TOP_MENU = "topMenu"; public static final String CACHE_MENU_LIST = "menuList"; public static final String CACHE_DATA_RULE_LIST = "dataRuleList"; public static final String CACHE_AREA_LIST = "areaList"; public static final String CACHE_OFFICE_LIST = "officeList"; public static final String CACHE_OFFICE_ALL_LIST = "officeAllList"; public static final String CACHE_SPLIT = "_user_id_"; /** * 根据ID获取用户 * @param id * @return 取不到返回null */ public static User get(String id){ User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_ID_ + id); if (user == null){ user = SpringContextHolder.getBean(UserMapper.class).get(id); if (user == null){ return null; } CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user); CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user); CacheUtils.put(USER_CACHE, USER_CACHE_USER_ID_ + user.getUserId(), user); } return user; } public static String getUserNameById(String id){ User user = get(id); if(user == null){ return ""; }else{ return user.getName(); } } /** * 根据登录名获取用户 * @param loginName * @return 取不到返回null */ public static User getByUserId(String loginName){ User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_USER_ID_ + loginName); if (user == null){ user = SpringContextHolder.getBean(UserMapper.class).getByLoginName(new User (null, loginName)); if (user == null){ return null; } CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user); CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user); CacheUtils.put(USER_CACHE, USER_CACHE_USER_ID_ + user.getUserId(), user); } return user; } /** * 根据登录名获取用户 * @param loginName * @return 取不到返回null */ public static User getByLoginName(String loginName){ User user = (User) CacheUtils.get(USER_CACHE, USER_CACHE_LOGIN_NAME_ + loginName); if (user == null){ user = SpringContextHolder.getBean(UserMapper.class).getByLoginName(new User (null, loginName)); if (user == null){ return null; } CacheUtils.put(USER_CACHE, USER_CACHE_ID_ + user.getId(), user); CacheUtils.put(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName(), user); CacheUtils.put(USER_CACHE, USER_CACHE_USER_ID_ + user.getUserId(), user); } return user; } /** * 清除当前用户缓存 */ public static void clearCache(){ removeCache(CACHE_ROLE_LIST); removeCache(CACHE_DATA_RULE_LIST); removeCache(CACHE_TOP_MENU); removeCache(CACHE_MENU_LIST); removeCache(CACHE_AREA_LIST); removeCache(CACHE_OFFICE_LIST); removeCache(CACHE_OFFICE_ALL_LIST); UserUtils.clearCache(getUser()); } /** * 清除指定用户缓存 * @param user */ public static void clearCache(User user){ CacheUtils.remove(USER_CACHE, USER_CACHE_ID_ + user.getId()); CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getLoginName()); CacheUtils.remove(USER_CACHE, USER_CACHE_LOGIN_NAME_ + user.getOldLoginName()); CacheUtils.remove(USER_CACHE, USER_CACHE_USER_ID_ + user.getOldLoginName()); if (user.getOffice() != null && user.getOffice().getId() != null){ CacheUtils.remove(USER_CACHE, USER_CACHE_LIST_BY_OFFICE_ID_ + user.getOffice().getId()); } } /** * 获取当前用户 * @return 取不到返回 new User() */ public static User getUser(){ String token = getToken(); if (token!=null){ User user = getByLoginName(JWTUtil.getLoginName(token)); if (user != null){ return user; } return new User (); } // 如果没有登录,则返回实例化空的User对象。 return new User (); } /** * 获取当前用户 * @return 取不到返回 new User() */ public static User getCasUser(){ String token = getToken(); if (token!=null){ User user = getByLoginName(JWTUtil.getLoginName(token)); if (user != null){ return user; } return new User (); } // 如果没有登录,则返回实例化空的User对象。 return new User (); } /** * 获取当前用户角色列表 * @return */ public static List<Role> getRoleList(){ @SuppressWarnings("unchecked") List<Role> roleList = (List<Role>)getCache(CACHE_ROLE_LIST); if (roleList == null){ User user = getUser(); if (user.isAdmin()){ roleList = SpringContextHolder.getBean(RoleMapper.class).findAllList(new Role ()); }else{ roleList = user.getRoleList(); } putCache(CACHE_ROLE_LIST, roleList); } return roleList; } /** * 获取当前用户授权菜单 * @return */ public static List<Menu> getMenuList(){ @SuppressWarnings("unchecked") List<Menu> menuList = (List<Menu>)getCache(CACHE_MENU_LIST); if (menuList == null){ User user = getUser(); if (user.isAdmin()){ menuList = SpringContextHolder.getBean(MenuMapper.class).findAllList(new Menu ()); }else{ Menu m = new Menu (); m.setUserId(user.getId()); menuList = SpringContextHolder.getBean(MenuMapper.class).findByUserId(m); } putCache(CACHE_MENU_LIST, menuList); } return menuList; } /** * 获取当前用户授权数据权限 * @return */ public static List<DataRule> getDataRuleList(){ @SuppressWarnings("unchecked") List<DataRule> dataRuleList = (List<DataRule>)getCache(CACHE_DATA_RULE_LIST); if (dataRuleList == null){ User user = getUser(); if (user.isAdmin()){ dataRuleList = Lists.newArrayList(); }else{ dataRuleList = SpringContextHolder.getBean(DataRuleMapper.class).findByUserId(user); } putCache(CACHE_DATA_RULE_LIST, dataRuleList); } return dataRuleList; } /** * 获取当前用户授权菜单 * @return */ public static Menu getTopMenu() { Menu topMenu = (Menu) getCache(CACHE_TOP_MENU); if (topMenu == null) { topMenu = SpringContextHolder.getBean(MenuMapper.class).get("1"); putCache(CACHE_TOP_MENU, topMenu); } return topMenu; } /** * 获取当前用户授权的区域 * @return */ public static List<Area> getAreaList(){ @SuppressWarnings("unchecked") List<Area> areaList = (List<Area>)getCache(CACHE_AREA_LIST); if (areaList == null){ areaList = SpringContextHolder.getBean(AreaMapper.class).findAllList(new Area ()); putCache(CACHE_AREA_LIST, areaList); } return areaList; } /** * 获取当前用户有权限访问的部门 * @return */ public static List<Office> getOfficeList(){ @SuppressWarnings("unchecked") List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_LIST); if (officeList == null){ User user = getUser(); if (user.isAdmin()){ officeList = SpringContextHolder.getBean(OfficeMapper.class).findAllList(new Office ()); }else{ Office office = new Office (); BaseService.dataRuleFilter(office); officeList = SpringContextHolder.getBean(OfficeMapper.class).findList(office); } putCache(CACHE_OFFICE_LIST, officeList); } return officeList; } /** * 获取当前用户有权限访问的部门 * @return */ public static List<Office> getOfficeAllList(){ @SuppressWarnings("unchecked") List<Office> officeList = (List<Office>)getCache(CACHE_OFFICE_ALL_LIST); if (officeList == null){ officeList = SpringContextHolder.getBean(OfficeMapper.class).findAllList(new Office ()); } return officeList; } /** * 获取授权主要对象 */ public static Subject getSubject(){ return SecurityUtils.getSubject(); } /** * 获取当前登录者对象 */ public static String getToken(){ try{ Subject subject = SecurityUtils.getSubject(); Object token = subject.getPrincipal(); if (token != null){ return token.toString(); } }catch (UnavailableSecurityManagerException e) { }catch (InvalidSessionException e){ } return null; } public static Session getSession(){ try{ Subject subject = SecurityUtils.getSubject(); Session session = subject.getSession(false); if (session == null){ session = subject.getSession(); } if (session != null){ return session; } // subject.logout(); }catch (InvalidSessionException e){ } return null; } // 根据key,获取和当前用户的缓存 public static Object getCache(String key) { Object obj = CacheUtils.get (USER_CACHE, key + CACHE_SPLIT + getUser ().getId ()); return obj; } //设置当前用户的缓存 public static void putCache(String key, Object value) { CacheUtils.put(USER_CACHE, key + CACHE_SPLIT +getUser ().getId (), value); } //清除当前用户的缓存 public static void removeCache(String key) { CacheUtils.remove (USER_CACHE, key + CACHE_SPLIT +getUser ().getId ()); } /** * 导出Excel调用,根据姓名转换为ID */ public static User getByUserName(String name){ User u = new User (); u.setName(name); List<User> list = SpringContextHolder.getBean(UserMapper.class).findList(u); if(list.size()>0){ return list.get(0); }else{ return new User (); } } /** * 导出Excel使用,根据名字转换为id */ public static Office getByOfficeName(String name){ Office o = new Office (); o.setName(name); List<Office> list = SpringContextHolder.getBean(OfficeMapper.class).findList(o); if(list.size()>0){ return list.get(0); }else{ return new Office (); } } /** * 导出Excel使用,根据名字转换为id */ public static Area getByAreaName(String name){ Area a = new Area (); a.setName(name); List<Area> list = SpringContextHolder.getBean(AreaMapper.class).findList(a); if(list.size()>0){ return list.get(0); }else{ return new Area (); } } public static boolean hasPermission(String permission){ return SecurityUtils.getSubject().isPermitted(permission); } } <file_sep>/jeeplus-plugins/jeeplus-form/src/main/java/com/jeeplus/modules/form/utils/ExcelUtils.java package com.jeeplus.modules.form.utils; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.ss.usermodel.Cell; /** * excel操作辅助类 * @author lc * @version 2021-03-11 */ public class ExcelUtils { // private static Logger log = LoggerFactory.getLogger(ExcelUtils.class); /** * 把EXCEL Cell原有数据转换成String类型 * @param cell * @return */ public static String getCellString(Cell cell) { if(cell==null) return ""; String cellSring=""; switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: // 字符串 cellSring = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_NUMERIC: // 数字 cellSring=String.valueOf(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean cellSring=String.valueOf(cell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: // 公式 cellSring=String.valueOf(cell.getCellFormula()); break; case HSSFCell.CELL_TYPE_BLANK: // 空值 cellSring=""; break; case HSSFCell.CELL_TYPE_ERROR: // 故障 cellSring=""; break; default: cellSring="ERROR"; break; } return cellSring; } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/security/util/JWTUtil.java package com.jeeplus.modules.sys.security.util; import com.auth0.jwt.JWT; import com.auth0.jwt.JWTVerifier; import com.auth0.jwt.algorithms.Algorithm; import com.auth0.jwt.exceptions.JWTDecodeException; import com.auth0.jwt.exceptions.TokenExpiredException; import com.auth0.jwt.interfaces.DecodedJWT; import com.jeeplus.config.properties.JeePlusProperites; import com.jeeplus.modules.sys.utils.UserUtils; import java.util.Date; public class JWTUtil { public static final String TOKEN = "token"; public static final String REFRESH_TOKEN = "refreshToken"; /** * 校验token是否正确 * @param token 密钥 * @return 是否正确 */ public static int verify(String token) { try { String userName = JWTUtil.getLoginName(token); String password = UserUtils.getByLoginName(userName).getPassword(); Algorithm algorithm = Algorithm.HMAC256(password); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username", userName) .build(); DecodedJWT jwt = verifier.verify(token); return 0; } catch (TokenExpiredException e){ return 1; } catch (Exception exception) { return 2; } } /** * 获得token中的信息无需secret解密也能获得 * @return token中包含的用户名 */ public static String getLoginName(String token) { try { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } catch (JWTDecodeException e) { return null; } } /** * 生成签名 * @param username 用户名 * @param password <PASSWORD> * @return 加密的token */ public static String createAccessToken(String username, String password) { Date date = new Date(System.currentTimeMillis() + JeePlusProperites.newInstance().getEXPIRE_TIME()); Algorithm algorithm = Algorithm.HMAC256(password); // 附带username信息 return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } /** * refresh TOKEN 刷新用 * @param username 用户名 * @param password <PASSWORD> * @return 加密的token */ public static String createRefreshToken(String username, String password) { Date date = new Date(System.currentTimeMillis() + 3*JeePlusProperites.newInstance().getEXPIRE_TIME()); Algorithm algorithm = Algorithm.HMAC256(password); // 附带username信息 return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } public static void main(String[] args){ System.out.println(JWTUtil.createAccessToken("admin","1")); } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/utils/RouterUtils.java package com.jeeplus.modules.sys.utils; import com.google.common.collect.Lists; import com.jeeplus.modules.sys.entity.Menu; import org.springframework.beans.BeanUtils; import java.util.List; public class RouterUtils { public static List<Menu> getRoutersByMenu() { Menu menu = UserUtils.getTopMenu(); menu = getChildOfTree(menu, 0, UserUtils.getMenuList()); return menu.getChildren(); } private static Menu getChildOfTree(Menu menuItem1, int level, List<Menu> menuList) { Menu menuItem = new Menu(); BeanUtils.copyProperties(menuItem1,menuItem); menuItem.setChildren(Lists.newArrayList()); for (Menu child : menuList) { if ( child.getParentId().equals(menuItem.getId())) { menuItem.getChildren().add(getChildOfTree(child, level + 1, menuList)); } } return menuItem; } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/service/FlowTaskService.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.flowable.service; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.BaseService; import com.jeeplus.modules.flowable.common.cmd.BackUserTaskCmd; import com.jeeplus.modules.flowable.constant.FlowableConstant; import com.jeeplus.modules.flowable.entity.Flow; import com.jeeplus.modules.flowable.entity.TaskComment; import com.jeeplus.modules.flowable.mapper.FlowMapper; import com.jeeplus.modules.flowable.service.converter.json.FlowModelService; import com.jeeplus.modules.flowable.utils.FlowableUtils; import com.jeeplus.modules.flowable.utils.ProcessDefCache; import com.jeeplus.modules.flowable.vo.*; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.utils.UserUtils; import org.flowable.bpmn.constants.BpmnXMLConstants; import org.flowable.bpmn.model.BpmnModel; import org.flowable.bpmn.model.FlowNode; import org.flowable.bpmn.model.Process; import org.flowable.editor.language.json.converter.util.CollectionUtils; import org.flowable.engine.*; import org.flowable.engine.history.HistoricActivityInstance; import org.flowable.engine.history.HistoricProcessInstance; import org.flowable.engine.history.HistoricProcessInstanceQuery; import org.flowable.engine.runtime.ActivityInstance; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.task.api.DelegationState; import org.flowable.task.api.Task; import org.flowable.task.api.TaskQuery; import org.flowable.task.api.history.HistoricTaskInstance; import org.flowable.task.api.history.HistoricTaskInstanceQuery; import org.flowable.task.service.impl.persistence.entity.TaskEntity; import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl; import org.flowable.variable.api.history.HistoricVariableInstanceQuery; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.ResultSet; import java.sql.SQLException; import java.util.*; import java.util.stream.Collectors; /** * 流程定义相关Service * * @author jeeplus * @version 2016-11-03 */ @Service @Transactional(readOnly = true) public class FlowTaskService extends BaseService { @Autowired private FlowMapper flowMapper; @Autowired private RuntimeService runtimeService; @Autowired private TaskService taskService; @Autowired private FormService formService; @Autowired private HistoryService historyService; @Autowired private RepositoryService repositoryService; @Autowired private IdentityService identityService; @Autowired private FlowModelService flowModelService; @Autowired private ManagementService managementService; @Autowired private FlowProcessService flowProcessService; @Autowired private JdbcTemplate jdbcTemplate; /** * 获取待办任务列表 * * @return */ public Page<ProcessVo> todoList(Page<ProcessVo> page, Flow flow) { List<HashMap<String, String>> result = new ArrayList<HashMap<String, String>> (); String userId = UserUtils.getUser ().getId ();//ObjectUtils.toString(UserUtils.getUser().getId()); // =============== 已经签收或者等待签收的任务 =============== TaskQuery todoTaskQuery = taskService.createTaskQuery ().taskCandidateOrAssigned (userId).active () .includeProcessVariables ().orderByTaskCreateTime ().desc (); // 设置查询条件 if (StringUtils.isNotBlank (flow.getProcDefKey ())) { todoTaskQuery.processDefinitionKey (flow.getProcDefKey ()); } if (flow.getBeginDate () != null) { todoTaskQuery.taskCreatedAfter (flow.getBeginDate ()); } if (flow.getEndDate () != null) { todoTaskQuery.taskCreatedBefore (flow.getEndDate ()); } if (StringUtils.isNotBlank (flow.getTitle ())) { todoTaskQuery.processVariableValueLike (FlowableConstant.TITLE, "%" + flow.getTitle () + "%"); } //任务名称 if (StringUtils.isNotBlank(flow.getTaskName())) { todoTaskQuery.processDefinitionName (flow.getTaskName().trim()); } List<Task> tasks = todoTaskQuery.list (); List<Task> reRasks = new ArrayList<>(); //没传这个参数表示全部都查出来 if(StringUtils.isNotEmpty(flow.getSave())){ for(Task task : tasks){ Map vars = task.getProcessVariables (); if(vars.containsKey("save_") && flow.getSave().equals(vars.get("save_").toString())){ reRasks.add(task); } else if("0".equals(flow.getSave()) && !vars.containsKey("save_")) { reRasks.add(task); } } } else { reRasks = tasks; } page.setCount (reRasks.size ()); // 查询列表 if (page.getPageSize () != -1 && reRasks.size()>10) {//不分页 if((page.getPageSize ()*(page.getPageNo()-1)-1)>reRasks.size ()){ reRasks = new ArrayList<>(); } else { reRasks = reRasks.subList (page.getPageNo()>1?page.getFirstResult ()-1:0, page.getLastResult ()-1); } } for (Task task : reRasks) { Process process = SpringContextHolder.getBean (RepositoryService.class).getBpmnModel (task.getProcessDefinitionId ()).getMainProcess (); ProcessVo processVo = new ProcessVo (); TaskVo taskVo = new TaskVo (task); taskVo.setProcessDefKey (process.getId ()); processVo.setTask (taskVo); processVo.setVars (task.getProcessVariables ()); processVo.setProcessDefinitionName ( ProcessDefCache.get (task.getProcessDefinitionId ()).getName ()); processVo.setVersion (ProcessDefCache.get (task.getProcessDefinitionId ()).getVersion ()); processVo.setStatus ("todo"); page.getList ().add (processVo); } return page; } /** * 获取已办任务列表 * * @param page * @return */ public Page<HisTaskVo> historicList(Page<HisTaskVo> page, Flow act) { String userId = UserUtils.getUser ().getId (); HistoricTaskInstanceQuery histTaskQuery = historyService.createHistoricTaskInstanceQuery ().taskAssignee (userId).finished () .includeProcessVariables ().orderByHistoricTaskInstanceEndTime ().desc (); // 设置查询条件 if (StringUtils.isNotBlank (act.getProcDefKey ())) { histTaskQuery.processDefinitionKey (act.getProcDefKey ()); } if (act.getBeginDate () != null) { histTaskQuery.taskCompletedAfter (act.getBeginDate ()); } if (act.getEndDate () != null) { histTaskQuery.taskCompletedBefore (act.getEndDate ()); } if (act.getTitle () != null) { histTaskQuery.processVariableValueLike (FlowableConstant.TITLE, "%" + act.getTitle () + "%"); } //任务名称 if (StringUtils.isNotBlank(act.getTaskName())) { histTaskQuery.processDefinitionName (act.getTaskName().trim()); } // 查询总数 page.setCount (histTaskQuery.count ()); page.initialize (); // 查询列表 List<HistoricTaskInstance> histList = Lists.newArrayList (); if (page.getMaxResults () == -1) { histList = histTaskQuery.list (); } else { histList = histTaskQuery.listPage (page.getFirstResult (), page.getMaxResults ()); } for (HistoricTaskInstance histTask : histList) { HisTaskVo hisTaskVo= new HisTaskVo (histTask); hisTaskVo.setProcessDefinitionName ( ProcessDefCache.get (histTask.getProcessDefinitionId ()).getName ()); hisTaskVo.setBack (isBack (histTask)); List<Task> currentTaskList = taskService.createTaskQuery ().processInstanceId (histTask.getProcessInstanceId ()).list (); if(((List) currentTaskList).size () > 0){ TaskVo currentTaskVo = new TaskVo (currentTaskList.get (0)); hisTaskVo.setCurrentTask (currentTaskVo); } // 获取意见评论内容 List<TaskComment> commentList = this.getTaskComments (histTask.getId ()); if (commentList.size () > 0) { TaskComment comment = commentList.get (commentList.size ()-1); hisTaskVo.setComment (comment.getMessage ()); hisTaskVo.setLevel (comment.getLevel ()); hisTaskVo.setType (comment.getType ()); hisTaskVo.setStatus (comment.getStatus ()); } page.getList ().add (hisTaskVo); } return page; } /** * 获取流转历史任务列表 * * @param procInsId 流程实例 */ public List<Flow> historicTaskList(String procInsId) throws Exception { List<Flow> actList = Lists.newArrayList (); List<HistoricActivityInstance> list = Lists.newArrayList (); List<HistoricActivityInstance> historicActivityInstances2 = historyService.createHistoricActivityInstanceQuery ().processInstanceId (procInsId) .orderByHistoricActivityInstanceStartTime ().asc ().orderByHistoricActivityInstanceEndTime ().asc ().list (); for (HistoricActivityInstance historicActivityInstance : historicActivityInstances2) { if (historicActivityInstance.getEndTime () != null) { list.add (historicActivityInstance); } } for (HistoricActivityInstance historicActivityInstance : historicActivityInstances2) { if (historicActivityInstance.getEndTime () == null) { list.add (historicActivityInstance); } } for (int i = 0; i < list.size (); i++) { HistoricActivityInstance histIns = list.get (i); // 只显示开始节点和结束节点,并且执行人不为空的任务 if (StringUtils.isNotBlank (histIns.getAssignee ()) && historyService.createHistoricTaskInstanceQuery ().taskId (histIns.getTaskId ()).count () != 0 || BpmnXMLConstants.ELEMENT_TASK_USER.equals (histIns.getActivityType ()) && histIns.getEndTime () == null || BpmnXMLConstants.ELEMENT_EVENT_START.equals (histIns.getActivityType ()) || BpmnXMLConstants.ELEMENT_EVENT_END.equals (histIns.getActivityType ())) { // 获取流程发起人名称 Flow e = queryTaskState (histIns); actList.add (e); } } return actList; } /** * 获取流程表单(首先获取任务节点表单KEY,如果没有则取流程开始节点表单KEY) * * @return */ public String getFormKey(String procDefId, String taskDefKey) { String formKey = ""; if (StringUtils.isNotBlank (procDefId)) { if (StringUtils.isNotBlank (taskDefKey)) { try { formKey = formService.getTaskFormKey (procDefId, taskDefKey); } catch (Exception e) { formKey = ""; } } if (StringUtils.isBlank (formKey)) { formKey = formService.getStartFormKey (procDefId); } if (StringUtils.isBlank (formKey)) { formKey = "/404"; } } logger.debug ("getFormKey: {}", formKey); return formKey; } /** * 获取正在运行的流程实例对象 * * @param procInsId * @return */ @Transactional(readOnly = false) public ProcessInstance getProcIns(String procInsId) { return runtimeService.createProcessInstanceQuery ().processInstanceId (procInsId).singleResult (); } /** * 获取已经结束流程实例对象 * * @param procInsId * @return */ @Transactional(readOnly = false) public HistoricProcessInstance getFinishedProcIns(String procInsId) { return historyService.createHistoricProcessInstanceQuery ().processInstanceId (procInsId).singleResult (); } /** * 获取我发起的流程申请列表 * * @param user * @return */ @Transactional(readOnly = false) public Page<ProcessVo> getMyStartedProcIns(User user, Page<ProcessVo> page, Flow flow) throws Exception { HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery ().startedBy (user.getId ()).includeProcessVariables ().orderByProcessInstanceStartTime ().desc (); if (flow.getBeginDate () != null) { query.startedAfter (flow.getBeginDate ()); } if (flow.getEndDate () != null) { query.startedBefore (flow.getEndDate ()); } if (StringUtils.isNotBlank (flow.getTitle ())) { query.variableValueLike (FlowableConstant.TITLE, "%" + flow.getTitle () + "%"); } page.setCount (query.count ()); List<HistoricProcessInstance> histList = Lists.newArrayList (); if (page.getMaxResults () == -1) {//不分页 histList = query.list (); } else { histList = query.involvedUser (user.getId ()).listPage (page.getFirstResult (), page.getMaxResults ()); } for (HistoricProcessInstance historicProcessInstance : histList) { ProcessVo processVo = flowProcessService.queryProcessState (historicProcessInstance.getProcessDefinitionId (), historicProcessInstance.getId ()); processVo.setEndTime (historicProcessInstance.getEndTime ()); processVo.setStartTime (historicProcessInstance.getStartTime ()); processVo.setProcessDefinitionId (historicProcessInstance.getProcessDefinitionId ()); processVo.setProcessInstanceId (historicProcessInstance.getId ()); processVo.setVars (historicProcessInstance.getProcessVariables ()); processVo.setProcessDefinitionName (historicProcessInstance.getProcessDefinitionName ()); processVo.setVersion ( historicProcessInstance.getProcessDefinitionVersion ()); page.getList ().add (processVo); } return page; } /** * 启动流程 * * @param procDefKey 流程定义KEY * @param businessTable 业务表表名 * @param businessId 业务表编号 * @param title 流程标题,显示在待办任务标题 * @return 流程实例ID */ @Transactional(readOnly = false) public String startProcess(String procDefKey, String businessTable, String businessId, String title) { Map<String, Object> vars = Maps.newHashMap (); return startProcess (procDefKey, businessTable, businessId, title, vars); } /** * 启动流程 * * @param procDefKey 流程定义KEY * @param businessTable 业务表表名 * @param businessId 业务表编号 * @param title 流程标题,显示在待办任务标题 * @param vars 流程变量 * @return 流程实例ID */ @SuppressWarnings("unused") @Transactional(readOnly = false) public String startProcess(String procDefKey, String businessTable, String businessId, String title, Map<String, Object> vars) { //String userId = UserUtils.getUser().getLoginName();//ObjectUtils.toString(UserUtils.getUser().getId()) // 设置流程变量 if (vars == null) { vars = Maps.newHashMap (); } String userId = (String) vars.get (FlowableConstant.INITIATOR); if (userId == null) { userId = UserUtils.getUser ().getId (); } String userName = UserUtils.get (userId).getName (); vars.put (FlowableConstant.USERNAME, userName); // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中 identityService.setAuthenticatedUserId (userId); // 设置流程标题 if (StringUtils.isNotBlank (title)) { vars.put (FlowableConstant.TITLE, title); } // 启动流程 ProcessInstance procIns = runtimeService.startProcessInstanceByKey (procDefKey, businessTable + ":" + businessId, vars); // 更新业务表流程实例ID Flow act = new Flow (); act.setBusinessTable (businessTable);// 业务表名 act.setBusinessId (businessId); // 业务表ID act.setProcInsId (procIns.getId ()); act.setVars (vars); flowMapper.updateProcInsIdByBusinessId (act); return act.getProcInsId (); } /** * 删除任务 * * @param taskId 任务ID * @param deleteReason 删除原因 */ public void deleteTask(String taskId, String deleteReason) { taskService.deleteTask (taskId, deleteReason); } /** * 签收任务 * * @param taskId 任务ID * @param userId 签收用户ID(用户登录名) */ @Transactional(readOnly = false) public void claim(String taskId, String userId) { taskService.claim (taskId, userId); } /** * @desc 暂存任务 * @param flow * @param properties * @return void * @author tangxin * @date 2021/3/12 */ @Transactional(readOnly = false) public void save(Flow flow, Map<String, String> properties){ formService.saveFormData(flow.getTaskId(),properties); } /** * 提交任务, 并保存意见 * * @param vars 任务变量 */ @Transactional(readOnly = false) public Task complete(Flow flow, Map<String, Object> vars) { // 添加意见 if (StringUtils.isNotBlank (flow.getProcInsId ())) { taskService.addComment (flow.getTaskId (), flow.getProcInsId (),flow.getComment ().getCommentType (), flow.getComment ().getFullMessage ()); } // 设置流程变量 if (vars == null) { vars = Maps.newHashMap (); } // 设置流程标题 if (StringUtils.isNotBlank (flow.getTitle ())) { vars.put (FlowableConstant.TITLE, flow.getTitle ()); } Task task = taskService.createTaskQuery ().taskId (flow.getTaskId ()).singleResult (); // owner不为空说明可能存在委托任务 if (StringUtils.isNotBlank (task.getOwner ())) { DelegationState delegationState = task.getDelegationState (); switch (delegationState) { case PENDING: taskService.resolveTask (flow.getTaskId ()); taskService.complete (flow.getTaskId (), vars); break; case RESOLVED: // 委托任务已经完成 break; default: // 不是委托任务 taskService.complete (flow.getTaskId (), vars); break; } } else if(StringUtils.isBlank (task.getAssignee ())) { // 未签收任务 // 签收任务 taskService.claim (flow.getTaskId (), UserUtils.getUser ().getId ()); // 提交任务 taskService.complete (flow.getTaskId (), vars); } else { // 提交任务 taskService.complete (flow.getTaskId (), vars); } return task; } /** * 查询任务节点的状态 */ public Flow queryTaskState(HistoricActivityInstance histIns) { Flow e = new Flow (); e.setHistIns (histIns); // 获取流程发起人名称 if (BpmnXMLConstants.ELEMENT_EVENT_START.equals (histIns.getActivityType ())) { List<HistoricProcessInstance> il = historyService.createHistoricProcessInstanceQuery ().processInstanceId (histIns.getProcessInstanceId ()).orderByProcessInstanceStartTime ().asc ().list (); if (il.size () > 0) { if (StringUtils.isNotBlank (il.get (0).getStartUserId ())) { User user = UserUtils.get (il.get (0).getStartUserId ()); if (user != null) { e.setAssignee (histIns.getAssignee ()); e.setAssigneeName (user.getName ()); } } } TaskComment taskComment = new TaskComment (); taskComment.setStatus (FlowableConstant.START_EVENT_LABEL); taskComment.setMessage (FlowableConstant.START_EVENT_COMMENT); e.setComment (taskComment); return e; } if (BpmnXMLConstants.ELEMENT_EVENT_END.equals (histIns.getActivityType ())) { TaskComment taskComment = new TaskComment (); taskComment.setStatus (FlowableConstant.END_EVENT_LABEL); taskComment.setMessage (FlowableConstant.END_EVENT_COMMENT); e.setAssigneeName (FlowableConstant.SYSTEM_EVENT_COMMENT); e.setComment (taskComment); return e; } // 获取任务执行人名称 if (StringUtils.isNotEmpty (histIns.getAssignee ())) { User user = UserUtils.get (histIns.getAssignee ()); if (user != null) { e.setAssignee (histIns.getAssignee ()); e.setAssigneeName (user.getName ()); } } // 获取意见评论内容 if (StringUtils.isNotBlank (histIns.getTaskId ())) { List<TaskComment> commentList = this.getTaskComments (histIns.getTaskId ()); HistoricVariableInstanceQuery action = historyService.createHistoricVariableInstanceQuery ().processInstanceId (histIns.getProcessInstanceId ()).taskId (histIns.getTaskId ()).variableName ("_flow_button_name"); if (commentList.size () > 0) { TaskComment comment = commentList.get (commentList.size ()-1); e.setComment (comment); }else { e.setComment (new TaskComment ()); } } //等待执行的任务 if(histIns.getEndTime () == null) { TaskComment taskComment = new TaskComment (); taskComment.setStatus (ActionType.WAITING.getStatus ()); taskComment.setMessage (FlowableConstant.WAITING_EVENT_COMMENT); e.setComment (taskComment); } return e; } public List<TaskComment> getTaskComments(String taskId){ return jdbcTemplate.query("select * from ACT_HI_COMMENT where TYPE_ like '"+TaskComment.prefix+"%' and TASK_ID_ = '" + taskId + "' order by TIME_ desc", new RowMapper<TaskComment>() { @Override public TaskComment mapRow(ResultSet rs, int rowNum) throws SQLException { TaskComment taskComment = new TaskComment (); taskComment.setCommentType (rs.getString ("TYPE_")); taskComment.setFullMessage (new String(rs.getBytes ("FULL_MSG_"))); return taskComment; } }); } public Map getDiagram(String processId) { Map m = new HashMap (); try { String processDefId = ""; ProcessInstance pi = runtimeService.createProcessInstanceQuery ().processInstanceId (processId).singleResult (); //流程走完的不显示图 if (pi == null) { processDefId = historyService.createHistoricProcessInstanceQuery ().processInstanceId (processId).singleResult ().getProcessDefinitionId (); } else { processDefId = pi.getProcessDefinitionId (); } BpmnModel bpmnModel = repositoryService.getBpmnModel (processDefId); List<HistoricActivityInstance> historyProcess = getHistoryProcess (processId); Set<String> activityIds = new LinkedHashSet<> (); List<String> flows = new ArrayList<> (); for (HistoricActivityInstance hi : historyProcess) { String activityType = hi.getActivityType (); if (activityType.equals (BpmnXMLConstants.ELEMENT_SEQUENCE_FLOW) || activityType.equals (BpmnXMLConstants.ELEMENT_GATEWAY_EXCLUSIVE)) { flows.add (hi.getActivityId ()); } else if (StringUtils.isNotBlank (hi.getAssignee ()) && historyService.createHistoricTaskInstanceQuery ().taskId (hi.getTaskId ()).count () != 0 || BpmnXMLConstants.ELEMENT_TASK_USER.equals (hi.getActivityType ()) && hi.getEndTime () == null || BpmnXMLConstants.ELEMENT_EVENT_START.equals (hi.getActivityType ()) || BpmnXMLConstants.ELEMENT_EVENT_END.equals (hi.getActivityType ())) { activityIds.add (hi.getActivityId ()); } } List<Task> tasks = taskService.createTaskQuery ().processInstanceId (processId).list (); for (Task task : tasks) { activityIds.add (task.getTaskDefinitionKey ()); } byte[] bpmnBytes = flowModelService.getBpmnXML (bpmnModel); m.put ("bpmnXml", new String (bpmnBytes)); m.put ("flows", flows); m.put ("activityIds", activityIds); return m; } catch (Exception e) { e.printStackTrace (); } return null; } /** * 任务历史 * * @param processId 部署id */ public List<HistoricActivityInstance> getHistoryProcess(String processId) { List<HistoricActivityInstance> list = historyService // 历史相关Service .createHistoricActivityInstanceQuery () // 创建历史活动实例查询 .processInstanceId (processId) // 执行流程实例id .finished ().orderByHistoricActivityInstanceEndTime ().asc () .list (); return list; } /** * 保存审核意见 * * @param flow */ @Transactional(readOnly = false) public void auditSave(Flow flow, Map vars) { flow.preUpdate (); complete (flow, vars); } /** * 是否可以取回任务 */ public boolean isBack(HistoricTaskInstance hisTask) { ProcessInstance pi = runtimeService.createProcessInstanceQuery () .processInstanceId (hisTask.getProcessInstanceId ()).singleResult (); if (pi != null) { if (pi.isSuspended ()) { return false; } else { Task currentTask = taskService.createTaskQuery ().processInstanceId (hisTask.getProcessInstanceId ()).list ().get (0); HistoricTaskInstance lastHisTask = historyService.createHistoricTaskInstanceQuery ().processInstanceId (hisTask.getProcessInstanceId ()).finished () .includeProcessVariables ().orderByHistoricTaskInstanceEndTime ().desc ().list ().get (0); if (currentTask.getClaimTime () != null) {//用户已签收 return false; } if (hisTask.getId ().equals (lastHisTask.getId ())) { return true; } return false; } } else { return false; } } /* * 驳回任务 */ @Transactional(readOnly = false) public void backTask(String backTaskDefKey, String taskId, TaskComment comment) { Task task = taskService.createTaskQuery ().taskId (taskId).singleResult (); if(StringUtils.isBlank (task.getAssignee ())){ taskService.claim (taskId, UserUtils.getUser ().getId ()); } // 退回发起者处理,退回到发起者,默认设置任务执行人为发起者 ActivityInstance targetRealActivityInstance = runtimeService.createActivityInstanceQuery ().processInstanceId (task.getProcessInstanceId ()).activityId (backTaskDefKey).list ().get (0); if (targetRealActivityInstance.getActivityType ().equals (BpmnXMLConstants.ELEMENT_EVENT_START)) { flowProcessService.stopProcessInstanceById (task.getProcessInstanceId (), ProcessStatus.REJECT, comment.getMessage ()); }else { taskService.addComment (taskId, task.getProcessInstanceId (), comment.getCommentType (), comment.getFullMessage ()); managementService.executeCommand (new BackUserTaskCmd (runtimeService, taskId, backTaskDefKey)); } // TODO 发送消息通知 } /** * 获取可驳回节点 * * @param taskId * @return */ public List<Flow> getBackNodes(String taskId) { Task taskEntity = taskService.createTaskQuery ().taskId (taskId).singleResult (); String processInstanceId = taskEntity.getProcessInstanceId (); String currActId = taskEntity.getTaskDefinitionKey (); String processDefinitionId = taskEntity.getProcessDefinitionId (); Process process = repositoryService.getBpmnModel (processDefinitionId).getMainProcess (); FlowNode currentFlowElement = (FlowNode) process.getFlowElement (currActId, true); List<ActivityInstance> activitys = runtimeService.createActivityInstanceQuery ().processInstanceId (processInstanceId).finished ().orderByActivityInstanceStartTime ().asc ().list (); List<String> activityIds = activitys.stream ().filter (activity -> activity.getActivityType ().equals (BpmnXMLConstants.ELEMENT_TASK_USER) || activity.getActivityType ().equals (BpmnXMLConstants.ELEMENT_EVENT_START)).filter (activity -> !activity.getActivityId ().equals (currActId)).map (ActivityInstance::getActivityId).distinct ().collect (Collectors.toList ()); List<Flow> result = new ArrayList<> (); for (String activityId : activityIds) { FlowNode toBackFlowElement = (FlowNode) process.getFlowElement (activityId, true); if (FlowableUtils.isReachable (process, toBackFlowElement, currentFlowElement)) { Flow vo = new Flow (); vo.setTaskDefKey (activityId); vo.setTaskName (toBackFlowElement.getName ()); vo.setTaskId (activityId); result.add (vo); } } return result; } @Transactional(readOnly = false) public void addSignTask(String taskId, List<String> userIds, String comment, Boolean flag) throws Exception { TaskEntityImpl taskEntity = (TaskEntityImpl) taskService.createTaskQuery().taskId(taskId).singleResult(); //1.把当前的节点设置为空 if (taskEntity != null) { //如果是加签再加签 String parentTaskId = taskEntity.getParentTaskId(); if (org.apache.commons.lang.StringUtils.isBlank(parentTaskId)) { taskEntity.setOwner(UserUtils.getUser ().getId ()); taskEntity.setAssignee(null); taskEntity.setCountEnabled(true); if (flag) { taskEntity.setScopeType(FlowableConstant.AFTER_ADDSIGN); } else { taskEntity.setScopeType(FlowableConstant.BEFORE_ADDSIGN); } //1.2 设置任务为空执行者 taskService.saveTask(taskEntity); } //2.添加加签数据 this.createSignSubTasks(userIds, taskEntity); //3.添加审批意见 String type = flag ? ActionType.ADD_AFTER_MULTI_INSTANCE.toString() : ActionType.ADD_BEFORE_MULTI_INSTANCE.toString(); taskService.addComment (taskId, taskEntity.getProcessInstanceId (), type, comment); } else { throw new Exception ("不存在任务实例,请确认!"); } } /** * 创建加签子任务 * * @param userIds 加签参数 * @param taskEntity 父任务 */ private void createSignSubTasks(List<String> userIds, TaskEntity taskEntity) { if (CollectionUtils.isNotEmpty(userIds)) { String parentTaskId = taskEntity.getParentTaskId(); if (org.apache.commons.lang.StringUtils.isBlank(parentTaskId)) { parentTaskId = taskEntity.getId(); } String finalParentTaskId = parentTaskId; //1.创建被加签人的任务列表 userIds.forEach(userCode -> { if (StringUtils.isNotBlank(userCode)) { this.createSubTask(taskEntity, finalParentTaskId, userCode); } }); String taskId = taskEntity.getId(); if (org.apache.commons.lang.StringUtils.isBlank(taskEntity.getParentTaskId())) { //2.创建加签人的任务并执行完毕 Task task = this.createSubTask(taskEntity, finalParentTaskId, UserUtils.getUser ().getId ()); taskId = task.getId(); } Task taskInfo = taskService.createTaskQuery().taskId(taskId).singleResult(); if (null != taskInfo) { taskService.complete(taskId); } //如果是候选人,需要删除运行时候选表种的数据。 long candidateCount = taskService.createTaskQuery().taskId(parentTaskId).taskCandidateUser(UserUtils.getUser ().getId ()).count(); if (candidateCount > 0) { taskService.deleteCandidateUser(parentTaskId, UserUtils.getUser ().getId ()); } } } /** * 创建子任务 * * @param ptask 创建子任务 * @param assignee 子任务的执行人 * @return */ protected TaskEntity createSubTask(TaskEntity ptask, String ptaskId, String assignee) { TaskEntity task = null; if (ptask != null) { //1.生成子任务 task = (TaskEntity) taskService.newTask(UUID.randomUUID ().toString ()); task.setCategory(ptask.getCategory()); task.setDescription(ptask.getDescription()); task.setTenantId(ptask.getTenantId()); task.setAssignee(assignee); task.setName(ptask.getName()); task.setParentTaskId(ptaskId); task.setProcessDefinitionId(ptask.getProcessDefinitionId()); task.setProcessInstanceId(ptask.getProcessInstanceId()); task.setTaskDefinitionKey(ptask.getTaskDefinitionKey()); task.setTaskDefinitionId(ptask.getTaskDefinitionId()); task.setPriority(ptask.getPriority()); task.setCreateTime(new Date()); taskService.saveTask(task); } return task; } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/ding/config/DingUrl.java package com.jeeplus.ding.config; /** * @author: lh * @date: 2021/3/8 */ public class DingUrl { /** * 钉钉网关gettoken地址 */ public static final String URL_GET_TOKKEN = "https://oapi.dingtalk.com/gettoken"; /** *获取用户在企业内userId的接口URL */ public static final String URL_GET_USER_INFO = "https://oapi.dingtalk.com/topapi/v2/user/getuserinfo"; /** *获取用户姓名的接口url */ public static final String URL_USER_GET = "https://oapi.dingtalk.com/user/get"; /** * 获取ticket */ public static final String URL_JSAPI_TICKET = "https://oapi.dingtalk.com/get_jsapi_ticket"; /** * 发起工作待办通知 */ public static final String URL_WORK_CORD = "https://oapi.dingtalk.com/topapi/workrecord/add"; /** * 发起工作通知 */ public static final String URL_WORK_NOTICE = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2"; /** * 创建日程 */ public static final String URL_DATE_EVENT = "https://oapi.dingtalk.com/topapi/calendar/v2/event/create"; /** * 取消日程 */ public static final String URL_DATE_EVENT_CANCEL = "https://oapi.dingtalk.com/topapi/calendar/v2/event/cancel"; } <file_sep>/jeeplus-plugins/jeeplus-search/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.jeeplus</groupId> <artifactId>jeeplus</artifactId> <version>8.0</version> <relativePath>../../pom.xml</relativePath> </parent> <artifactId>jeeplus-search</artifactId> <packaging>jar</packaging> <name>jeeplus-search</name> <description>search for jeeplus</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <lib.path>${basedir}/lib</lib.path> <java.version>1.8</java.version> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/com.baidu.aip/java-sdk --> <dependency> <groupId>com.baidu.aip</groupId> <artifactId>java-sdk</artifactId> <version>4.15.3</version> <exclusions> <exclusion> <artifactId>slf4j-simple</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-core</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-admin</artifactId> <version>${project.parent.version}</version> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-form</artifactId> <version>8.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.jeeplus</groupId> <artifactId>jeeplus-flowable</artifactId> <version>8.0</version> <scope>compile</scope> </dependency> </dependencies> </project> <file_sep>/jeeplus-module/committee/src/main/java/com/jeeplus/modules/committee/entity/CommitteeDetail.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.committee.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 常委详情Entity * @author tangxin * @version 2021-03-24 */ @Data public class CommitteeDetail extends DataEntity<CommitteeDetail> { private static final long serialVersionUID = 1L; @ExcelField(title="头像", align=2, sort=1) private String photo; // 头像 @ExcelField(title="界别", dictType="sectors", align=2, sort=2) private String sector; // 界别 @ExcelField(title="所在组织", align=2, sort=3) private String org; // 所在组织 @ExcelField(title="常委名称", align=2, sort=4) private String name; // 常委名称 private StandingCommittee standing; // 常委会id 父类 public CommitteeDetail() { super(); } public CommitteeDetail(String id){ super(id); } public CommitteeDetail(StandingCommittee standing){ this.standing = standing; } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/shop/entity/Goods.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.shop.entity; import com.jeeplus.modules.test.shop.entity.Category; import javax.validation.constraints.NotNull; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 商品Entity * @author liugf * @version 2021-01-05 */ @Data public class Goods extends DataEntity<Goods> { private static final long serialVersionUID = 1L; @ExcelField(title="商品名称", align=2, sort=1) private String name; // 商品名称 @NotNull(message="所属类型不能为空") @ExcelField(title="所属类型", fieldType=Category.class, value="category.name", align=2, sort=2) private Category category; // 所属类型 @ExcelField(title="价格", align=2, sort=3) private String price; // 价格 public Goods() { super(); } public Goods(String id){ super(id); } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/web/TaskDefExtensionController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.web; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.extension.entity.TaskDefExtension; import com.jeeplus.modules.extension.service.TaskDefExtensionService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * 工作流扩展Controller * @author 刘高峰 * @version 2020-12-23 */ @RestController @RequestMapping(value = "/extension/taskDefExtension") public class TaskDefExtensionController extends BaseController { @Autowired private TaskDefExtensionService taskDefExtensionService; @ModelAttribute public TaskDefExtension get(@RequestParam(required=false) String id) { TaskDefExtension entity = null; if (StringUtils.isNotBlank(id)){ entity = taskDefExtensionService.get(id); } if (entity == null){ entity = new TaskDefExtension(); } return entity; } /** * 工作流扩展列表数据 */ @GetMapping("list") public AjaxJson list(TaskDefExtension taskDefExtension, HttpServletRequest request, HttpServletResponse response) { Page<TaskDefExtension> page = taskDefExtensionService.findPage(new Page<TaskDefExtension>(request, response), taskDefExtension); return AjaxJson.success().put("page",page); } /** * 根据Id获取工作流扩展数据 */ @GetMapping("queryById") public AjaxJson queryById(TaskDefExtension taskDefExtension) { return AjaxJson.success().put("taskDefExtension", taskDefExtension); } @GetMapping("queryByDefIdAndTaskId") public AjaxJson queryByDefIdAndTaskId(TaskDefExtension taskDefExtension) throws Exception { if(StringUtils.isBlank(taskDefExtension.getProcessDefId()) || StringUtils.isBlank(taskDefExtension.getTaskDefId())){ return AjaxJson.success().put("taskDefExtension", null); } List<TaskDefExtension> list = taskDefExtensionService.findList(taskDefExtension); if(list.size() > 1){ throw new Exception("重复的task id定义!"); }else if(list.size() == 1){ String id = list.get(0).getId(); return AjaxJson.success().put("taskDefExtension", taskDefExtensionService.get(id)); }else { return AjaxJson.success().put("taskDefExtension", taskDefExtension); } } /** * 保存工作流扩展 */ @PostMapping("save") public AjaxJson save(@RequestBody List<TaskDefExtension> taskDefExtensionList, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ for(TaskDefExtension taskDefExtension: taskDefExtensionList){ List<TaskDefExtension> list = taskDefExtensionService.findList(taskDefExtension); for(TaskDefExtension defExtension:list){ taskDefExtensionService.delete(defExtension); } //新增或编辑表单保存 taskDefExtensionService.save(taskDefExtension);//保存 } return AjaxJson.success("保存工作流扩展成功"); } /** * 批量删除工作流扩展 */ @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ taskDefExtensionService.delete(new TaskDefExtension(id)); } return AjaxJson.success("删除工作流扩展成功"); } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/web/FlowableFormController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.flowable.web; import com.google.common.collect.Lists; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.flowable.entity.Flow; import com.jeeplus.modules.flowable.entity.TaskComment; import com.jeeplus.modules.flowable.service.FlowNoticeService; import com.jeeplus.modules.flowable.service.FlowTaskService; import com.jeeplus.modules.sys.utils.UserUtils; import net.sf.json.JSONObject; import org.flowable.bpmn.model.FlowElement; import org.flowable.bpmn.model.StartEvent; import org.flowable.bpmn.model.UserTask; import org.flowable.engine.*; import org.flowable.engine.form.FormProperty; import org.flowable.engine.form.StartFormData; import org.flowable.engine.form.TaskFormData; import org.flowable.task.api.Task; import org.flowable.variable.api.history.HistoricVariableInstance; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import java.lang.reflect.Field; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; /** * 流程个人任务相关Controller * * @author jeeplus * @version 2016-11-03 */ @RestController @RequestMapping("/flowable/form") public class FlowableFormController extends BaseController { @Autowired private FlowTaskService flowTaskService; @Autowired private FormService formService; @Autowired private HistoryService historyService; @Autowired private RepositoryService repositoryService; @Autowired private TaskService taskService; @Autowired private IdentityService identityService; @Autowired private FlowNoticeService flowNoticeService; /** * 提交表单 * * @param processDefinitionId 流程定义ID */ @PostMapping("submitStartFormData") public AjaxJson submitStartFormData(String assignee, String processDefinitionId, String title, @RequestParam("data") String data) { StartFormData formData = formService.getStartFormData(processDefinitionId);//拿取流程启动前的表单字段。 List<FormProperty> formProperties = formData.getFormProperties();//获取表单字段值 JSONObject jData = JSONObject.fromObject(data); // 设置流程变量 Map<String,String> formValues = new HashMap<String,String>(); String userId = UserUtils.getUser().getId(); String userName = UserUtils.get(userId).getName(); formValues.put("userName", userName); // 用来设置启动流程的人员ID,引擎会自动把用户ID保存到activiti:initiator中 identityService.setAuthenticatedUserId(userId); // 设置流程标题 if (StringUtils.isNotBlank(title)) { formValues.put("title", title); } for(FormProperty formProperty:formProperties){ if (formProperty.isWritable()) { if(jData.has(formProperty.getId())){ String value = jData.getString(formProperty.getId());//拿取具体参数值 formValues.put(formProperty.getId(), value); } } } String procInsId = formService.submitStartFormData(processDefinitionId,formValues).getId();//启动流程,提交表单 //指定下一步处理人 if(StringUtils.isNotBlank(assignee)){ Task task = taskService.createTaskQuery().processInstanceId(procInsId).active().singleResult(); if(task != null){ taskService.setAssignee(task.getId(), assignee); flowNoticeService.sendNotice(startFlow(assignee), formValues,task); } } return AjaxJson.success("启动成功").put("procInsId", procInsId); } private Flow startFlow(String assignee){ Flow flow = new Flow(); TaskComment comment = new TaskComment(); comment.setStatus("启动"); comment.setMessage("流程启动"); flow.setAssignee(assignee); flow.setComment(comment); return flow; } /** * 获取表单数据 * * @param taskId 任务ID */ @GetMapping("getTaskFormData") public AjaxJson getTaskFormData(String taskId) { TaskFormData taskFormData = formService.getTaskFormData(taskId);//根据任务ID拿取表单数据 return AjaxJson.success().put("taskFormData", taskFormData.getFormProperties()); } /** * 获取表单启动弄数据 * * @param processDefinitionId 流程定义id */ @GetMapping("getStartFormData") public AjaxJson getStartFormData(String processDefinitionId) { StartFormData startFormData = formService.getStartFormData(processDefinitionId);//根据流程定义ID拿取表单数据 return AjaxJson.success().put("startFormData", startFormData.getFormProperties()); } /** * 获取历史表单数据 * * @param processInstanceId 流程实例Id */ @GetMapping("getHistoryTaskFormData") public AjaxJson getHistroyTaskFormData(String processInstanceId, String procDefId, String taskDefKey) { List<HistoricVariableInstance> historicVariableInstances=historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstanceId) .list(); HashMap<String,Object> historicVariableMap = new HashMap<>(); for(HistoricVariableInstance historicVariableInstance: historicVariableInstances){ historicVariableMap.put(historicVariableInstance.getVariableName(), historicVariableInstance.getValue()); } List<Map> list = Lists.newArrayList(); FlowElement node = repositoryService.getBpmnModel(procDefId).getFlowElement(taskDefKey); if(node!=null){ List<org.flowable.bpmn.model.FormProperty> formPropertyList = Lists.newArrayList(); if(node instanceof UserTask){ formPropertyList = ((UserTask) node).getFormProperties(); }else if(node instanceof StartEvent){ formPropertyList = ((StartEvent) node).getFormProperties(); } for(org.flowable.bpmn.model.FormProperty formProperty : formPropertyList){ try { HashMap<String,Object> formPropertyMap = new HashMap<>(); Field field = formProperty.getClass().getDeclaredField("readable"); field.setAccessible(true); boolean readable =(boolean) field.get(formProperty); if(readable){ formPropertyMap.put("id", formProperty.getId()); formPropertyMap.put("name", formProperty.getName()); formPropertyMap.put("value", historicVariableMap.get(formProperty.getId())); formPropertyMap.put("readable", readable); list.add(formPropertyMap); } }catch (Exception e){ } } }else{ List<FormProperty> formPropertyList = formService.getStartFormData(procDefId).getFormProperties(); for(FormProperty formProperty : formPropertyList){ try { HashMap<String,Object> formPropertyMap = new HashMap<>(); boolean readable = formProperty.isReadable(); if(readable){ formPropertyMap.put("id", formProperty.getId()); formPropertyMap.put("name", formProperty.getName()); formPropertyMap.put("value", historicVariableMap.get(formProperty.getId())); formPropertyMap.put("readable", readable); list.add(formPropertyMap); } }catch (Exception e){ } } } return AjaxJson.success().put("taskFormData", list); } /** * 暂存表单表单 */ @PostMapping("saveTaskFormData") public AjaxJson saveTaskFormData(Flow flow, @RequestParam("data") String data) { TaskFormData taskFormData = formService.getTaskFormData(flow.getTaskId ());//根据任务ID拿取表单数据 List<FormProperty> formProperties = taskFormData.getFormProperties();//获取表单字段值 JSONObject jData = JSONObject.fromObject(data); HashSet noCommitValues = new HashSet(); Map<String, String> formValues = new HashMap(); for (FormProperty formProperty : formProperties) { if (!formProperty.isWritable()) { noCommitValues.add(formProperty.getId()); } } for(Object str: jData.keySet()){ if(!noCommitValues.contains(str.toString())){ String value = jData.get(str.toString()).toString();//拿取具体参数值 formValues.put(str.toString(), value); //将ID和value存入map中 } } formValues.put("assignee", "");// 避免jackson序列化错误 formValues.put("save_","1"); flowTaskService.save(flow, formValues ); //提交用户任务表单并且完成任务。 return AjaxJson.success("暂存成功"); } /** * 提交表单 */ @PostMapping("submitTaskFormData") public AjaxJson submitTaskFormData(Flow flow, @RequestParam("data") String data) { TaskFormData taskFormData = formService.getTaskFormData(flow.getTaskId ());//根据任务ID拿取表单数据 List<FormProperty> formProperties = taskFormData.getFormProperties();//获取表单字段值 JSONObject jData = JSONObject.fromObject(data); Map<String, Object> formValues = new HashMap<String, Object>(); HashSet noCommitValues = new HashSet(); for (FormProperty formProperty : formProperties) { if (!formProperty.isWritable()) { noCommitValues.add(formProperty.getId()); } } for(Object str: jData.keySet()){ if(!noCommitValues.contains(str.toString())){ Object value = jData.get(str.toString());//拿取具体参数值 if("save_".equals(str.toString())) value = "0"; formValues.put(str.toString(), value); //将ID和value存入map中 } } formValues.put("assignee", "");// 避免jackson序列化错误 flowTaskService.complete(flow, formValues ); //提交用户任务表单并且完成任务。 //指定下一步处理人 if(StringUtils.isNotBlank(flow.getAssignee ())){ Task task = taskService.createTaskQuery().processInstanceId(flow.getProcInsId ()).active().singleResult(); if(task != null){ taskService.setAssignee(task.getId(), flow.getAssignee ()); flowNoticeService.sendNotice(flow, formValues,task); } } return AjaxJson.success("提交成功"); } } <file_sep>/jeeplus-plugins/jeeplus-monitor/src/main/java/com/jeeplus/modules/monitor/server/ServerOS.java package com.jeeplus.modules.monitor.server; import com.google.common.collect.Lists; import com.jeeplus.modules.monitor.utils.MathUtils; import com.jeeplus.modules.monitor.utils.IpUtils; import oshi.SystemInfo; import oshi.hardware.CentralProcessor; import oshi.hardware.GlobalMemory; import oshi.hardware.HardwareAbstractionLayer; import oshi.software.os.FileSystem; import oshi.software.os.OSFileStore; import oshi.software.os.OperatingSystem; import oshi.util.Util; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * @author : liugf * @date : 2019/9/27 **/ public class ServerOS { public static Map getInfo(){ Map map = new HashMap(); SystemInfo si = new SystemInfo(); HardwareAbstractionLayer hal = si.getHardware(); CentralProcessor processor = hal.getProcessor(); //获取cpu信息 map.put("cpu", setCpuInfo(processor)); GlobalMemory memory = hal.getMemory(); //获取内存信息 map.put("mem", setMemInfo(memory)); map.put("sys", setSysInfo()); //服务器信息 map.put("jvm", setJvmInfo()); //jvm信息 OperatingSystem op = si.getOperatingSystem(); map.put("file",setSysFiles(op)); //磁盘信息 map.put("ip", IpUtils.getHostIp()); map.put("hostname", IpUtils.getHostName()); return map; } /** * cpu信息 * @param processor */ private static Map setCpuInfo(CentralProcessor processor) { // CPU信息 long[] prevTicks = processor.getSystemCpuLoadTicks(); Util.sleep(1000); long[] ticks = processor.getSystemCpuLoadTicks(); double nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()]; double irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()]; double softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]; double steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()]; /** * CPU系统使用率 */ double sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; /** * CPU用户使用率 */ double used = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()]; /** * CPU当前等待率 */ double iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; /** * CPU当前空闲率 */ double free = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; /** * CPU总的使用率 */ double total = used + nice + sys + free + iowait + irq + softirq + steal; /** * 核心数 */ int cpuNum = processor.getLogicalProcessorCount(); /** * CPU当前等待率 */ Map cpu = new HashMap<String,String>(); cpu.put("cpucard", processor);//cpu信息 cpu.put("num", processor.getLogicalProcessorCount());//cpu核心数 cpu.put("used", MathUtils.round(MathUtils.mul((sys+used) / total, 100), 2));//cpu 用户使用率; cpu.put("free", MathUtils.round(MathUtils.mul(free / total, 100), 2));//cpu 空闲率 return cpu; } /** * 内存信息 */ private static Map setMemInfo(GlobalMemory memory) { /** * 内存总量 */ double total = +memory.getTotal(); /** * 已用内存 */ double used = memory.getTotal() - memory.getAvailable(); /** * 剩余内存 */ double free = memory.getAvailable(); Map mem = new HashMap(); mem.put("total", div(total, (1024 * 1024 * 1024), 2));// 内存总大小 mem.put("usedMem", div(used, (1024 * 1024 * 1024), 2));// 已使用内存大小 mem.put("free", MathUtils.round(MathUtils.mul(free / total, 100), 2));// 剩余内存大小 mem.put("used", MathUtils.round(MathUtils.mul(used / total, 100), 2)); return mem; } /** * 服务器信息 */ private static Properties setSysInfo() { Properties props = System.getProperties(); return props; } /** * Java虚拟机 */ private static Map setJvmInfo() { Properties props = System.getProperties(); Map jvm = new HashMap(); jvm.put("total", div(Runtime.getRuntime().totalMemory(),1024*1024,2)); jvm.put("maxTotal",div(Runtime.getRuntime().maxMemory(),1024*1024,2)); jvm.put("usedMem", div((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()),1024*1024,2)); jvm.put("used", MathUtils.round(MathUtils.mul((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory())*1.0/ Runtime.getRuntime().totalMemory(), 100), 2)); return jvm; } /** * 设置磁盘信息 */ private static List setSysFiles(OperatingSystem os) { FileSystem fileSystem = os.getFileSystem(); OSFileStore[] fsArray = fileSystem.getFileStores(); List list = Lists.newArrayList(); for (OSFileStore fs : fsArray) { long free = fs.getUsableSpace(); long total = fs.getTotalSpace(); long used = total - free; Map map = new HashMap(); map.put("path", fs.getMount()); map.put("type", fs.getType()); map.put("name", fs.getName()); map.put("total", convertFileSize(total)); map.put("free", convertFileSize(free)); map.put("used", convertFileSize(used)); map.put("rate", div(used, total, 4)*100); list.add(map); } return list; } /** * 字节转换 * * @param size 字节大小 * @return 转换后值 */ public static String convertFileSize(long size) { long kb = 1024; long mb = kb * 1024; long gb = mb * 1024; if (size >= gb) { return String.format("%.1f GB", (float) size / gb); } else if (size >= mb) { float f = (float) size / mb; return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f); } else if (size >= kb) { float f = (float) size / kb; return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f); } else { return String.format("%d B", size); } } /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 * 定精度,以后的数字四舍五入。 * @param v1 被除数 * @param v2 除数 * @param scale 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ public static double div(double v1, double v2, int scale) { return ((double)((int)( v1/v2 * Math.pow(10 , scale))))/Math.pow(10 , scale) ; } public static void main(String[] args){ System.out.println(div(19, 7, 4)); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/moments/entity/Share.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.moments.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.test.comm.entity.ComFiles; import lombok.Data; import java.util.List; /** * 委员圈Entity * @author lh * @version 2021-03-10 */ @Data public class Share extends DataEntity<Share> { private static final long serialVersionUID = 1L; @ExcelField(title="内容", align=2, sort=1) private String content; // 内容 private String invis; // 不可见人员 private String vis; // 可见人员 public Share() { super(); } public Share(String id){ super(id); } /** * 是否当前用户,不是则不能修改和删除 */ public String isCurrent; public List<Support> supports; public List<ComFiles> comFiles; public List<Remind> reminds; public List<User> invisUsers; public List<User> visUsers; }<file_sep>/jeeplus-plugins/jeeplus-echarts/src/main/java/com/jeeplus/modules/echarts/entity/ChartData.java package com.jeeplus.modules.echarts.entity; import com.google.common.collect.Lists; import java.util.List; import java.util.Map; public class ChartData { private List<String> columns = Lists.newArrayList(); private List<Map> rows = Lists.newArrayList(); public List<String> getColumns() { return columns; } public void setColumns(List<String> columns) { this.columns = columns; } public List<Map> getRows() { return rows; } public void setRows(List<Map> rows) { this.rows = rows; } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/constant/FlowableConstant.java package com.jeeplus.modules.flowable.constant; public class FlowableConstant { /** * 约定的发起者节点id 前缀 */ public final static String INITIATOR = "applyUserId";// 流程发起人变量 public final static String USERNAME = "userName"; //流程执行人 public final static String TITLE = "title"; //流程标题 public final static String SPECIAL_GATEWAY_BEGIN_SUFFIX = "_begin"; public final static String SPECIAL_GATEWAY_END_SUFFIX = "_end"; public final static String START_EVENT_LABEL = "开始"; public final static String START_EVENT_COMMENT = "发起流程"; public final static String END_EVENT_LABEL = "结束"; public final static String END_EVENT_COMMENT= "结束流程"; public final static String WAITING_EVENT_COMMENT= "等待审核"; public final static String SYSTEM_EVENT_COMMENT= "系统执行"; public final static String FLOW_ACTION = "_FLOW_ACTION_"; public final static String PROCESS_STATUS_CODE = "_process_status_code"; //流程状态码 public final static String PROCESS_STATUS_COMMENT= "_process_status_comment"; //流程状态描述 public static final String AFTER_ADDSIGN = "after"; //后加签 public static final String BEFORE_ADDSIGN = "before"; //前加签 } <file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/java/com/jeeplus/modules/database/datalink/service/DataSourceService.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.database.datalink.service; import java.util.List; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.database.datalink.entity.DataSource; import com.jeeplus.modules.sys.utils.DictUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.modules.database.datalink.mapper.DataSourceMapper; import org.springframework.web.util.HtmlUtils; /** * 数据库连接Service * * @author 刘高峰 * @version 2018-08-06 */ @Service @Transactional(readOnly = true) public class DataSourceService extends CrudService<DataSourceMapper, DataSource> { public DataSource get(String id) { return super.get(id); } public List<DataSource> findList(DataSource dataSource) { return super.findList(dataSource); } public Page<DataSource> findPage(Page page, DataSource dataSource) { return super.findPage(page, dataSource); } @Transactional(readOnly = false) public void save(DataSource dataSource) { super.save(dataSource); } @Transactional(readOnly = false) public void delete(DataSource dataSource) { super.delete(dataSource); } /** * 转换为JDBC连接 * * @param type * @param host * @param port * @param dbName * @return */ public String toUrl(String type, String host, int port, String dbName) { String template = DictUtils.getDictValue(type, "db_jdbc_url", "mysql"); if (template != null) { template = HtmlUtils.htmlUnescape(template); return template.replace("${host}", host).replace("${port}", port + "").replace("${db}", dbName); } return null; } /** * 获取JDBC驱动 * * @param type * @return */ public String getDriver(String type) { return DictUtils.getDictValue(type, "db_driver", "mysql"); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/moments/vo/ShareVo.java package com.jeeplus.modules.test.moments.vo; import com.jeeplus.ding.config.DingConf; import com.jeeplus.ding.io.DingNotice; import com.jeeplus.ding.utils.TimeUtil; import com.jeeplus.modules.test.comm.entity.ComFiles; import com.jeeplus.modules.test.moments.entity.Share; import lombok.Getter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; /** * @author: lh * @date: 2021/3/18 */ @Component @Getter public class ShareVo { @Autowired private DingConf dingConf; public ShareVo(){}; /** * 委员圈分享模板 * @return */ public DingNotice shareNotice(Share share,List<ComFiles> comFiles){ String text = "委员圈分享 \n\n " +">"+share.getContent()+" \n\n "; if(comFiles.size()>0){ for (ComFiles s: comFiles) { if(s.getType().equals("video")){ continue; }else{ text += "![screenshot]("+dingConf.getPATH()+s.getUrl()+")"; } } text += " \n\n "; } text += ">>来源@"+share.getCreateBy().getName()+" "+ TimeUtil.getCurrent(); return new DingNotice("markdown",text,"委员圈分享"); } } <file_sep>/jeeplus-plugins/jeeplus-search/src/main/java/com/jeeplus/modules/search/entity/SearchVo.java package com.jeeplus.modules.search.entity; import com.google.common.collect.Lists; import com.jeeplus.common.utils.excel.annotation.ExcelField; import com.jeeplus.core.persistence.DataEntity; import lombok.Data; import java.util.Date; /** * 模糊搜索Entity * @author lc * @version 2021-03-15 */ @Data public class SearchVo extends DataEntity<SearchVo> { private static final long serialVersionUID = 1L; private String name; // 名称 private String pathId; // 路径 private Integer type; // 类别,0标识流程设计,1标识动态表单 public SearchVo() { super(); } } <file_sep>/jeeplus-plugins/jeeplus-tools/src/main/java/com/jeeplus/modules/tools/web/HttpToolController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.tools.web; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.tools.utils.HttpToolUtils; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * 请求工具测试类 * * @author lgf * @version 2016-01-07 */ @RestController @RequestMapping("/http") public class HttpToolController extends BaseController { /** * 接口内部请求 * * @param * @throws Exception */ @GetMapping("/get") public Object getTest(String serverUrl, String requestBody ) { Map<String, String> map = new HashMap<String, String>(); String errInfo = "success", str = "", rTime = ""; try { long startTime = System.currentTimeMillis(); Map<String, String> params = new HashMap<String, String>(); if (requestBody != null && !requestBody.equals("")) { String[] paramList = requestBody.split("&"); for (String param : paramList) { if (param.split("=").length == 2) { params.put(param.split("=")[0], param.split("=")[1]); } else { params.put(param.split("=")[0], ""); } } } HttpToolUtils test = new HttpToolUtils(serverUrl, params); str = test.post(); long endTime = System.currentTimeMillis(); rTime = String.valueOf(endTime - startTime); } catch (Exception e) { errInfo = "error"; str = e.getMessage(); } return AjaxJson.success().put("errInfo", errInfo).put("result", str).put("rTime", rTime); } /** * 接口内部请求 * * @param * @throws Exception */ @GetMapping("/post") public Object postTest(HttpServletRequest request, HttpServletResponse response, Model model) { Map<String, String> map = new HashMap<String, String>(); String errInfo = "success", str = "", rTime = ""; try { long startTime = System.currentTimeMillis(); String s_url = request.getParameter("serverUrl");//请求起始时间_毫秒 String type = request.getParameter("requestMethod"); String requestBody = request.getParameter("requestBody"); URL url; if (type.equals("POST")) {//请求类型 POST or GET Map<String, String> params = new HashMap<String, String>(); if (requestBody != null && !requestBody.equals("")) { String[] paramList = requestBody.split("&"); for (String param : paramList) { if (param.split("=").length == 2) { params.put(param.split("=")[0], param.split("=")[1]); } else { params.put(param.split("=")[0], ""); } } } HttpToolUtils test = new HttpToolUtils(s_url, params); str = test.post(); } else { url = new URL(s_url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8")); //请求结束时间_毫秒 String temp = ""; while ((temp = in.readLine()) != null) { str = str + temp; } } long endTime = System.currentTimeMillis(); rTime = String.valueOf(endTime - startTime); } catch (Exception e) { errInfo = "error"; str = e.getMessage(); } map.put("errInfo", errInfo); //状态信息 map.put("result", str); //返回结果 map.put("rTime", rTime); //服务器请求时间 毫秒 return map; } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/utils/AddChildExecutionCmd.java package com.jeeplus.modules.flowable.utils; import org.flowable.common.engine.impl.interceptor.Command; import org.flowable.common.engine.impl.interceptor.CommandContext; import org.flowable.engine.impl.persistence.entity.ExecutionEntity; import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager; import org.flowable.engine.impl.util.CommandContextUtil; /* * 添加一个流程实例下面的执行实例 */ public class AddChildExecutionCmd implements Command<Void> { private ExecutionEntity parentExecutionEntity; public AddChildExecutionCmd(ExecutionEntity parentExecutionEntity) { this.parentExecutionEntity = parentExecutionEntity; } @Override public Void execute(CommandContext commandContext) { ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext); executionEntityManager.createChildExecution(parentExecutionEntity); return null; } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/web/UserController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.web; import java.io.File; import java.io.IOException; import java.util.List; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import com.jeeplus.config.properties.FileProperties; import com.jeeplus.modules.sys.entity.*; import com.jeeplus.modules.sys.security.util.JWTUtil; import com.jeeplus.modules.sys.service.RoleService; import com.jeeplus.modules.sys.service.UserService; import com.jeeplus.modules.sys.utils.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jeeplus.common.beanvalidator.BeanValidators; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.utils.FileUtils; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; /** * 用户Controller * * @author jeeplus * @version 2016-8-29 */ @RestController @RequestMapping("/sys/user") @Api(tags ="用户管理") public class UserController extends BaseController { @Autowired private UserService userService; @Autowired private RoleService roleService; @Autowired private FileProperties fileProperties; @ModelAttribute public User get(@RequestParam(required = false) String id) { if (StringUtils.isNotBlank(id)) { return userService.get(id); } else { return new User(); } } @GetMapping("queryById") @ApiOperation(value = "查询用户") public AjaxJson queryById(User user) { return AjaxJson.success().put("user", user); } @RequiresPermissions("sys:user:list") @GetMapping("list") @ApiOperation(value = "用户列表") public AjaxJson list(User user, HttpServletRequest request, HttpServletResponse response) { Page<User> page = userService.findPage(new Page<User>(request, response), user); return AjaxJson.success().put("page", page); } @RequiresPermissions(value = {"sys:user:add", "sys:user:edit"}, logical = Logical.OR) @PostMapping("save") @ApiOperation(value = "保存用户") public AjaxJson save(User user) { if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } // 如果新密码为空,则不更换密码 if (StringUtils.isNotBlank(user.getNewPassword())) { user.setPassword(userService.entryptPassword(user.getNewPassword())); } /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(user); if (StringUtils.isNotBlank(errMsg)) { return AjaxJson.error(errMsg); } if (!isCheckLoginName(user.getOldLoginName(), user.getLoginName())) { return AjaxJson.error("保存用户'" + user.getLoginName() + "'失败,登录名已存在!"); } // 角色数据有效性验证,过滤不在授权内的角色 List<Role> roleList = Lists.newArrayList(); List<String> roleIdList = user.getRoleIdList(); for (String roleId : roleIdList) { roleList.add(roleService.get(roleId)); } user.setRoleList(roleList); // 保存用户信息 userService.saveUser(user); // 清除当前用户缓存 if (user.getLoginName().equals(UserUtils.getUser().getLoginName())) { UserUtils.clearCache(); } return AjaxJson.success("保存用户'" + user.getLoginName() + "'成功!"); } /** * 批量删除用户 */ @ApiOperation(value = "删除用户") @RequiresPermissions("sys:user:del") @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] = ids.split(","); AjaxJson j = new AjaxJson(); if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } StringBuffer msg = new StringBuffer(); boolean success = true; for (String id : idArray) { User user = userService.get(id); if (UserUtils.getUser().getId().equals(user.getId())) { success = false; msg.append("["+user.getLoginName()+"]删除失败,不允许删除当前用户!<br/>"); } else if (User.isAdmin(user.getId())) { success = false; msg.append("["+user.getLoginName()+"]删除失败,不允许删除超级管理员!<br/>");//删除用户失败, 不允许删除超级管理员用户 } else { msg.append("["+user.getLoginName()+"]删除成功!<br/>"); userService.deleteUser(user);//删除用户成功 } } if(success){ return AjaxJson.success(msg.toString()); }else { return AjaxJson.error(msg.toString()); } } /** * 导出用户数据 * * @param user * @param request * @param response * @return */ @RequiresPermissions("sys:user:export") @GetMapping("export") @ApiOperation(value = "导出用户excel") public void exportFile(User user, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = "用户数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx"; Page<User> page = userService.findPage(new Page<User>(request, response, -1), user); new ExportExcel("用户数据", User.class).setDataList(page.getList()).write(response, fileName).dispose(); } /** * 导入用户数据 * * @param file * @param redirectAttributes * @return */ @RequiresPermissions("sys:user:import") @PostMapping("import") @ApiOperation(value = "导入用户excel") public AjaxJson importFile(MultipartFile file, RedirectAttributes redirectAttributes) { if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<User> list = ei.getDataList(User.class); for (User user : list) { try { if (isCheckLoginName("", user.getLoginName())) { user.setPassword(userService.entryptPassword("<PASSWORD>")); BeanValidators.validateWithException(validator, user); userService.saveUser(user); successNum++; } else { failureMsg.append("<br/>登录名 " + user.getLoginName() + " 已存在; "); failureNum++; } } catch (ConstraintViolationException ex) { failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败:"); List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": "); for (String message : messageList) { failureMsg.append(message + "; "); failureNum++; } } catch (Exception ex) { failureNum++; failureMsg.append("<br/>登录名 " + user.getLoginName() + " 导入失败:" + ex.getMessage()); } } if (failureNum > 0) { failureMsg.insert(0, ",失败 " + failureNum + " 条用户,导入信息如下:"); } return AjaxJson.success("已成功导入 " + successNum + " 条用户" + failureMsg); } catch (Exception e) { return AjaxJson.error("导入用户失败!失败信息:" + e.getMessage()); } } /** * 下载导入用户数据模板 * * @param response * @return */ @RequiresPermissions("sys:user:import") @GetMapping("import/template") @ApiOperation(value = "下载模板") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "用户数据导入模板.xlsx"; List<User> list = Lists.newArrayList(); list.add(UserUtils.getUser()); new ExportExcel("用户数据", User.class, 2).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导入模板下载失败!失败信息:" + e.getMessage()); } } private boolean isCheckLoginName(String oldLoginName, String loginName) { if (loginName != null && loginName.equals(oldLoginName)) { return true; } else if (loginName != null && userService.getUserByLoginName(loginName) == null) { return true; } return false; } /** * 用户信息显示编辑保存 * * @param user * @return */ @RequiresPermissions("user") @PostMapping("saveInfo") @ApiOperation(value = "修改个人资料") public AjaxJson infoEdit(User user) { User currentUser = UserUtils.getUser(); if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } if (user.getName() != null) currentUser.setName(user.getName()); if (user.getEmail() != null) currentUser.setEmail(user.getEmail()); if (user.getPhone() != null) currentUser.setPhone(user.getPhone()); if (user.getMobile() != null) currentUser.setMobile(user.getMobile()); if (user.getRemarks() != null) currentUser.setRemarks(user.getRemarks()); if (user.getSign() != null) currentUser.setSign(user.getSign()); userService.updateUserInfo(currentUser); return AjaxJson.success("修改个人资料成功!"); } /** * 用户头像显示编辑保存 * * @return * @throws IOException * @throws IllegalStateException */ @RequiresPermissions("user") @PostMapping("imageUpload") @ApiOperation(value = "上传头像") public AjaxJson imageUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) throws IllegalStateException, IOException { User currentUser = UserUtils.getUser(); // 判断文件是否为空 if (!file.isEmpty()) { if(fileProperties.isImage (file.getOriginalFilename ())){ // 文件保存路径 String realPath = FileKit.getAttachmentDir() + "sys/user/images/"; // 转存文件 FileUtils.createDirectory(realPath); file.transferTo(new File(realPath + file.getOriginalFilename())); currentUser.setPhoto(FileKit.getAttachmentUrl() + "sys/user/images/" + file.getOriginalFilename()); userService.updateUserInfo(currentUser); return AjaxJson.success("上传成功!").put("path", FileKit.getAttachmentUrl() + "sys/user/images/" + file.getOriginalFilename()); }else{ return AjaxJson.error ("请上传图片!"); } }else{ return AjaxJson.error ("文件不存在!"); } } /** * 返回用户信息 * * @return */ @RequiresPermissions("user") @GetMapping("info") @ApiOperation(value = "获取当前用户信息") public AjaxJson infoData() { return AjaxJson.success("获取个人信息成功!").put("role", UserUtils.getRoleList()).put("user", UserUtils.getUser()); } @RequiresPermissions("user") @PostMapping("savePwd") @ApiOperation(value = "修改密码") public AjaxJson savePwd(String oldPassword, String newPassword, Model model) { User user = UserUtils.getUser(); if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) { if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } if (UserService.validatePassword(oldPassword, user.getPassword())) { userService.updatePasswordById(user.getId(), user.getLoginName(), newPassword); return AjaxJson.success("修改密码成功!"); } else { return AjaxJson.error("修改密码失败,旧密码错误!"); } } return AjaxJson.error("参数错误!"); } /** * 保存签名 */ @ApiOperation(value = "用户签名") @PostMapping("saveSign") public AjaxJson saveSign(User user, boolean __ajax, HttpServletResponse response, Model model) throws Exception { AjaxJson j = new AjaxJson(); User currentUser = UserUtils.getUser(); currentUser.setSign(user.getSign()); userService.updateUserInfo(currentUser); return AjaxJson.success("设置签名成功!"); } @RequiresPermissions("user") @GetMapping("treeData") public List<Map<String, Object>> treeData(@RequestParam(required = false) String officeId, HttpServletResponse response) { List<Map<String, Object>> mapList = Lists.newArrayList(); List<User> list = userService.findUserByOfficeId(officeId); for (int i = 0; i < list.size(); i++) { User e = list.get(i); Map<String, Object> map = Maps.newHashMap(); map.put("id", "u_" + e.getId()); map.put("pId", officeId); map.put("name", StringUtils.replace(e.getName(), " ", "")); mapList.add(map); } return mapList; } /** * web端ajax验证手机号是否可以注册(数据库中不存在) */ @ApiOperation("验证手机号") @GetMapping("validateMobile") public AjaxJson validateMobile(String mobile, HttpServletResponse response, Model model) { User user = userService.findUniqueByProperty("mobile", mobile); if (user == null) { return AjaxJson.success().put("noExist", true); } else { return AjaxJson.success().put("noExist", false); } } @ApiOperation(value = "用户权限") @RequiresPermissions("user") @GetMapping("getPermissions") public Set<String> getPermissions() { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); String token = UserUtils.getToken(); String loginName = JWTUtil.getLoginName(token); User user = UserUtils.getByLoginName(loginName); if (user != null) { List<Menu> list = UserUtils.getMenuList(); for (Menu menu : list) { if (org.apache.commons.lang3.StringUtils.isNotBlank(menu.getPermission())) { // 添加基于Permission的权限信息 for (String permission : org.apache.commons.lang3.StringUtils.split(menu.getPermission(), ",")) { info.addStringPermission(permission); } } } // 添加用户权限 info.addStringPermission("user"); // 添加用户角色信息 for (Role role : user.getRoleList()) { info.addRole(role.getEnname()); } } return info.getStringPermissions(); } @GetMapping("getMenus") @RequiresPermissions("user") public AjaxJson getMenus() { AjaxJson j = new AjaxJson(); j.put("dictList", this.getDicts()); j.put("permissions", this.getPermissions()); j.put("menuList", MenuUtils.getMenus()); j.put("routerList", RouterUtils.getRoutersByMenu()); return j; } private Map<String, List<DictValue>> getDicts() { return DictUtils.getDictMap(); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/comm/mapper/ComFilesMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.comm.mapper; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.jeeplus.modules.test.comm.entity.ComFiles; import java.util.List; /** * 公共MAPPER接口 * @author lh * @version 2021-03-12 */ @Mapper @Repository public interface ComFilesMapper extends BaseMapper<ComFiles> { public List<ComFiles> findListBySourceAOwnerId(ComFiles comFiles); public int deleteBySource(ComFiles comFiles); }<file_sep>/jeeplus-plugins/jeeplus-form/src/main/java/com/jeeplus/modules/form/entity/Form.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.form.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import com.jeeplus.modules.database.datalink.entity.DataSource; /** * 数据表单Entity * @author 刘高峰 * @version 2019-12-24 */ public class Form extends DataEntity<Form> { private static final long serialVersionUID = 1L; private String code; // 表单编码 private String autoCreate; // 是否自动建表 private DataSource dataSource; // 数据库连接 private String name; // 表单名称 private String tableName; // 表名 private String source; // 表单结构 private String version; // 版本号 public Form() { super(); } public Form(String id){ super(id); } @ExcelField(title="表单编码", align=2, sort=1) public String getCode() { return code; } public void setCode(String code) { this.code = code; } @ExcelField(title="是否自动建表", dictType="yes_no", align=2, sort=2) public String getAutoCreate() { return autoCreate; } public void setAutoCreate(String autoCreate) { this.autoCreate = autoCreate; } @ExcelField(title="数据库连接", align=2, sort=3) public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } @ExcelField(title="表单名称", align=2, sort=4) public String getName() { return name; } public void setName(String name) { this.name = name; } @ExcelField(title="表名", align=2, sort=5) public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } @ExcelField(title="表单结构", align=2, sort=6) public String getSource() { return source; } public void setSource(String source) { this.source = source; } @ExcelField(title="版本号", align=2, sort=7) public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/onetomany/entity/TestDataMainForm.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.onetomany.entity; import com.jeeplus.modules.sys.entity.User; import javax.validation.constraints.NotNull; import com.jeeplus.modules.sys.entity.Office; import com.jeeplus.modules.sys.entity.Area; import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.List; import com.google.common.collect.Lists; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 票务代理Entity * @author liugf * @version 2021-01-05 */ @Data public class TestDataMainForm extends DataEntity<TestDataMainForm> { private static final long serialVersionUID = 1L; @NotNull(message="用户不能为空") @ExcelField(title="用户", fieldType=User.class, value="tuser.name", align=2, sort=1) private User tuser; // 用户 @NotNull(message="所属部门不能为空") @ExcelField(title="所属部门", fieldType=Office.class, value="office.name", align=2, sort=2) private Office office; // 所属部门 @NotNull(message="所属区域不能为空") @ExcelField(title="所属区域", fieldType=Area.class, value="area.name", align=2, sort=3) private Area area; // 所属区域 @ExcelField(title="名称", align=2, sort=4) private String name; // 名称 @ExcelField(title="性别", dictType="sex", align=2, sort=5) private String sex; // 性别 @ExcelField(title="身份证照片", align=2, sort=6) private String file; // 身份证照片 @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") @ExcelField(title="加入日期", align=2, sort=7) private Date inDate; // 加入日期 private Date beginInDate; // 开始 加入日期 private Date endInDate; // 结束 加入日期 private List<TestDataChild21> testDataChild21List = Lists.newArrayList(); // 子表列表 private List<TestDataChild22> testDataChild22List = Lists.newArrayList(); // 子表列表 private List<TestDataChild23> testDataChild23List = Lists.newArrayList(); // 子表列表 public TestDataMainForm() { super(); } public TestDataMainForm(String id){ super(id); } }<file_sep>/jeeplus-plugins/jeeplus-form/src/main/java/com/jeeplus/modules/form/utils/FormTableBuilder.java package com.jeeplus.modules.form.utils; import com.jeeplus.common.utils.IdGen; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.dialect.Dialect; import com.jeeplus.core.persistence.dialect.db.*; import com.jeeplus.modules.database.datalink.jdbc.DBPool; import com.jeeplus.modules.form.dto.Column; import com.jeeplus.modules.form.entity.Form; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.utils.UserUtils; import org.apache.ibatis.mapping.DatabaseIdProvider; import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; import java.text.SimpleDateFormat; import java.util.*; /** * 表单数据表生成 */ public class FormTableBuilder { private static String tablePrefix = "jp_form_"; private String tableName = ""; private JdbcTemplate jdbcTemplate; public FormTableBuilder(JdbcTemplate jdbcTemplate, String tableName) { this.jdbcTemplate = jdbcTemplate; this.tableName = tableName; } public static String getTablePrefix() { return tablePrefix; } /* 获取数据库类型 */ public static String getJdbcType(String enName){ String dbType; try{ dbType = SpringContextHolder.getBean(DatabaseIdProvider.class).getDatabaseId(DBPool.getInstance().getDataSource(enName).getDataSource()); }catch (Exception e){ dbType = "mysql"; } return dbType; } /* 获取方言 */ public static Dialect getDialect() { Dialect dialect = null; String dbType ; try{ dbType = SpringContextHolder.getBean(DatabaseIdProvider.class).getDatabaseId(SpringContextHolder.getBean(DataSource.class)); }catch (Exception e){ dbType = "mysql"; } if ("db2".equals(dbType)){ dialect = new DB2Dialect(); }else if("derby".equals(dbType)){ dialect = new DerbyDialect(); }else if("h2".equals(dbType)){ dialect = new H2Dialect(); }else if("hsql".equals(dbType)){ dialect = new HSQLDialect(); }else if("mysql".equals(dbType)){ dialect = new MySQLDialect(); }else if("oracle".equals(dbType)){ dialect = new OracleDialect(); }else if("postgre".equals(dbType)){ dialect = new PostgreSQLDialect(); }else if("mssql".equals(dbType) || "sqlserver".equals(dbType)){ dialect = new SQLServerDialect(); }else if("sybase".equals(dbType)){ dialect = new SybaseDialect(); } if (dialect == null) { throw new RuntimeException("mybatis dialect error."); } return dialect; } /** * 删除表格 * * @return */ public boolean dropTable() { if(StringUtils.isNotBlank(tableName)){ jdbcTemplate.execute(String.format("drop table if exists %s", tableName)); } return true; } public String executeInsert(String tableName, Map data, Map map) { //保存表单数据 String uuid = IdGen.uuid(); if (StringUtils.isNotBlank(tableName)) { //遍历参数,组装sql语句 String insertSql = "insert into " + tableName + "("; String insertSqlValue = " values("; for (Object name : data.keySet()) { if (map.get(name) == null) continue; insertSql += "" + name + ","; if (map.get(name).equals("slider") || map.get(name).equals("number") || map.get(name).equals("rate") || map.get(name).equals("switch")) { insertSqlValue += "" + data.get(name) + ","; } else { insertSqlValue += "'" + data.get(name) + "',"; } } User user = UserUtils.getUser(); if (StringUtils.isNotBlank(user.getId())){ if(this.getColumns().contains("create_by") && map.get("create_by") == null){ insertSql += "create_by,"; insertSqlValue += "'" + user.getId() + "',"; } if(this.getColumns().contains("update_by") && map.get("update_by") == null){ insertSql += "update_by,"; insertSqlValue += "'" + user.getId() + "',"; } } if(this.getColumns().contains("create_date") && map.get("create_date") == null) { insertSql += "create_date,"; insertSqlValue += "'" + formatDate(new Date()) + "',"; } if(this.getColumns().contains("update_date") && map.get("update_date") == null) { insertSql += "update_date,"; insertSqlValue += "'" + formatDate(new Date()) + "',"; } if(this.getColumns().contains("del_flag") && map.get("del_flag") == null) { insertSql += "del_flag,"; insertSqlValue += "'0',"; } insertSql += "id)" + insertSqlValue + "'" + uuid + "')"; jdbcTemplate.execute(insertSql); } return uuid; } public String formatDate(Date date) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //从前端或者自己模拟一个日期格式,转为String即可 return format.format(date); } /** * 删除表单内容 * * @return */ public void executeDelete(String tableName, String ids) { if (StringUtils.isNotBlank(tableName)) { String deleteSql = "delete from " + tableName + " where id in ( "; String idArra = ""; for (String id : ids.split(",")) { idArra = idArra + "'" + id + "',"; } idArra = idArra.substring(0, idArra.length() - 1); deleteSql = deleteSql + idArra + " ) "; jdbcTemplate.execute(deleteSql); } } /** * 删除外键删除表单内容 * * @return */ public void executeDeleteByForeignKey(String tableName, String ids, String foreignKey) { if (StringUtils.isNotBlank(tableName)) { String deleteSql = "delete from " + tableName + " where "+foreignKey+" in ( "; String idArra = ""; for (String id : ids.split(",")) { idArra = idArra + "'" + id + "',"; } idArra = idArra.substring(0, idArra.length() - 1); deleteSql = deleteSql + idArra + " ) "; jdbcTemplate.execute(deleteSql); } } /* 查询表单内容 */ public int executeQueryCountByForeignKey(String tableName, String foreignKey, String foreignValue){ String countSql = "select count(1) from "+tableName+" where "+foreignKey+" = '"+foreignValue+"'"; int count = jdbcTemplate.queryForObject(countSql, Integer.class); return count; } /* 查询表单内容 */ public Map executeQueryById(String tableName, String id){ String originalSql = "select * from "+tableName+" where id = '"+id+"'"; Map map = jdbcTemplate.queryForMap(originalSql); return map; } /** * 更新表单 * * @param data * @return */ public void executeUpdate(String tableName, Map data, Map map) { //保存表单数据 if (StringUtils.isNotBlank(tableName)) { String updateSql = "update " + tableName + " set "; boolean needUpdate = false; for (Object name : data.keySet()) { if (name.equals("id") || map.get(name) == null) continue; if (map.get(name).equals("slider") || map.get(name).equals("number") || map.get(name).equals("rate") || map.get(name).equals("switch")) { updateSql = updateSql + " " + name + " = " + data.get(name) + ","; } else { updateSql = updateSql + " " + name + " = '" + data.get(name) + "',"; } needUpdate = true; } User user = UserUtils.getUser(); if (StringUtils.isNotBlank(user.getId()) && map.get("update_by") == null){ if(this.getColumns().contains("update_by")){ updateSql = updateSql + " update_by = '" + user.getId() + "',"; } } if(this.getColumns().contains("update_date") && map.get("update_date") == null){ updateSql = updateSql + " update_date = '" + formatDate(new Date()) + "',"; } updateSql = updateSql.substring(0, updateSql.length() - 1); updateSql = updateSql + " where id = '" + data.get("id").toString() + "'"; if (needUpdate) { jdbcTemplate.execute(updateSql); } } } /** * 通过外键更新 * * @param data * @return */ public void executeUpdateByForeignKey(String tableName, Map data, Map map, String foreignKey) { //保存表单数据 if (StringUtils.isNotBlank(tableName)) { String updateSql = "update " + tableName + " set "; boolean needUpdate = false; for (Object name : data.keySet()) { if (name.equals("id") || name.equals(foreignKey) || map.get(name) == null) continue; if (map.get(name).equals("slider") || map.get(name).equals("number") || map.get(name).equals("rate") || map.get(name).equals("switch")) { updateSql = updateSql + " " + name + " = " + data.get(name) + ","; } else { updateSql = updateSql + " " + name + " = '" + data.get(name) + "',"; } needUpdate = true; } User user = UserUtils.getUser(); if (StringUtils.isNotBlank(user.getId())){ if(this.getColumns().contains("update_by")){ updateSql = updateSql + " update_by = '" + user.getId() + "',"; } } if(this.getColumns().contains("update_date")){ updateSql = updateSql + " update_date = '" + formatDate(new Date()) + "',"; } updateSql = updateSql.substring(0, updateSql.length() - 1); updateSql = updateSql + " where "+foreignKey+" = '" + data.get(foreignKey) + "'"; if (needUpdate) { jdbcTemplate.execute(updateSql); } } } public boolean createTable() { jdbcTemplate.execute(String.format("CREATE TABLE IF NOT EXISTS %s(`id` varchar(32) primary key comment '主键', `create_by` varchar(64) comment '创建人', `create_date` datetime comment '创建日期' , `update_by` varchar(64) comment '更新者', `update_date` datetime comment '更新日期' )", tableName)); return true; } public HashSet getColumns () { HashSet columns = new HashSet(); String sql = String.format("select * from %s", tableName); String[] str= jdbcTemplate.queryForRowSet(sql).getMetaData().getColumnNames(); for(int i = 0;i<str.length;i++){ columns.add(str[i]); } return columns; } public void modifyColumn(List<Column> columnList){ HashSet<String> newColumns = new HashSet(); HashMap<String, String> map = new HashMap(); HashMap<String, String> map2 = new HashMap(); HashSet<String> oldColumns = getColumns(); for(Column column:columnList){ newColumns.add(column.getModel()); map.put(column.getModel(),column.getType()); map2.put(column.getModel(), column.getName()); } for(String oldColumn: oldColumns){ if(!newColumns.contains(oldColumn) && !oldColumn.equals("id") && !oldColumn.equals("create_by") && !oldColumn.equals("create_date") && !oldColumn.equals("update_by") && !oldColumn.equals("update_date")){ jdbcTemplate.execute("alter table `"+tableName+"` drop column `"+oldColumn+"`" ); } } for(String newColumn : newColumns){ if(!oldColumns.contains(newColumn)){ String type = map.get(newColumn); String sql = "alter table `"+tableName+"` add column `"+newColumn+"`"; if(type.equals("slider") || type.equals("number") || type.equals("rate") ){ sql += " integer"; }else if(type.equals("switch")){ sql += " boolean"; }else if(type.equals("textarea") || type.equals("table") || type.equals("imgupload") || type.equals("fileupload") || type.equals("editor")){ sql += " text"; }else{ sql += " text"; } sql += " comment '"+ map2.get(newColumn) +"'"; jdbcTemplate.execute(sql); } } } /** * 创建表格 * * @return */ public boolean syncTable(List<Column> columnList) { if (this.createTable()) { this.modifyColumn(columnList); } return true; } public String getTableName() { return tableName; } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/comm/mapper/ComDingMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.comm.mapper; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.jeeplus.modules.test.comm.entity.ComDing; /** * 钉钉推送MAPPER接口 * @author lh * @version 2021-03-22 */ @Mapper @Repository public interface ComDingMapper extends BaseMapper<ComDing> { public ComDing getBySource(String sourceType,String source); }<file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/ding/io/DingWorkIo.java package com.jeeplus.ding.io; import com.dingtalk.api.request.OapiWorkrecordAddRequest; import com.jeeplus.ding.utils.TimeUtil; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author: lh * @date: 2021/3/10 */ @Setter @Getter public class DingWorkIo implements Serializable { public DingWorkIo(String userId,String title,OapiWorkrecordAddRequest.FormItemVo formItemVo,String url){ this.userId = userId; this.title = title; List<OapiWorkrecordAddRequest.FormItemVo> list = new ArrayList<>(); list.add(formItemVo); this.formItemVoList = list; this.url = url; createTime = TimeUtil.getUnixTime(); } public DingWorkIo(String userId,String title,List<OapiWorkrecordAddRequest.FormItemVo> formItemVo,String url){ this.userId = userId; this.title = title; this.formItemVoList = formItemVo; this.url = url; createTime = TimeUtil.getUnixTime(); } public DingWorkIo(){ createTime = TimeUtil.getUnixTime(); } public DingWorkIo(String userId,String title){ createTime = TimeUtil.getUnixTime(); this.userId = userId; this.title = title; } /** * 大主题 */ private String title; /** * 接收人id */ private String userId; /** * 跳转url(可pc端工作台打开) * @see "https://developers.dingtalk.com/document/app/message-link-description?spm=ding_open_doc.document.0.0.1e81c943ZYDqaC#section-7w8-4c2-9az" */ private String url = ""; /** * 表单列表 */ private List<OapiWorkrecordAddRequest.FormItemVo> formItemVoList = new ArrayList<>(); /** * 创建时间 (默认当前时间) */ private Long createTime; //===========================以下不必填============================== /** * PC端跳转URl */ private String pcUrl; /** * 发送人员id */ private String originatorUserId; /** * 来源名称 */ private String sourceName; /** * 待办的PC打开方式 * 2:在PC端打开 * 4:在浏览器打开 */ private Long pcOpenType; /** * 外部业务ID */ private String bizId; public void setVoList(String title, String content){ formItemVoList.add((new DingForm(title,content)).getVo()); } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/vo/SysConfigVo.java package com.jeeplus.modules.sys.vo; import lombok.Data; @Data public class SysConfigVo { /* 外观配置 */ private String defaultTheme;//默认主题 private String defaultLayout; private String productName;//产品名称 private String logo;//产品logo; } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/service/converter/json/FlowStartEventJsonConverter.java /* 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. */ package com.jeeplus.modules.flowable.service.converter.json; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; import org.flowable.bpmn.model.*; import org.flowable.editor.language.json.converter.StartEventJsonConverter; import java.util.List; import java.util.Map; /** * @author liugaofeng */ public class FlowStartEventJsonConverter extends StartEventJsonConverter{ @Override protected FlowElement convertJsonToElement(JsonNode elementNode, JsonNode modelNode, Map<String, JsonNode> shapeMap) { StartEvent startEvent = (StartEvent)super.convertJsonToElement(elementNode, modelNode, shapeMap); if (getPropertyValueAsString ("formType", elementNode) != null) { ExtensionAttribute attribute2 = new ExtensionAttribute (); attribute2.setName ("flowable:formType"); attribute2.setValue (getPropertyValueAsString ("formType", elementNode)); startEvent.addAttribute (attribute2); } return startEvent; } //将Element转为Json @Override protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) { super.convertElementToJson (propertiesNode, baseElement); if (baseElement instanceof StartEvent) { //读取自定义扩展属性 if (baseElement.getAttributes ().get ("formType") != null && baseElement.getAttributes ().get ("formType").size () > 0) { propertiesNode.put ("formType", baseElement.getAttributes ().get ("formType").get (0).getValue ()); } if (baseElement.getAttributes ().get ("formReadOnly") != null && baseElement.getAttributes ().get ("formReadOnly").size () > 0) { propertiesNode.put ("formReadOnly", baseElement.getAttributes ().get ("formReadOnly").get (0).getValue ()); } } } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/web/SysConfigController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.web; import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; import com.aliyuncs.exceptions.ClientException; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.MyBeanUtils; import com.jeeplus.common.utils.sms.SmsUtils; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.sys.entity.SysConfig; import com.jeeplus.modules.sys.service.SysConfigService; import com.jeeplus.modules.sys.vo.SysConfigVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 系统配置Controller * @author 刘高峰 * @version 2018-10-18 */ @RestController @RequestMapping("/sys/sysConfig") public class SysConfigController extends BaseController { @Autowired private SysConfigService sysConfigService; /** * 系统配置 */ @GetMapping("queryById") public AjaxJson queryById(HttpServletRequest request, HttpServletResponse response, Model model) { SysConfig config = sysConfigService.get("1"); return AjaxJson.success().put("config", config); } /** * 系统配置 */ @GetMapping("getConfig") public AjaxJson getConfig() { SysConfig config = sysConfigService.get("1"); SysConfigVo vo = new SysConfigVo (); vo.setDefaultLayout (config.getDefaultLayout ()); vo.setDefaultTheme (config.getDefaultTheme ()); vo.setLogo (config.getLogo ()); vo.setProductName (config.getProductName ()); return AjaxJson.success().put("config", vo); } @GetMapping("testSms") public AjaxJson testSms(@RequestParam("tel")String tel)throws ClientException { SendSmsResponse response = SmsUtils.sendSms(tel,"{code:123}"); if (response.getCode() != null && response.getCode().equals("OK")) { return AjaxJson.success("短信发送成功!"); }else { return AjaxJson.error("短信发送失败!"+ response.getMessage()); } } /** * 保存系统配置 */ @PostMapping("save") public AjaxJson save(SysConfig config)throws Exception { AjaxJson j = new AjaxJson(); if(jeePlusProperites.isDemoMode()){ return AjaxJson.error("演示模式,禁止修改!"); } if(config.getMultiAccountLogin() == null){ config.setMultiAccountLogin("0"); } SysConfig target = sysConfigService.get("1"); MyBeanUtils.copyBeanNotNull2Bean(config, target); target.setIsNewRecord(false); sysConfigService.save(target); return AjaxJson.success("保存系统配置成功").put("config", target); } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/mapper/NodeSettingMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.jeeplus.modules.extension.entity.NodeSetting; /** * 节点设置MAPPER接口 * @author 刘高峰 * @version 2021-01-11 */ @Mapper @Repository public interface NodeSettingMapper extends BaseMapper<NodeSetting> { public NodeSetting queryByDefIdAndTaskId(@Param("processDefId") String processDefId, @Param("taskDefId") String taskDefId); public NodeSetting queryByKey(@Param("processDefId") String processDefId, @Param("taskDefId") String taskDefId ,@Param ("key")String key); public void deleteByDefIdAndTaskId(NodeSetting nodeSetting); public void deleteByProcessDefId(NodeSetting nodeSetting); } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/service/FlowableModelService.java package com.jeeplus.modules.flowable.service; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Lists; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.extension.service.NodeSettingService; import com.jeeplus.modules.extension.service.TaskDefExtensionService; import com.jeeplus.modules.flowable.entity.FlowModel; import com.jeeplus.modules.flowable.mapper.FlowModelMapper; import org.apache.commons.lang3.StringUtils; import org.apache.http.NameValuePair; import org.apache.http.client.utils.URLEncodedUtils; import org.flowable.bpmn.BpmnAutoLayout; import org.flowable.bpmn.converter.BpmnXMLConverter; import org.flowable.bpmn.model.BpmnModel; import org.flowable.common.engine.api.FlowableException; import org.flowable.editor.language.json.converter.BpmnJsonConverter; import org.flowable.editor.language.json.converter.util.CollectionUtils; import org.flowable.engine.RepositoryService; import org.flowable.engine.repository.Deployment; import org.flowable.engine.repository.Model; import org.flowable.engine.repository.ProcessDefinition; import org.flowable.ui.common.model.ResultListDataRepresentation; import org.flowable.ui.common.service.exception.BadRequestException; import org.flowable.ui.common.util.XmlUtil; import org.flowable.ui.modeler.model.ModelRepresentation; import org.flowable.ui.modeler.service.FlowableModelQueryService; import org.flowable.ui.modeler.serviceapi.ModelService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.Charset; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; /** * 流出模型Service * @author liuruijun * @version 2018-08-02 */ @Service @Transactional(readOnly = true) public class FlowableModelService extends CrudService<FlowModelMapper, FlowModel> { @Autowired FlowProcessService flowProcessService; @Autowired private RepositoryService repositoryService; @Autowired private ModelService flowModelService; @Autowired private NodeSettingService nodeSettingService; @Autowired private TaskDefExtensionService taskDefExtensionService; @Autowired protected FlowableModelQueryService modelQueryService; protected BpmnXMLConverter bpmnXmlConverter = new BpmnXMLConverter(); protected BpmnJsonConverter bpmnJsonConverter = new BpmnJsonConverter(); public Page<FlowModel> findPage(Page<FlowModel> page, FlowModel flowModel) { return super.findPage(page, flowModel); } public FlowModel get(String id) { return super.get(new FlowModel(id)); } /** * 流程模型列表 */ public Page<FlowModel> getModels(Page<FlowModel> page, @RequestParam(required = false) String filter, @RequestParam(required = false) String sort, @RequestParam(required = false) Integer modelType, HttpServletRequest request) { ResultListDataRepresentation modelQuery = this.modelQueryService.getModels(filter, sort, modelType, request); String category = getParam(request,"category"); List<FlowModel> flowModelList = Lists.newArrayList(); for(Object o : modelQuery.getData()){ FlowModel flowModel = new FlowModel(); ModelRepresentation m = (ModelRepresentation)o; flowModel.setName(m.getName()); flowModel.setId(m.getId()); flowModel.setComment(m.getComment()); flowModel.setKey(m.getKey()); flowModel.setCreatedBy(m.getCreatedBy()); flowModel.setUpdateDate(m.getLastUpdated()); flowModel.setLastUpdated(m.getLastUpdated()); ProcessDefinition processDefinition = flowProcessService.getProcessDefinitionByKey(m.getKey()); Map pMap = new HashMap<>(); if(processDefinition != null){ String deploymentId = processDefinition.getDeploymentId(); Deployment deployment = repositoryService.createDeploymentQuery().deploymentId(deploymentId).singleResult(); pMap.put("id", processDefinition.getId()); if(StringUtils.isNotEmpty(category)){ if(!category.equals(processDefinition.getCategory())) continue; } pMap.put("category", processDefinition.getCategory()); pMap.put("key", processDefinition.getKey()); pMap.put("name", processDefinition.getName()); pMap.put("version", "V:" + processDefinition.getVersion()); pMap.put("resourceName", processDefinition.getResourceName()); pMap.put("diagramResourceName", processDefinition.getDiagramResourceName()); pMap.put("deploymentId", processDefinition.getDeploymentId()); pMap.put("suspended", processDefinition.isSuspended()); pMap.put("deploymentTime", deployment.getDeploymentTime()); } flowModel.setProcDef(pMap); flowModelList.add(flowModel); } page.setCount(flowModelList.size()); if (page.getMaxResults() != -1) { //分页 flowModelList = flowModelList.subList(page.getFirstResult(), page.getLastResult()); } page.setList(flowModelList); return page; } private String getParam(HttpServletRequest request,String name){ List<NameValuePair> params = URLEncodedUtils.parse(request.getQueryString(), Charset.forName("UTF-8")); String value = null; NameValuePair nameValuePair; if (params != null) { Iterator var7 = params.iterator(); while(var7.hasNext()) { nameValuePair = (NameValuePair)var7.next(); if (name.equalsIgnoreCase(nameValuePair.getName())) { value = nameValuePair.getValue(); } } } return value; } public String changeXmlToJson(String xml) { try { XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory(); InputStreamReader xmlIn = new InputStreamReader(new ByteArrayInputStream(xml.getBytes("UTF-8")), "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn); BpmnModel bpmnModel = this.bpmnXmlConverter.convertToBpmnModel(xtr); if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) { throw new BadRequestException("No process found in definition " ); } else { if (bpmnModel.getLocationMap().size() == 0) { BpmnAutoLayout bpmnLayout = new BpmnAutoLayout(bpmnModel); bpmnLayout.execute(); } ObjectNode modelNode = this.bpmnJsonConverter.convertToJson(bpmnModel); return modelNode.toString(); } } catch (BadRequestException var14) { throw var14; } catch (Exception var15) { throw new BadRequestException("Import failed for " + ", error message " + var15.getMessage()); } } /* * 根据Model部署流程 */ @Transactional(readOnly = false) public String deploy(String id, String category) { String message = ""; try { org.flowable.ui.modeler.domain.Model model = flowModelService.getModel(id); byte[] bpmnBytes = flowModelService.getBpmnXML(model); String processName = model.getName(); if (!StringUtils.endsWith(processName, ".bpmn20.xml")) { processName += ".bpmn20.xml"; } Deployment deployment = repositoryService.createDeployment() .addBytes(processName, bpmnBytes) .name(model.getName()) .key(model.getKey()) .deploy(); logger.debug("流程部署--------deploy:" + deployment ); List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery() .deploymentId(deployment.getId()).list(); // 设置流程分类 for (ProcessDefinition processDefinition : list) { if (StringUtils.isNotBlank(category)) { repositoryService.setProcessDefinitionCategory(processDefinition.getId(), category); } message += "部署成功,流程ID=" + processDefinition.getId() ; } if (list.size() == 0) { message = "部署失败,没有流程。"; } } catch (Exception e) { throw new FlowableException("设计模型图不正确,检查模型正确性,模型ID=" + id, e); } return message; } /** * 导出model的xml文件 * * @throws IOException */ public String export(String id, HttpServletResponse response) { try { // Model modelData = repositoryService.getModel(id); org.flowable.ui.modeler.domain.Model modelData = flowModelService.getModel(id); byte[] bpmnBytes = flowModelService.getBpmnXML(modelData); return new String(bpmnBytes); } catch (Exception e) { throw new FlowableException("导出model的xml文件失败,模型ID=" + id, e); } } /** * 更新Model分类 */ @Transactional(readOnly = false) public void updateCategory(String id, String category) { Model modelData = repositoryService.getModel(id); modelData.setCategory(category); repositoryService.saveModel(modelData); } /** * 删除模型 * * @param id * @return */ @Transactional(readOnly = false) public void delete(String id) { org.flowable.ui.modeler.domain.Model model = flowModelService.getModel(id); try { this.deleteDeployment(model.getKey()); this.flowModelService.deleteModel(model.getId()); taskDefExtensionService.deleteByProcessDefId(model.getKey()); nodeSettingService.deleteByProcessDefId(model.getKey()); } catch (Exception var4) { logger.error("Error while deleting: ", var4); throw new BadRequestException("Model cannot be deleted: " + id); } } /** * 级联删除流程定义 * * @param key * @return */ @Transactional(readOnly = false) public void deleteDeployment(String key) { ProcessDefinition processDefinition = flowProcessService.getProcessDefinitionByKey(key); if(processDefinition == null){ return; }else { try { repositoryService.deleteDeployment(processDefinition.getDeploymentId(), true); } catch (Exception var4) { logger.error("Error while deleting: ", var4); throw new BadRequestException("Process cannot be deleted: " + processDefinition.getDeploymentId()); } this.deleteDeployment(key); } } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/onetomany/web/TestDataMainFormController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.onetomany.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.test.onetomany.entity.TestDataMainForm; import com.jeeplus.modules.test.onetomany.service.TestDataMainFormService; /** * 票务代理Controller * @author liugf * @version 2021-01-05 */ @RestController @RequestMapping(value = "/test/onetomany/testDataMainForm") public class TestDataMainFormController extends BaseController { @Autowired private TestDataMainFormService testDataMainFormService; @ModelAttribute public TestDataMainForm get(@RequestParam(required=false) String id) { TestDataMainForm entity = null; if (StringUtils.isNotBlank(id)){ entity = testDataMainFormService.get(id); } if (entity == null){ entity = new TestDataMainForm(); } return entity; } /** * 票务代理列表数据 */ @RequiresPermissions("test:onetomany:testDataMainForm:list") @GetMapping("list") public AjaxJson list(TestDataMainForm testDataMainForm, HttpServletRequest request, HttpServletResponse response) { Page<TestDataMainForm> page = testDataMainFormService.findPage(new Page<TestDataMainForm>(request, response), testDataMainForm); return AjaxJson.success().put("page",page); } /** * 根据Id获取票务代理数据 */ @RequiresPermissions(value={"test:onetomany:testDataMainForm:view","test:onetomany:testDataMainForm:add","test:onetomany:testDataMainForm:edit"},logical=Logical.OR) @GetMapping("queryById") public AjaxJson queryById(TestDataMainForm testDataMainForm) { return AjaxJson.success().put("testDataMainForm", testDataMainForm); } /** * 保存票务代理 */ @RequiresPermissions(value={"test:onetomany:testDataMainForm:add","test:onetomany:testDataMainForm:edit"},logical=Logical.OR) @PostMapping("save") public AjaxJson save(TestDataMainForm testDataMainForm, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(testDataMainForm); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 testDataMainFormService.save(testDataMainForm);//保存 return AjaxJson.success("保存票务代理成功"); } /** * 批量删除票务代理 */ @RequiresPermissions("test:onetomany:testDataMainForm:del") @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ testDataMainFormService.delete(new TestDataMainForm(id)); } return AjaxJson.success("删除票务代理成功"); } /** * 导出excel文件 */ @RequiresPermissions("test:onetomany:testDataMainForm:export") @GetMapping("export") public AjaxJson exportFile(TestDataMainForm testDataMainForm, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "票务代理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<TestDataMainForm> page = testDataMainFormService.findPage(new Page<TestDataMainForm>(request, response, -1), testDataMainForm); new ExportExcel("票务代理", TestDataMainForm.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出票务代理记录失败!失败信息:"+e.getMessage()); } } /** * 导入Excel数据 */ @RequiresPermissions("test:onetomany:testDataMainForm:import") @PostMapping("import") public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<TestDataMainForm> list = ei.getDataList(TestDataMainForm.class); for (TestDataMainForm testDataMainForm : list){ try{ testDataMainFormService.save(testDataMainForm); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条票务代理记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条票务代理记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入票务代理失败!失败信息:"+e.getMessage()); } } /** * 下载导入票务代理数据模板 */ @RequiresPermissions("test:onetomany:testDataMainForm:import") @GetMapping("import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "票务代理数据导入模板.xlsx"; List<TestDataMainForm> list = Lists.newArrayList(); new ExportExcel("票务代理数据", TestDataMainForm.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } }<file_sep>/jeeplus-plugins/jeeplus-form/src/main/java/com/jeeplus/modules/form/service/GenerateFormService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.form.service; import com.alibaba.fastjson.JSON; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.persistence.dialect.Dialect; import com.jeeplus.core.persistence.interceptor.SQLHelper; import com.jeeplus.database.datasource.annotation.DS; import com.jeeplus.modules.database.datalink.jdbc.DBPool; import com.jeeplus.modules.form.dto.Column; import com.jeeplus.modules.form.dto.Relation; import com.jeeplus.modules.form.entity.Form; import com.jeeplus.modules.form.utils.FormJsonUtils; import com.jeeplus.modules.form.utils.FormOracleTableBuilder; import com.jeeplus.modules.form.utils.FormTableBuilder; import com.jeeplus.modules.sys.entity.DataRule; import com.jeeplus.modules.sys.service.AreaService; import com.jeeplus.modules.sys.service.OfficeService; import com.jeeplus.modules.sys.utils.UserUtils; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.sql.Timestamp; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 数据表单Service * * @author 刘高峰 * @version 2019-12-24 */ @Service @Transactional(readOnly = true) public class GenerateFormService { @Autowired private JdbcTemplate jdbcTemplate; @Autowired private OfficeService officeService; @Autowired private AreaService areaService; /** * 更新表单 * * @param data * @return */ @Transactional(readOnly = false) @DS("#form.dataSource.enName") public void executeUpdate(Form form, JSONObject data, HashMap map) { //保存表单数据 FormTableBuilder formTableBuilder; String enName = form.getDataSource().getEnName(); String dbType = FormTableBuilder.getJdbcType(enName); JdbcTemplate jdbcTemplate = DBPool.getInstance().getDataSource(enName); if (dbType.equals("oracle")) { formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName()); } else { formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName()); } List<Relation> relations = FormJsonUtils.newInstance().getRelations(form.getSource ()); if(relations.size() == 0) { // 如果是单表 formTableBuilder.executeUpdate(form.getTableName(), data, map); }else{//如果是多表 // 主表 Map mainMap = new HashMap(); Map mainData = new HashMap(); for (Object name : data.keySet()) { if (!name.toString().contains("->")) { mainMap.put(name, map.get(name)); mainData.put(name, data.get(name)); } } formTableBuilder.executeUpdate(form.getTableName(), mainData, mainMap); // 多表关联 for (Relation relation : relations) { if("table".equals(relation.getType())){ continue; } Map childMap = new HashMap(); Map dataMap = new HashMap(); for (Object name : data.keySet()) { if (name.toString().startsWith(relation.getChildTableName() + "->")) { childMap.put(name.toString().substring((relation.getChildTableName() + "->").length()), map.get(name)); dataMap.put(name.toString().substring((relation.getChildTableName() + "->").length()), data.get(name)); } } String foreignKey = relation.getForeignKey().split("\\.")[1]; childMap.put(foreignKey, "input"); dataMap.put(foreignKey, data.get(relation.getPrimaryKey())); int count = formTableBuilder.executeQueryCountByForeignKey(relation.getChildTableName(), foreignKey, dataMap.get(foreignKey).toString()); if(count == 0){ formTableBuilder.executeInsert(relation.getChildTableName(), dataMap, childMap); }else { formTableBuilder.executeUpdateByForeignKey(relation.getChildTableName(), dataMap, childMap, foreignKey); } } // 子表 for (Relation relation : relations) { if("table".equals(relation.getType())){ String foreignKey = relation.getForeignKey().split("\\.")[1]; for (Object name : data.keySet()) { if (name.toString().equals("childTable->"+relation.getChildTableName())) { JSONArray childArray = data.getJSONArray("childTable->" + relation.getChildTableName()); List<Column> fieldArra = FormJsonUtils.newInstance().getFieldsByTable(form.getSource (), "childTable->"+relation.getChildTableName()); Map childMap = new HashMap(); for(Column column: fieldArra){ childMap.put(column.getModel().split("->")[1], column.getType()); } // 统一设置外键 childMap.put(foreignKey, "input"); String foreignValue = data.get(relation.getPrimaryKey()).toString(); // 删除所有数据 formTableBuilder.executeDeleteByForeignKey(relation.getChildTableName(), foreignValue, foreignKey); // 逐条插入子表 for(int i=0; i<childArray.size(); i++){ JSONObject columnData = childArray.getJSONObject(i); Map dataMap = new HashMap(); dataMap.put(foreignKey, foreignValue); for(Column column: fieldArra){ dataMap.put(column.getModel().split("->")[1], columnData.get(column.getModel())); } formTableBuilder.executeInsert(relation.getChildTableName(), dataMap, childMap); } } } } } } } /** * 保存表单 * * @param data * @return */ @Transactional(readOnly = false) @DS("#form.dataSource.enName") public void executeInsert(Form form, JSONObject data, Map map) { //保存表单数据 FormTableBuilder formTableBuilder; String enName = form.getDataSource().getEnName(); String dbType = FormTableBuilder.getJdbcType(enName); JdbcTemplate jdbcTemplate = DBPool.getInstance().getDataSource(enName); if (dbType.equals("oracle")) { formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName()); } else { formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName()); } List<Relation> relations = FormJsonUtils.newInstance().getRelations(form.getSource ()); if(relations.size() == 0){ // 如果是单表 for (Object name : data.keySet()) { if (map.get(name) == null) continue; } formTableBuilder.executeInsert(form.getTableName(), data, map); }else { // 如果是多表关联 // 主表 Map mainMap = new HashMap(); Map mainData = new HashMap(); for (Object name : data.keySet()) { if (!name.toString().contains("->")) { mainMap.put(name, map.get(name)); mainData.put(name, data.get(name)); } } String id = formTableBuilder.executeInsert(form.getTableName(), mainData, mainMap); // 多表关联 for (Relation relation : relations) { if("table".equals(relation.getType())){// 排除子表 continue; } Map childMap = new HashMap(); Map dataMap = new HashMap(); for (Object name : data.keySet()) { if (name.toString().startsWith(relation.getChildTableName() + "->")) { childMap.put(name.toString().substring((relation.getChildTableName() + "->").length()), map.get(name)); dataMap.put(name.toString().substring((relation.getChildTableName() + "->").length()), data.get(name)); } } String foreignKey = relation.getForeignKey().split("\\.")[1]; if (relation.getPrimaryKey().equals("id")) { childMap.put(foreignKey, "input"); dataMap.put(foreignKey, id); } else { childMap.put(foreignKey, "input"); dataMap.put(foreignKey, data.get(relation.getPrimaryKey())); } formTableBuilder.executeInsert(relation.getChildTableName(), dataMap, childMap); } // 子表 for (Relation relation : relations) { if("table".equals(relation.getType())){ String foreignKey = relation.getForeignKey().split("\\.")[1]; for (Object name : data.keySet()) { if (name.toString().equals("childTable->"+relation.getChildTableName())) { JSONArray childArray = data.getJSONArray("childTable->" + relation.getChildTableName()); List<Column> fieldArra = FormJsonUtils.newInstance().getFieldsByTable(form.getSource (), "childTable->"+relation.getChildTableName()); Map childMap = new HashMap(); for(Column column: fieldArra){ childMap.put(column.getModel().split("->")[1], column.getType()); } String foreignValue; // 统一设置外键 if (relation.getPrimaryKey().equals("id")) { childMap.put(foreignKey, "input"); foreignValue = id; } else { childMap.put(foreignKey, "input"); foreignValue = data.get(relation.getPrimaryKey()).toString(); } // 逐条插入子表 for(int i=0; i<childArray.size(); i++){ JSONObject columnData = childArray.getJSONObject(i); Map dataMap = new HashMap(); dataMap.put(foreignKey, foreignValue); for(Column column: fieldArra){ dataMap.put(column.getModel().split("->")[1], columnData.get(column.getModel())); } formTableBuilder.executeInsert(relation.getChildTableName(), dataMap, childMap); } } } } } } } /** * 删除表单内容 * * @return */ @Transactional(readOnly = false) @DS("#form.dataSource.enName") public void executeDelete(Form form, String ids) { FormTableBuilder formTableBuilder; String enName = form.getDataSource().getEnName(); String dbType = FormTableBuilder.getJdbcType(enName); JdbcTemplate jdbcTemplate = DBPool.getInstance().getDataSource(enName); if (dbType.equals("oracle")) { formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName()); } else { formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName()); } List<Relation> relations = FormJsonUtils.newInstance().getRelations(form.getSource ()); if(relations.size() == 0){ // 如果是单表 formTableBuilder.executeDelete(form.getTableName(), ids); }else { // 如果是多表关联 // 子表 for (Relation relation : relations) { String keys = ""; if(!relation.getPrimaryKey().equalsIgnoreCase("id")){ String querySql = "select "+relation.getPrimaryKey()+ " from " + form.getTableName() + " where id in ( "; String idArra = ""; for (String id : ids.split(",")) { idArra = idArra + "'" + id + "',"; } idArra = idArra.substring(0, idArra.length() - 1); querySql = querySql + idArra + " ) "; List<Map<String, Object>> mapList = jdbcTemplate.queryForList(querySql); for (Map map : mapList){ String key = map.get(relation.getPrimaryKey()).toString(); keys = keys + key + ","; } keys = keys.substring(0, keys.length()-1); }else{ keys = ids; } formTableBuilder.executeDeleteByForeignKey(relation.getChildTableName(), keys, relation.getForeignKey().split("\\.")[1]); } // 主表 formTableBuilder.executeDelete(form.getTableName(), ids); } } /** * 查询表单内容 * * @return */ @Transactional(readOnly = true) @DS("#form.dataSource.enName") public Map executeQueryById(Form form, String id) { FormTableBuilder formTableBuilder; String enName = form.getDataSource().getEnName(); String dbType = FormTableBuilder.getJdbcType(enName); JdbcTemplate jdbcTemplate = DBPool.getInstance().getDataSource(enName); if (dbType.equals("oracle")) { formTableBuilder = new FormOracleTableBuilder(jdbcTemplate, form.getTableName()); } else { formTableBuilder = new FormTableBuilder(jdbcTemplate, form.getTableName()); } List<Relation> relations = FormJsonUtils.newInstance().getRelations(form.getSource ()); if(relations.size() == 0){ // 如果是单表 return formTableBuilder.executeQueryById(form.getTableName(), id); }else { // 如果是多表关联 String originalSql = "select "; List<Column> fields = FormJsonUtils.newInstance().getFields(form.getSource ()); HashMap<String, String> typeMap = new HashMap(); for (Column column : fields) { typeMap.put(column.getModel(), column.getType()); } for (Column field : fields) { if(field.getModel().startsWith("childTable->")){ continue; } if(field.getModel().contains("->")){ originalSql = originalSql + field.getModel().replace ("->", ".") + " as '" + field.getModel() + "',"; }else{ originalSql = originalSql + form.getTableName()+ "."+ field.getModel() + " as '" + field.getModel() + "',"; } } originalSql = originalSql.substring(0, originalSql.length() - 1); originalSql = originalSql + " from " + form.getTableName(); // 多表关联关系 for (Relation relation : relations) { if("table".equals(relation.getType())){ continue; } originalSql = originalSql + " left join " + relation.getChildTableName() + " on " + form.getTableName() + "." + relation.getPrimaryKey() + " = " + relation.getForeignKey(); } originalSql = originalSql + " where " + form.getTableName() + ".id = '" + id + "'"; Map map = jdbcTemplate.queryForMap(originalSql); map.put("id", id);// 主键存储。 //处理日期 for (Object key : map.keySet()) { if ("date".equals(typeMap.get(key)) || "time".equals(typeMap.get(key))) { if (map.get(key) != null) { if(map.get (key) instanceof Timestamp){ long time = ((Timestamp) map.get (key)).getTime ()/1000; map.put (key, DateUtils.long2string (time)); } } } } // 子表 for (Relation relation : relations) { if("table".equals(relation.getType())){ String foreignKey = relation.getForeignKey().split("\\.")[1]; String childSql = "select "; List<Column> childTableFieldArra = FormJsonUtils.newInstance().getFieldsByTable(form.getSource (), "childTable->"+relation.getChildTableName()); for(Column column: childTableFieldArra){ childSql = childSql + column.getModel().split("->")[1] + " as '" + column.getModel() + "',"; } childSql = childSql.substring(0, childSql.length()-1); childSql = childSql + " from "+ relation.getChildTableName() +" where "+foreignKey+" = '"+map.get(relation.getPrimaryKey())+"'"; List<Map<String, Object>> childList = jdbcTemplate.queryForList(childSql); //处理日期 HashMap<String, String> childTableTypeMap = new HashMap(); for (Column column : childTableFieldArra) { childTableTypeMap.put(column.getModel(), column.getType()); } for (Map<String, Object> childMap : childList) { for (String key : childMap.keySet()) { if ("date".equals(childTableTypeMap.get(key)) || "time".equals(childTableTypeMap.get(key))) { if (childMap.get(key) != null) { if(childMap.get (key) instanceof Timestamp){ long time = ((Timestamp) childMap.get (key)).getTime ()/1000; childMap.put (key, DateUtils.long2string (time)); } } } } } map.put("childTable->"+relation.getChildTableName()+"", JSON.toJSONString(childList)); } } return map; } } @DS("#form.dataSource.enName") public Page<Map> executeFindPage(Page page, Form form, String params) { String originalSql = ""; List<Relation> relations = FormJsonUtils.newInstance().getRelations(form.getSource ()); if (relations.size() == 0) {// 包含子表 originalSql = "select * from " + form.getTableName() + " "; } else {// 如果是多表关联 originalSql = "select "+form.getTableName()+".id,"; List<Column> fields = FormJsonUtils.newInstance().getFields(form.getSource ()); for (Column field : fields) { if(field.getModel().startsWith("childTable->")){//排除子表 continue; } if(field.getModel().contains("->")){ originalSql = originalSql + field.getModel().replace ("->", ".") + " as '" + field.getModel() + "',"; }else{ originalSql = originalSql + form.getTableName()+ "." + field.getModel() + " as '" + field.getModel() + "',"; } } originalSql = originalSql.substring(0, originalSql.length() - 1); originalSql = originalSql + " from " + form.getTableName(); // 子表 for (Relation relation : relations) { if("table".equals(relation.getType())){// 排除子表 continue; } originalSql = originalSql + " left join " + relation.getChildTableName() + " on " + form.getTableName() + "." + relation.getPrimaryKey() + " = " + relation.getForeignKey(); } } Map<String, String> paramsMap = JSON.parseObject(params, Map.class); List<Column> fieldArra = FormJsonUtils.newInstance().getFields(form.getSource ()); HashMap<String, String> typeMap = new HashMap(); for (Column column : fieldArra) { typeMap.put(column.getModel(), column.getType()); } if (paramsMap.size() > 0) { if (StringUtils.isNotBlank(dataRuleFilter(form))) { originalSql = originalSql + " where 1=1 " + dataRuleFilter(form) + " and "; } else { originalSql = originalSql + " where "; } for (String key : paramsMap.keySet()) { if(StringUtils.isNotBlank(String.valueOf(paramsMap.get(key)))){ originalSql = originalSql + " " + key + " like " + "'%" + String.valueOf(paramsMap.get(key)) + "%' and "; } } originalSql = originalSql.substring(0, originalSql.length() - 6); } else if (StringUtils.isNotBlank(dataRuleFilter(form))) { originalSql = originalSql + " where 1=1 " + dataRuleFilter(form); } if (StringUtils.isNotBlank(page.getOrderBy())) { originalSql = originalSql + " order by " + page.getOrderBy(); } Dialect dialect = FormTableBuilder.getDialect(); final String countSql = "select count(1) from (" + dialect.getCountString(originalSql) + ") tmp_count"; int count = jdbcTemplate.queryForObject(countSql, Integer.class); page.setCount(count); String pageSql = SQLHelper.generatePageSql(originalSql, page, dialect); List<Map<String, Object>> mapList = jdbcTemplate.queryForList(pageSql); for (Map<String, Object> map : mapList) { for (String key : map.keySet()) { if ("user".equals(typeMap.get(key))) { if (map.get(key) != null && UserUtils.get(map.get(key).toString()) != null) { map.put(key, UserUtils.get(map.get(key).toString()).getName()); } } if ("office".equals(typeMap.get(key))) { if (map.get(key) != null && officeService.get(map.get(key).toString()) != null) { map.put(key, officeService.get(map.get(key).toString()).getName()); } } if ("area".equals(typeMap.get(key))) { if (map.get(key) != null && areaService.get(map.get(key).toString()) != null) { map.put(key, areaService.get(map.get(key).toString()).getName()); } } if ("date".equals(typeMap.get(key)) || "time".equals(typeMap.get(key))) { if (map.get(key) != null) { if(map.get (key) instanceof Timestamp){ long time = ((Timestamp) map.get (key)).getTime ()/1000; map.put (key, DateUtils.long2string (time)); } } } } } page.setCount(count); page.setList(mapList); return page; } public static String dataRuleFilter(Form form) { if (UserUtils.getUser() == null || StringUtils.isBlank(UserUtils.getUser().getId())) { return ""; } form.setCurrentUser(UserUtils.getUser()); List<DataRule> dataRuleList = UserUtils.getDataRuleList(); // 如果是超级管理员,则不过滤数据 if (dataRuleList.size() == 0) { return ""; } // 数据范围 StringBuilder sqlString = new StringBuilder(); for (DataRule dataRule : dataRuleList) { if (form.getTableName().equals(dataRule.getClassName())) { sqlString.append(dataRule.getDataScopeSql()); } } return sqlString.toString(); } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/web/AreaController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.web; import com.google.common.collect.Lists; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.sys.entity.Area; import com.jeeplus.modules.sys.service.AreaService; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 区域Controller * * @author jeeplus * @version 2016-5-15 */ @RestController @RequestMapping("/sys/area") public class AreaController extends BaseController { @Autowired private AreaService areaService; @ModelAttribute("area") public Area get(@RequestParam(required = false) String id) { if (StringUtils.isNotBlank(id)) { return areaService.get(id); } else { return new Area(); } } @RequiresPermissions("sys:area:list") @GetMapping("list") public AjaxJson list(Area area) { return AjaxJson.success().put("list", areaService.findAll()); } @RequiresPermissions(value = {"sys:area:view", "sys:area:add", "sys:area:edit"}, logical = Logical.OR) @GetMapping("queryById") public AjaxJson queryById(Area area) { return AjaxJson.success().put("area", area); } @RequiresPermissions(value = {"sys:area:add", "sys:area:edit"}, logical = Logical.OR) @PostMapping("save") public AjaxJson save(Area area, Model model) { if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(area); if (StringUtils.isNotBlank(errMsg)) { return AjaxJson.error(errMsg); } areaService.save(area); return AjaxJson.success("保存成功!").put("area", area); } @RequiresPermissions("sys:area:del") @DeleteMapping("delete") public AjaxJson delete(Area area) { AjaxJson j = new AjaxJson(); if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } areaService.delete(area); return AjaxJson.success("删除区域成功!"); } /** * 获取区域JSON数据。 * * @param extId 排除的ID * @return */ @RequiresPermissions("user") @GetMapping("treeData") public AjaxJson treeData(@RequestParam(required = false) String extId) { List<Area> list = areaService.findAll(); List rootTree = areaService.formatListToTree (new Area ("0"),list, extId ); return AjaxJson.success().put("treeData", rootTree); } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/entity/FlowButton.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 按钮设置Entity * @author 刘高峰 * @version 2020-12-23 */ @Data public class FlowButton extends DataEntity<FlowButton> { private static final long serialVersionUID = 1L; private String name; // 按钮名称 private String code; // 编码 private String isHide; // 是否隐藏 private String next; // 下一节点审核人 private Integer sort; // 排序 private TaskDefExtension taskDef; // 任务节点外键 父类 public FlowButton() { super(); } public FlowButton(String id){ super(id); } public FlowButton(TaskDefExtension taskDef){ this.taskDef = taskDef; } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/utils/DeleteChildExecutionCmd.java package com.jeeplus.modules.flowable.utils; import org.flowable.common.engine.impl.interceptor.Command; import org.flowable.common.engine.impl.interceptor.CommandContext; import org.flowable.engine.impl.persistence.entity.ExecutionEntity; import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager; import org.flowable.engine.impl.util.CommandContextUtil; /* * 删除执行实例 */ public class DeleteChildExecutionCmd implements Command<Void> { private ExecutionEntity child; public DeleteChildExecutionCmd(ExecutionEntity child) { this.child = child; } @Override public Void execute(CommandContext commandContext) { ExecutionEntityManager executionEntityManager = CommandContextUtil.getExecutionEntityManager(commandContext); executionEntityManager.delete(child,true); return null; } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/tree/service/TestTreeService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.tree.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.service.TreeService; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.modules.test.tree.entity.TestTree; import com.jeeplus.modules.test.tree.mapper.TestTreeMapper; /** * 组织机构Service * @author lgf * @version 2021-01-05 */ @Service @Transactional(readOnly = true) public class TestTreeService extends TreeService<TestTreeMapper, TestTree> { public TestTree get(String id) { return super.get(id); } public List<TestTree> findList(TestTree testTree) { if (StringUtils.isNotBlank(testTree.getParentIds())){ testTree.setParentIds(","+testTree.getParentIds()+","); } return super.findList(testTree); } @Transactional(readOnly = false) public void save(TestTree testTree) { super.save(testTree); } @Transactional(readOnly = false) public void delete(TestTree testTree) { super.delete(testTree); } }<file_sep>/README.md # jeep http://www.jeeplus.org/blog/user/product <EMAIL> sckr2002 <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/cppcc/web/ComDataController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.cppcc.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.test.cppcc.entity.ComData; import com.jeeplus.modules.test.cppcc.service.ComDataService; /** * 政协通讯Controller * @author lc * @version 2021-03-15 */ @RestController @RequestMapping(value = "/cppcc/communication/comData") @Api(tags = "政协通讯") public class ComDataController extends BaseController { @Autowired private ComDataService comDataService; @ModelAttribute public ComData get(@RequestParam(required=false) String id) { ComData entity = null; if (StringUtils.isNotBlank(id)){ entity = comDataService.get(id); } if (entity == null){ entity = new ComData(); } return entity; } /** * 政协通讯管理列表数据 */ @RequiresPermissions("cppcc:communication:comData:list") @GetMapping("list") @ApiOperation(value = "政协通讯列表") public AjaxJson list(ComData comData, HttpServletRequest request, HttpServletResponse response) { Page<ComData> page = comDataService.findPage(new Page<ComData>(request, response), comData); return AjaxJson.success().put("page",page); } /** * 根据Id获取政协通讯管理数据 */ @RequiresPermissions(value={"cppcc:communication:comData:view","cppcc:communication:comData:add","cppcc:communication:comData:edit"},logical=Logical.OR) @GetMapping("queryById") @ApiOperation(value = "根据Id获取政协通讯管理数据") public AjaxJson queryById(ComData comData) { return AjaxJson.success().put("comData", comData); } /** * 保存政协通讯管理 */ @RequiresPermissions(value={"cppcc:communication:comData:add","cppcc:communication:comData:edit"},logical=Logical.OR) @PostMapping("save") @ApiOperation(value = "新建政协通讯以及评论数据") public AjaxJson save(ComData comData, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(comData); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 comDataService.save(comData);//保存 return AjaxJson.success("保存政协通讯管理成功"); } /** * 批量删除政协通讯管理 */ @RequiresPermissions("cppcc:communication:comData:del") @DeleteMapping("delete") @ApiOperation(value = "删除政协通讯以及评论数据") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ comDataService.delete(new ComData(id)); } return AjaxJson.success("删除政协通讯管理成功"); } /** * 导出excel文件 */ @RequiresPermissions("cppcc:communication:comData:export") @GetMapping("export") public AjaxJson exportFile(ComData comData, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "政协通讯管理"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<ComData> page = comDataService.findPage(new Page<ComData>(request, response, -1), comData); new ExportExcel("政协通讯管理", ComData.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出政协通讯管理记录失败!失败信息:"+e.getMessage()); } } /** * 导入Excel数据 */ @RequiresPermissions("cppcc:communication:comData:import") @PostMapping("import") public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<ComData> list = ei.getDataList(ComData.class); for (ComData comData : list){ try{ comDataService.save(comData); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条政协通讯管理记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条政协通讯管理记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入政协通讯管理失败!失败信息:"+e.getMessage()); } } /** * 下载导入政协通讯管理数据模板 */ @RequiresPermissions("cppcc:communication:comData:import") @GetMapping("import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "政协通讯管理数据导入模板.xlsx"; List<ComData> list = Lists.newArrayList(); new ExportExcel("政协通讯管理数据", ComData.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/video/web/MemberController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.video.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.test.video.entity.Member; import com.jeeplus.modules.test.video.service.MemberService; /** * 参与人Controller * @author lh * @version 2021-03-17 */ @RestController @RequestMapping(value = "/test/video/member") public class MemberController extends BaseController { @Autowired private MemberService memberService; @ModelAttribute public Member get(@RequestParam(required=false) String id) { Member entity = null; if (StringUtils.isNotBlank(id)){ entity = memberService.get(id); } if (entity == null){ entity = new Member(); } return entity; } /** * 参与人列表数据 */ @RequiresPermissions("test:video:member:list") @GetMapping("list") public AjaxJson list(Member member, HttpServletRequest request, HttpServletResponse response) { Page<Member> page = memberService.findPage(new Page<Member>(request, response), member); return AjaxJson.success().put("page",page); } /** * 根据Id获取参与人数据 */ @RequiresPermissions(value={"test:video:member:view","test:video:member:add","test:video:member:edit"},logical=Logical.OR) @GetMapping("queryById") public AjaxJson queryById(Member member) { return AjaxJson.success().put("member", member); } /** * 保存参与人 */ @RequiresPermissions(value={"test:video:member:add","test:video:member:edit"},logical=Logical.OR) @PostMapping("save") public AjaxJson save(Member member, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(member); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 memberService.save(member);//保存 return AjaxJson.success("保存参与人成功"); } /** * 批量删除参与人 */ @RequiresPermissions("test:video:member:del") @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ memberService.delete(new Member(id)); } return AjaxJson.success("删除参与人成功"); } /** * 导出excel文件 */ @RequiresPermissions("test:video:member:export") @GetMapping("export") public AjaxJson exportFile(Member member, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "参与人"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<Member> page = memberService.findPage(new Page<Member>(request, response, -1), member); new ExportExcel("参与人", Member.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出参与人记录失败!失败信息:"+e.getMessage()); } } /** * 导入Excel数据 */ @RequiresPermissions("test:video:member:import") @PostMapping("import") public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<Member> list = ei.getDataList(Member.class); for (Member member : list){ try{ memberService.save(member); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条参与人记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条参与人记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入参与人失败!失败信息:"+e.getMessage()); } } /** * 下载导入参与人数据模板 */ @RequiresPermissions("test:video:member:import") @GetMapping("import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "参与人数据导入模板.xlsx"; List<Member> list = Lists.newArrayList(); new ExportExcel("参与人数据", Member.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/service/FormDefinitionJsonService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.extension.entity.FormDefinitionJson; import com.jeeplus.modules.extension.mapper.FormDefinitionJsonMapper; /** * 流程表单Service * @author 刘高峰 * @version 2020-02-02 */ @Service @Transactional(readOnly = true) public class FormDefinitionJsonService extends CrudService<FormDefinitionJsonMapper, FormDefinitionJson> { public FormDefinitionJson get(String id) { return super.get(id); } public List<FormDefinitionJson> findList(FormDefinitionJson formDefinitionJson) { return super.findList(formDefinitionJson); } public Page<FormDefinitionJson> findPage(Page<FormDefinitionJson> page, FormDefinitionJson formDefinitionJson) { return super.findPage(page, formDefinitionJson); } @Transactional(readOnly = true) public Integer getMaxVersion(FormDefinitionJson formDefinitionJson) { return mapper.getMaxVersion(formDefinitionJson); } @Transactional(readOnly = false) public void save(FormDefinitionJson formDefinitionJson) { super.save(formDefinitionJson); } @Transactional(readOnly = false) public void delete(FormDefinitionJson formDefinitionJson) { super.delete(formDefinitionJson); } @Transactional(readOnly = false) public void deleteByFormDefinitionId(FormDefinitionJson formDefinitionJson) { mapper.deleteByFormDefinitionId(formDefinitionJson); } @Transactional(readOnly = false) public void updatePrimary(FormDefinitionJson formDefinitionJson) { mapper.updatePrimary(formDefinitionJson); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/comm/service/ComDingService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.comm.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.test.comm.entity.ComDing; import com.jeeplus.modules.test.comm.mapper.ComDingMapper; /** * 钉钉推送Service * @author lh * @version 2021-03-22 */ @Service @Transactional(readOnly = false) public class ComDingService extends CrudService<ComDingMapper, ComDing> { public ComDing get(String id) { return super.get(id); } public List<ComDing> findList(ComDing comDing) { return super.findList(comDing); } public Page<ComDing> findPage(Page<ComDing> page, ComDing comDing) { return super.findPage(page, comDing); } @Transactional(readOnly = false) public void save(ComDing comDing) { super.save(comDing); } @Transactional(readOnly = false) public void delete(ComDing comDing) { super.delete(comDing); } public ComDing getBySource(String sourceType,String source ){ return mapper.getBySource(sourceType,source); } }<file_sep>/jeeplus-plugins/jeeplus-form/src/main/java/com/jeeplus/modules/form/service/FormService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.form.service; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.database.datasource.annotation.DS; import com.jeeplus.modules.form.entity.DataTable; import com.jeeplus.modules.form.entity.DataTableColumn; import com.jeeplus.modules.form.entity.Form; import com.jeeplus.modules.form.mapper.FormMapper; import com.jeeplus.modules.sys.entity.Menu; import com.jeeplus.modules.sys.service.MenuService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 数据表单Service * @author 刘高峰 * @version 2019-12-24 */ @Service @Transactional(readOnly = true) public class FormService extends CrudService<FormMapper, Form> { @Autowired private MenuService menuService; public Form get(String id) { return super.get(id); } public List<Form> findList(Form form) { return super.findList(form); } public Page<Form> findPage(Page<Form> page, Form form) { return super.findPage(page, form); } @Transactional(readOnly = false) public void save(Form form) { super.save(form); } @Transactional(readOnly = false) public void delete(Form form) { super.delete(form); } /** * 获取物理数据表列表 * * @param dataTable * @return */ @Transactional(readOnly = false) @DS("#dataTable.dataSource.enName") public List<DataTable> findTableListFormDb(DataTable dataTable) { return mapper.findTableList(dataTable); } @Transactional(readOnly = false) @DS("#dataTable.dataSource.enName") public DataTable findTableByName(DataTable dataTable) { return mapper.findTableByName(dataTable); } @Transactional(readOnly = false) @DS("#dataTable.dataSource.enName") public List<DataTableColumn> findTableColumnList(DataTable dataTable) { return mapper.findTableColumnList(dataTable); } @Transactional(readOnly = false) public Menu createMenu(Form form, Menu topMenu) { String permissionPrefix = "form:"+form.getTableName(); String url = "/form/GenerateList?title="+form.getName()+"&id="+form.getId(); topMenu.setHref(url); topMenu.setIsShow("1"); topMenu.setType("1"); topMenu.setPermission(permissionPrefix + ":list"); menuService.saveMenu(topMenu); Menu addMenu = new Menu(); addMenu.setName("新建"); addMenu.setIsShow("0"); addMenu.setType("2"); addMenu.setSort(30); addMenu.setPermission(permissionPrefix + ":add"); addMenu.setParent(topMenu); menuService.saveMenu(addMenu); Menu delMenu = new Menu(); delMenu.setName("删除"); delMenu.setIsShow("0"); delMenu.setType("2"); delMenu.setSort(60); delMenu.setPermission(permissionPrefix + ":del"); delMenu.setParent(topMenu); menuService.saveMenu(delMenu); Menu editMenu = new Menu(); editMenu.setName("修改"); editMenu.setIsShow("0"); editMenu.setType("2"); editMenu.setSort(90); editMenu.setPermission(permissionPrefix + ":edit"); editMenu.setParent(topMenu); menuService.saveMenu(editMenu); Menu viewMenu = new Menu(); viewMenu.setName("查看"); viewMenu.setIsShow("0"); viewMenu.setType("2"); viewMenu.setSort(120); viewMenu.setPermission(permissionPrefix + ":view"); viewMenu.setParent(topMenu); menuService.saveMenu(viewMenu); Menu importMenu = new Menu(); importMenu.setName("导入"); importMenu.setIsShow("0"); importMenu.setType("2"); importMenu.setSort(150); importMenu.setPermission(permissionPrefix + ":import"); importMenu.setParent(topMenu); menuService.saveMenu(importMenu); Menu exportMenu = new Menu(); exportMenu.setName("导出"); exportMenu.setIsShow("0"); exportMenu.setType("2"); exportMenu.setSort(180); exportMenu.setPermission(permissionPrefix + ":export"); exportMenu.setParent(topMenu); menuService.saveMenu(exportMenu); return topMenu; } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/activiti/web/TestActivitiExpenseController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.activiti.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.modules.test.activiti.entity.TestActivitiExpense; import com.jeeplus.modules.test.activiti.service.TestActivitiExpenseService; /** * 报销申请Controller * @author liugf * @version 2021-01-05 */ @RestController @RequestMapping(value = "/test/activiti/testActivitiExpense") public class TestActivitiExpenseController extends BaseController { @Autowired private TestActivitiExpenseService testActivitiExpenseService; @ModelAttribute public TestActivitiExpense get(@RequestParam(required=false) String id) { TestActivitiExpense entity = null; if (StringUtils.isNotBlank(id)){ entity = testActivitiExpenseService.get(id); } if (entity == null){ entity = new TestActivitiExpense(); } return entity; } /** * 报销申请列表数据 */ @GetMapping("list") public AjaxJson list(TestActivitiExpense testActivitiExpense, HttpServletRequest request, HttpServletResponse response) { Page<TestActivitiExpense> page = testActivitiExpenseService.findPage(new Page<TestActivitiExpense>(request, response), testActivitiExpense); return AjaxJson.success().put("page",page); } /** * 根据Id获取报销申请数据 */ @GetMapping("queryById") public AjaxJson queryById(TestActivitiExpense testActivitiExpense) { return AjaxJson.success().put("testActivitiExpense", testActivitiExpense); } /** * 保存报销申请 */ @PostMapping("save") public AjaxJson save(TestActivitiExpense testActivitiExpense, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(testActivitiExpense); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑保存 testActivitiExpenseService.save(testActivitiExpense);//保存 return AjaxJson.success("保存报销申请成功").put("businessTable", "test_activiti_expense").put("businessId", testActivitiExpense.getId()); } /** * 批量删除报销申请 */ @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ testActivitiExpenseService.delete(new TestActivitiExpense(id)); } return AjaxJson.success("删除报销申请成功"); } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/video/entity/Member.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.video.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 参与人Entity * @author lh * @version 2021-03-17 */ @Data public class Member extends DataEntity<Member> { private static final long serialVersionUID = 1L; private String uid; // 钉钉唯一标识 @ExcelField(title="是否参与", align=2, sort=2) private String isIn; // 是否参与 @ExcelField(title="视频主键", align=2, sort=3) private String liveId; // 视频主键 @ExcelField(title="是否发起人", align=2, sort=4) private String launch; // 是否发起人 @ExcelField(title="退出时间", align=2, sort=5) private String endTime; // 退出时间 @ExcelField(title="参与时间", align=2, sort=6) private String startTime; // 参与时间 private String userId; // 用户 @ExcelField(title="用户名", align=2, sort=7) private String name; // 用户 private String photo; //头像 public Member() { super(); } public Member(String id){ super(id); } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/grid/entity/TestContinent.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.grid.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 洲Entity * @author lgf * @version 2021-01-05 */ @Data public class TestContinent extends DataEntity<TestContinent> { private static final long serialVersionUID = 1L; @ExcelField(title="洲名", align=2, sort=1) private String name; // 洲名 public TestContinent() { super(); } public TestContinent(String id){ super(id); } }<file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/ding/config/NoticeUrl.java package com.jeeplus.ding.config; /** * @author: lh * @date: 2021/3/16 */ public class NoticeUrl { /** * 会议通知地址 */ public static final String URL_HY = ""; /** * 微应用基础url * dingtalk://dingtalkclient/action/openapp?corpid=免登企业corpId&container_type=work_platform&app_id=0_{应用agentid}&redirect_type=jump&redirect_url=跳转url */ public static final String BASE_URl = "dingtalk://dingtalkclient/action/openapp?corpid=#{corpid}&container_type=work_platform&app_id=#{app_id}&redirect_type=jump&redirect_url=#{url}"; } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/ding/io/DingNoticeIo.java package com.jeeplus.ding.io; import lombok.Getter; import lombok.Setter; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author: lh * @date: 2021/3/17 */ @Getter @Setter public class DingNoticeIo { /** * 人员列表多人以逗号分开 */ private String users; private DingNotice dingNotice; public void setContentList(DingNotice dingNotice){ this.dingNotice = dingNotice; } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/service/RoleService.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.service; import com.google.common.collect.Lists; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.sys.entity.Role; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.mapper.RoleMapper; import com.jeeplus.modules.sys.utils.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * 角色管理类 * * @author jeeplus * @version 2016-12-05 */ @Service @Transactional(readOnly = true) public class RoleService extends CrudService<RoleMapper, Role> { @Autowired private UserService userService; public Role get(String id) { return mapper.get(id); } public Role getRoleByName(String name) { Role r = new Role(); r.setName(name); return mapper.getByName(r); } public Role getRoleByEnname(String enname) { Role r = new Role(); r.setEnname(enname); return mapper.getByEnname(r); } /** * 查询角色的所有无下属菜单ID * @param id * @return */ public List<String> queryAllNotChildrenMenuId(String id){ if(StringUtils.isNotEmpty(id)){ return mapper.queryAllNotChildrenMenuId(id); } return Lists.newArrayList(); } public List<Role> findAllRole() { return UserUtils.getRoleList(); } @Transactional(readOnly = false) public void saveRole(Role role) { if (StringUtils.isBlank(role.getId())) { role.preInsert(); mapper.insert(role); } else { role.preUpdate(); mapper.update(role); } // 更新角色与菜单关联 mapper.deleteRoleMenu(role); if (role.getMenuList().size() > 0) { mapper.insertRoleMenu(role); } // 更新角色与数据权限关联 mapper.deleteRoleDataRule(role); if (role.getDataRuleList().size() > 0) { mapper.insertRoleDataRule(role); } // 清除用户角色缓存 UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST); } @Transactional(readOnly = false) public void deleteRole(Role role) { mapper.deleteRoleMenu(role); mapper.deleteRoleDataRule(role); mapper.delete(role); // 清除用户角色缓存 UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST); } @Transactional(readOnly = false) public Boolean outUserInRole(Role role, User user) { List<Role> roles = user.getRoleList(); for (Role e : roles) { if (e.getId().equals(role.getId())) { roles.remove(e); userService.saveUser(user); return true; } } return false; } @Transactional(readOnly = false) public User assignUserToRole(Role role, User user) { if (user == null) { return null; } List<String> roleIds = user.getRoleIdList(); if (roleIds.contains(role.getId())) { return null; } user.getRoleList().add(role); userService.saveUser(user); return user; } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/vo/ProcessVo.java package com.jeeplus.modules.flowable.vo; import lombok.Data; import java.util.Date; import java.util.Map; @Data public class ProcessVo { private String processInstanceId; // 流程实例ID private String processDefinitionId; // 流程定义ID private String processDefinitionName; // 流程名称 private String activityId; private int version; // 流程版本 private Map vars; // 流程变量 private Date startTime; // 流程开始时间 private Date endTime; //流程结束时间 private String taskName; //流程当前节点名称 private String deleteReason; //流程作废原因 private HisTaskVo hisTask; // 历史流程节点 private TaskVo task; //流程当前节点 private int code; // 流程状态码 private String status; //流程状态 private String level; //状态级别,用于控制在前台显示的颜色 public String getId(){ // 流程实例id 作为列表的id return processInstanceId; } public void setProcessStatus(ProcessStatus processStatus){ this.code = processStatus.getCode (); this.status = processStatus.getStatus (); this.level = processStatus.getLevel (); } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/entity/FlowCopy.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; /** * 流程抄送Entity * @author 刘高峰 * @version 2019-10-10 */ public class FlowCopy extends DataEntity<FlowCopy> { private static final long serialVersionUID = 1L; private String userId; // 抄送用户id private String procDefId; // 流程定义id private String procInsId; // 流程实例id private String procDefName; // 流程标题 private String procInsName; // 实例标题 private String taskName; // 流程节点 public FlowCopy() { super(); } public FlowCopy(String id){ super(id); } @ExcelField(title="抄送用户id", align=2, sort=1) public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } @ExcelField(title="流程定义id", align=2, sort=2) public String getProcDefId() { return procDefId; } public void setProcDefId(String procDefId) { this.procDefId = procDefId; } @ExcelField(title="流程实例id", align=2, sort=3) public String getProcInsId() { return procInsId; } public void setProcInsId(String procInsId) { this.procInsId = procInsId; } @ExcelField(title="流程标题", align=2, sort=6) public String getProcDefName() { return procDefName; } public void setProcDefName(String procDefName) { this.procDefName = procDefName; } @ExcelField(title="实例标题", align=2, sort=7) public String getProcInsName() { return procInsName; } public void setProcInsName(String procInsName) { this.procInsName = procInsName; } @ExcelField(title="流程节点", align=2, sort=8) public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/service/ext/iml/FlowGroupQueryImpl.java package com.jeeplus.modules.flowable.service.ext.iml; import com.google.common.collect.Lists; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.modules.sys.entity.Role; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.service.UserService; import com.jeeplus.modules.flowable.utils.FlowableUtils; import org.flowable.common.engine.impl.interceptor.CommandContext; import org.flowable.idm.api.Group; import org.flowable.idm.engine.impl.GroupQueryImpl; import java.util.ArrayList; import java.util.List; /** * 扩展Flowable组Service * @author liugoafeng * @version 2019-11-02 */ public class FlowGroupQueryImpl extends GroupQueryImpl { private static final long serialVersionUID = 1L; private UserService userService; public UserService getSystemService() { if (userService == null){ userService = SpringContextHolder.getBean(UserService.class); } return userService; } @Override public long executeCount(CommandContext commandContext) { return executeQuery().size(); } @Override public List<Group> executeList(CommandContext commandContext) { return executeQuery(); } protected List<Group> executeQuery() { if (getUserId() != null) { return findGroupsByUser(getUserId()); } else { return findAllGroups(); } } protected List<Group> findGroupsByUser(String userId) { List<Group> list = Lists.newArrayList(); User user = getSystemService().getUserByLoginName(userId); if (user != null && user.getRoleList() != null){ for (Role role : user.getRoleList()){ list.add(FlowableUtils.toFlowableGroup(role)); } } return list; } protected List<Group> findAllGroups() { return new ArrayList<>(); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/pic/entity/TestPic.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.pic.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 图片管理Entity * @author lgf * @version 2021-01-05 */ @Data public class TestPic extends DataEntity<TestPic> { private static final long serialVersionUID = 1L; @ExcelField(title="标题", align=2, sort=1) private String title; // 标题 @ExcelField(title="图片路径", align=2, sort=2) private String pic; // 图片路径 public TestPic() { super(); } public TestPic(String id){ super(id); } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/comm/config/FilesType.java package com.jeeplus.modules.test.comm.config; /** * @author: lh * @date: 2021/3/13 */ public class FilesType { /** * 数字办公-宣传新闻类别 */ public static final String NEWS_FILE = "news"; /** * 数字文史-资料管理 */ public static final String MATERIAL_FILE = "material"; /** * 数字文史-资料管理 */ public static final String SHARE_FILE = "share"; } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/moments/web/SupportController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.moments.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.test.moments.entity.Share; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.test.moments.entity.Support; import com.jeeplus.modules.test.moments.service.SupportService; /** * 委员圈点赞Controller * @author lh * @version 2021-03-10 */ @RestController @RequestMapping(value = "/test/moments/support") @Api(tags = "委员圈") public class SupportController extends BaseController { @Autowired private SupportService supportService; @ModelAttribute public Support get(@RequestParam(required=false) String id) { Support entity = null; if (StringUtils.isNotBlank(id)){ entity = supportService.get(id); } if (entity == null){ entity = new Support(); } return entity; } /** * 委员圈点赞列表数据 */ @RequiresPermissions("test:moments:support:list") @GetMapping("list") public AjaxJson list(Support support, HttpServletRequest request, HttpServletResponse response) { Page<Support> page = supportService.findPage(new Page<Support>(request, response), support); return AjaxJson.success().put("page",page); } /** * 根据Id获取委员圈点赞数据 */ @GetMapping("queryById") public AjaxJson queryById(Support support) { return AjaxJson.success().put("support", support); } /** * 保存委员圈点赞 */ @PostMapping("save") @ApiOperation(value = "委员圈点赞评论") @ApiImplicitParams({ @ApiImplicitParam(name = "shareId", value = "委员圈主表id", required = true), @ApiImplicitParam(name = "pid", value = "点赞传0,评论传0,回复传评论的主id", required = true), @ApiImplicitParam(name = "type", value = "点赞传1,评论传2", required = true), @ApiImplicitParam(name = "content", value = "内容") }) public AjaxJson save(Support support, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(support); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 supportService.save(support);//保存 return AjaxJson.success("保存委员圈点赞成功"); } /** * 批量删除委员圈点赞 */ @DeleteMapping("delete") @ApiOperation(value = "删除点赞评论") public AjaxJson delete(String ids) { Support support = supportService.get(ids); if(!support.getCurrentUser().getId().equals(support.getCreateBy().getId())){ return AjaxJson.error("没有删除权限"); } supportService.delete(support); return AjaxJson.success("删除委员圈点赞成功"); } /** * 导出excel文件 */ @RequiresPermissions("test:moments:support:export") @GetMapping("export") public AjaxJson exportFile(Support support, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "委员圈点赞"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<Support> page = supportService.findPage(new Page<Support>(request, response, -1), support); new ExportExcel("委员圈点赞", Support.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出委员圈点赞记录失败!失败信息:"+e.getMessage()); } } /** * 导入Excel数据 */ @RequiresPermissions("test:moments:support:import") @PostMapping("import") public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<Support> list = ei.getDataList(Support.class); for (Support support : list){ try{ supportService.save(support); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条委员圈点赞记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条委员圈点赞记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入委员圈点赞失败!失败信息:"+e.getMessage()); } } /** * 下载导入委员圈点赞数据模板 */ @RequiresPermissions("test:moments:support:import") @GetMapping("import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "委员圈点赞数据导入模板.xlsx"; List<Support> list = Lists.newArrayList(); new ExportExcel("委员圈点赞数据", Support.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/flowable/web/FlowableTaskController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.flowable.web; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.extension.entity.NodeSetting; import com.jeeplus.modules.extension.service.NodeSettingService; import com.jeeplus.modules.flowable.entity.Flow; import com.jeeplus.modules.flowable.entity.TaskComment; import com.jeeplus.modules.flowable.service.FlowNoticeService; import com.jeeplus.modules.flowable.service.FlowTaskService; import com.jeeplus.modules.flowable.vo.HisTaskVo; import com.jeeplus.modules.flowable.vo.ProcessVo; import com.jeeplus.modules.sys.utils.UserUtils; import org.apache.commons.lang3.StringUtils; import org.apache.ibatis.annotations.Param; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.flowable.common.engine.impl.identity.Authentication; import org.flowable.engine.HistoryService; import org.flowable.engine.RuntimeService; import org.flowable.engine.TaskService; import org.flowable.engine.runtime.ProcessInstance; import org.flowable.task.api.Task; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Arrays; import java.util.List; import java.util.Map; /** * 流程个人任务相关Controller * * @author jeeplus * @version 2016-11-03 */ @RestController @RequestMapping("/flowable/task") public class FlowableTaskController extends BaseController { @Autowired private FlowTaskService flowTaskService; @Autowired private HistoryService historyService; @Autowired private RuntimeService runtimeService; @Autowired private FlowNoticeService flowNoticeService; @Autowired private TaskService taskService; @Autowired private NodeSettingService nodeSettingService; @GetMapping("todo") public AjaxJson todoListData(Flow flow, HttpServletRequest request, HttpServletResponse response) throws Exception { Page<ProcessVo> page = flowTaskService.todoList(new Page<ProcessVo>(request, response), flow); return AjaxJson.success().put("page", page); } /** * 获取已办任务 * * @return */ @GetMapping("historic") public AjaxJson historicListData(Flow flow, HttpServletRequest request, HttpServletResponse response) throws Exception { Page<HisTaskVo> page = flowTaskService.historicList(new Page<HisTaskVo>(request, response), flow); return AjaxJson.success().put("page", page); } /** * 获取我的申请列表 * * @return */ @GetMapping("myApplyed") public AjaxJson myApplyedListData(Flow flow, HttpServletRequest request, HttpServletResponse response) throws Exception { Page<ProcessVo> page = flowTaskService.getMyStartedProcIns(UserUtils.getUser(), new Page<ProcessVo>(request, response), flow); return AjaxJson.success().put("page", page); } /** * 获取任务流转历史列表 * */ @GetMapping("historicTaskList") public AjaxJson historicTaskList(Flow flow) throws Exception { List<Flow> historicTaskList = flowTaskService.historicTaskList (flow.getProcInsId()); return AjaxJson.success().put("historicTaskList", historicTaskList); } /** * 获取流程表单 */ @GetMapping("getTaskDef") public AjaxJson getTaskDef(Flow flow) { // 获取流程XML上的表单KEY String formKey = flowTaskService.getFormKey(flow.getProcDefId(), flow.getTaskDefKey()); NodeSetting typeNode = nodeSettingService.queryByKey (flow.getProcDefKey(), flow.getTaskDefKey(), "formType"); NodeSetting ReadOnlyNode = nodeSettingService.queryByKey (flow.getProcDefKey(), flow.getTaskDefKey(), "formReadOnly"); String formType = "1"; boolean formReadOnly = false; if(typeNode != null){ formType = typeNode.getValue (); formReadOnly = "true".equals(ReadOnlyNode.getValue ()); }else{ if(StringUtils.isBlank(formKey)){ formType = "1"; }else if(formKey.indexOf("/")>=0 || formKey.length() != 32){ formType = "2"; } } // 获取流程实例对象 if (flow.getProcInsId() != null) { if (flowTaskService.getProcIns(flow.getProcInsId()) != null) { flow.setProcIns(flowTaskService.getProcIns(flow.getProcInsId())); } else { flow.setFinishedProcIns(flowTaskService.getFinishedProcIns(flow.getProcInsId())); } } flow.setFormUrl(formKey); flow.setFormReadOnly(formReadOnly); flow.setFormType(formType); return AjaxJson.success().put("flow", flow); } /** * 启动流程 */ @PostMapping("start") public AjaxJson start(Flow flow) throws Exception { String procInsId = flowTaskService.startProcess(flow.getProcDefKey(), flow.getBusinessTable(), flow.getBusinessId(), flow.getTitle()); //指定下一步处理人 if(StringUtils.isNotBlank(flow.getAssignee ())){ Task task = taskService.createTaskQuery().processInstanceId(procInsId).active().singleResult(); if(task != null){ taskService.setAssignee(task.getId(), flow.getAssignee ()); } } return AjaxJson.success("启动成功!").put("procInsId", procInsId); } /** * 签收任务 */ @PostMapping("claim") public AjaxJson claim(Flow flow) { String userId = UserUtils.getUser().getId();//ObjectUtils.toString(UserUtils.getUser().getId()); flowTaskService.claim(flow.getTaskId(), userId); return AjaxJson.success("签收成功!"); } /** * 完成任务 */ @PostMapping( value = "complete") public AjaxJson complete(Flow flow) { flowTaskService.complete(flow, flow.getVars().getVariableMap()); return AjaxJson.success("完成任务!"); } /** * 读取流程历史数据,用于渲染流程图 */ @GetMapping("getFlowChart") public Map getFlowChart(String processInstanceId) throws Exception { return flowTaskService.getDiagram(processInstanceId); } /** * 删除任务 * * @param taskId 流程实例ID * @param reason 删除原因 */ @DeleteMapping("deleteTask") public AjaxJson deleteTask(String taskId, String reason) { if (StringUtils.isBlank(reason)) { return AjaxJson.error("请填写删除原因"); } else { flowTaskService.deleteTask(taskId, reason); return AjaxJson.success("删除任务成功,任务ID=" + taskId); } } /** * 加签 */ @PostMapping("addSignTask") public AjaxJson addSignTask(String taskId, String userIds, String comment, Boolean flag) throws Exception { flowTaskService.addSignTask (taskId, Arrays.asList (userIds.split (",")), comment, flag); return AjaxJson.success ("加签成功!"); }; /** * 审批 * * @param flow */ @PostMapping("audit") public AjaxJson auditTask(HttpServletRequest request, Flow flow) { Map<String, Object> vars = Maps.newHashMap(); Map<String, String[]> map = request.getParameterMap(); for (Map.Entry<String, String[]> entry : map.entrySet()) { if(entry.getKey().startsWith("vars.")){ String key = entry.getKey().substring(5); String value = entry.getValue()[0]; if("true".equals(value) || "false".equals(value)){ vars.put(key, Boolean.valueOf(value).booleanValue()); }else{ vars.put(key, value); } } } flowTaskService.auditSave(flow, vars); //指定下一步处理人 if(StringUtils.isNotBlank(flow.getAssignee ())){ Task task = taskService.createTaskQuery().processInstanceId(flow.getProcInsId()).active().singleResult(); if(task != null){ taskService.setAssignee(task.getId(), flow.getAssignee ()); } flowNoticeService.sendNotice(flow, vars,task); } return AjaxJson.success("提交成功").put("procInsId", flow.getProcInsId ()); } /** * 取回已经执行的任务,只有在下一任务节点未执行或者未签收时才能取回 */ @PostMapping("callback") public AjaxJson callback(@Param("preTaskId") String preTaskId, @Param("currentTaskId") String currentTaskId, @Param("processInstanceId") String processInstanceId, @Param("preTaskDefKey") String preTaskDefKey, @Param("currentTaskDefKey") String currentTaskDefKey) { try { // 取得流程实例 ProcessInstance instance = runtimeService .createProcessInstanceQuery() .processInstanceId(processInstanceId) .singleResult(); if (instance == null) { return AjaxJson.error("流程已经结束"); } //在已办任务列表中清除该任务信息 historyService.deleteHistoricTaskInstance(preTaskId); List currTasks = Lists.newArrayList(); currTasks.add(currentTaskDefKey); //回退到上一节点 runtimeService.createChangeActivityStateBuilder() .processInstanceId(instance.getId()) .moveActivityIdsToSingleActivityId(currTasks, preTaskDefKey).changeState(); historyService.deleteHistoricTaskInstance(currentTaskId); return AjaxJson.success("取回成功"); } catch (Exception e) { e.printStackTrace(); return AjaxJson.error("流程取回失败,未知错误."); } } /** * 委托任务 * * @param taskId 任务ID */ @PostMapping("delegate") public AjaxJson delegate(String taskId, String userId) { if (StringUtils.isBlank(taskId) || StringUtils.isBlank(userId)) { return AjaxJson.error("参数异常"); } taskService.setOwner (taskId, UserUtils.getUser ().getId ());// 委托人为任务的拥有者 taskService.delegateTask(taskId, userId); return AjaxJson.success("委托成功"); } /** * 取消签收任务 * * @param taskId 任务ID */ @PostMapping("unclaim") public AjaxJson unclaim(String taskId) { taskService.unclaim(taskId); return AjaxJson.success("取消签收成功"); } /** * 转派任务 * * @param taskId 任务ID * @param userId 接收人 */ @PostMapping("transfer") public AjaxJson transferTask(String taskId, String userId) { if (StringUtils.isBlank(userId) || StringUtils.isBlank(taskId)) { return AjaxJson.error("转派失败, 参数异常"); } // 设置当前流程任务办理人 Authentication.setAuthenticatedUserId(UserUtils.getUser().getId()); Task task = taskService.createTaskQuery().taskId(taskId).singleResult(); taskService.setAssignee(taskId, userId); return AjaxJson.success("转派成功!"); } /** * 获取可退回任务节点 * @param taskId * @return */ @PostMapping(value = "/backNodes") public AjaxJson backNodes(@RequestParam String taskId) { List<Flow> nodes = flowTaskService.getBackNodes(taskId); return AjaxJson.success ().put ("backNodes", nodes); } /** * 驳回任务到指定节点 */ @PostMapping(value = "/back") public AjaxJson back(String backTaskDefKey, String taskId, TaskComment comment) { flowTaskService.backTask(backTaskDefKey, taskId, comment); return AjaxJson.success ("驳回成功!"); } } <file_sep>/jeeplus-plugins/jeeplus-form/src/main/java/com/jeeplus/modules/form/web/GenerateFormController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.form.web; import com.google.common.collect.Lists; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.form.dto.Column; import com.jeeplus.modules.form.entity.Form; import com.jeeplus.modules.form.service.FormService; import com.jeeplus.modules.form.service.GenerateFormService; import com.jeeplus.modules.form.utils.ExcelUtils; import com.jeeplus.modules.form.utils.FormJsonUtils; import com.jeeplus.modules.sys.entity.Area; import com.jeeplus.modules.sys.entity.Office; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.utils.UserUtils; import net.sf.json.JSONObject; import org.apache.poi.ss.usermodel.Row; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 数据表单Controller * @author 刘高峰 * @version 2019-12-24 */ @RestController @RequestMapping(value = "/form/generate") public class GenerateFormController extends BaseController { @Autowired private FormService formService; @Autowired private GenerateFormService generateFormService; /** * 保存数据表单 */ @PostMapping("save") public AjaxJson add(String formId, @RequestParam("data") String data) throws Exception{ /** * 后台hibernate-validation插件校验 */ Form form = formService.get(formId); JSONObject jData = JSONObject.fromObject(data); List<Column> fieldArra = FormJsonUtils.newInstance().getFields(form.getSource ()); HashMap<String, String> map = new HashMap(); for(Column column: fieldArra){ map.put(column.getModel(), column.getType()); } if(jData.get("id") != null && StringUtils.isNotBlank(jData.getString("id"))){ generateFormService.executeUpdate(form, jData, map); }else { generateFormService.executeInsert(form, jData, map); } return AjaxJson.success("保存数据成功"); } @RequestMapping(value = "/list") public AjaxJson dataList(@RequestParam("formId") String formId, @RequestParam("params") String params, HttpServletRequest request, HttpServletResponse response) throws Exception{ Form form = formService.get(formId); Page page = generateFormService.executeFindPage(new Page<Form>(request, response), form, params); return AjaxJson.success().put("page", page); } /** * 批量删除数据表单 */ @DeleteMapping("delete") public AjaxJson executeDelete(String formId, String ids) { Form form = formService.get(formId); generateFormService.executeDelete(form, ids); return AjaxJson.success("删除数据成功"); } /** * 查询 */ @GetMapping("queryById") public AjaxJson executeQueryById(String formId, @RequestParam String id) { Form form = formService.get(formId); Map map = generateFormService.executeQueryById(form, id); return AjaxJson.success().put("obj", map); } /** * 导出excel文件 */ @RequestMapping("export") public AjaxJson exportFile(@RequestParam("formId") String formId, @RequestParam("params") String params, HttpServletRequest request, HttpServletResponse response) { Form form = formService.get(formId); try { String fileName = form.getName() + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx"; Page<Map> page = generateFormService.executeFindPage(new Page<Map>(request, response), form, params); String title = form.getName(); List<String> header = Lists.newArrayList(); List<String> keys = Lists.newArrayList(); List<Column> fieldArra = FormJsonUtils.newInstance().getFields(form.getSource ()); for (Column column : fieldArra) { header.add(column.getName()); keys.add(column.getModel()); } ExportExcel exportExcel = new ExportExcel(title, header); for (Map<String, Object> map : page.getList()) { int column = 0; Row row = exportExcel.addRow(); for (String key: keys) { exportExcel.addCell(row, column, map.get(key)); column++; } } exportExcel.write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出" + form.getName() + "记录失败!失败信息:" + e.getMessage()); } } /** * 导入Excel数据 */ @PostMapping("import") public AjaxJson importFile(@RequestParam("formId") String formId, @RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) { Form form = formService.get(formId); try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) { Row row = ei.getRow(i); try { JSONObject jData = new JSONObject(); List<Column> fieldArra = FormJsonUtils.newInstance().getFields(form.getSource ()); HashMap<String, String> map = new HashMap(); for (int j = 0; j < fieldArra.size(); j++) { Column column = fieldArra.get(j); if (column.getType().equals("area")) { Area area = UserUtils.getByAreaName(row.getCell(j).toString()); if (area != null) { jData.put(column.getModel(), area.getId()); } else { jData.put(column.getModel(), ""); } } else if (column.getType().equals("user")) { User user = UserUtils.getByUserName(row.getCell(j).toString()); if (user != null) { jData.put(column.getModel(), user.getId()); } else { jData.put(column.getModel(), ""); } } else if (column.getType().equals("office")) { Office office = UserUtils.getByOfficeName(row.getCell(j).toString()); if (office != null) { jData.put(column.getModel(), office.getId()); } else { jData.put(column.getModel(), ""); } } else { jData.put(column.getModel(), ExcelUtils.getCellString(row.getCell(j))); } map.put(column.getModel(), column.getType()); } generateFormService.executeInsert(form, jData, map); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条"+form.getName()+"记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条"+form.getName()+"记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入"+form.getName()+"失败!失败信息:"+e.getMessage()); } } /** * 下载导入表单数据模板 */ @RequestMapping("import/template") public AjaxJson importFileTemplate(String formId, HttpServletResponse response) { Form form = formService.get(formId); try { String title = form.getName(); String fileName = title + "数据导入模板.xlsx"; List<String> header = Lists.newArrayList(); List<Column> fieldArra = FormJsonUtils.newInstance().getFields(form.getSource ()); for (Column column : fieldArra) { header.add(column.getName()); } ExportExcel exportExcel = new ExportExcel(title, header); exportExcel.write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/service/ActCategoryService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.service.TreeService; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.modules.extension.entity.ActCategory; import com.jeeplus.modules.extension.mapper.ActCategoryMapper; /** * 流程分类Service * @author 刘高峰 * @version 2019-10-09 */ @Service @Transactional(readOnly = true) public class ActCategoryService extends TreeService<ActCategoryMapper, ActCategory> { public ActCategory get(String id) { return super.get(id); } public List<ActCategory> findList(ActCategory actCategory) { if (StringUtils.isNotBlank(actCategory.getParentIds())){ actCategory.setParentIds(","+actCategory.getParentIds()+","); } return super.findList(actCategory); } @Transactional(readOnly = false) public void save(ActCategory actCategory) { super.save(actCategory); } @Transactional(readOnly = false) public void delete(ActCategory actCategory) { super.delete(actCategory); } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/books/entity/ListenRead.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.books.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 在线听书看书Entity * @author lc * @version 2021-03-16 */ @Data public class ListenRead extends DataEntity<ListenRead> { private static final long serialVersionUID = 1L; @ExcelField(title="书籍名称", align=2, sort=1) private String bookName; // 书籍名称 @ExcelField(title="书籍作者", align=2, sort=2) private String bookAuthor; // 书籍作者 @ExcelField(title="书籍内容", align=2, sort=3) private String book; // 书籍内容 public ListenRead() { super(); } public ListenRead(String id){ super(id); } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/service/TaskDefExtensionService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.modules.extension.entity.TaskDefExtension; import com.jeeplus.modules.extension.mapper.TaskDefExtensionMapper; import com.jeeplus.modules.extension.entity.FlowAssignee; import com.jeeplus.modules.extension.mapper.FlowAssigneeMapper; import com.jeeplus.modules.extension.entity.FlowButton; import com.jeeplus.modules.extension.mapper.FlowButtonMapper; import com.jeeplus.modules.extension.entity.FlowCondition; import com.jeeplus.modules.extension.mapper.FlowConditionMapper; /** * 工作流扩展Service * @author 刘高峰 * @version 2020-12-23 */ @Service @Transactional(readOnly = true) public class TaskDefExtensionService extends CrudService<TaskDefExtensionMapper, TaskDefExtension> { @Autowired private FlowAssigneeMapper flowAssigneeMapper; @Autowired private FlowButtonMapper flowButtonMapper; @Autowired private FlowConditionMapper flowConditionMapper; public TaskDefExtension get(String id) { TaskDefExtension taskDefExtension = super.get(id); taskDefExtension.setFlowAssigneeList(flowAssigneeMapper.findList(new FlowAssignee(taskDefExtension))); taskDefExtension.setFlowButtonList(flowButtonMapper.findList(new FlowButton(taskDefExtension))); taskDefExtension.setFlowConditionList(flowConditionMapper.findList(new FlowCondition(taskDefExtension))); return taskDefExtension; } public List<TaskDefExtension> findList(TaskDefExtension taskDefExtension) { return super.findList(taskDefExtension); } public Page<TaskDefExtension> findPage(Page<TaskDefExtension> page, TaskDefExtension taskDefExtension) { return super.findPage(page, taskDefExtension); } @Transactional(readOnly = false) public void save(TaskDefExtension taskDefExtension) { super.save(taskDefExtension); for (FlowAssignee flowAssignee : taskDefExtension.getFlowAssigneeList()){ if (flowAssignee.getId() == null){ continue; } if (FlowAssignee.DEL_FLAG_NORMAL.equals(flowAssignee.getDelFlag())){ if (StringUtils.isBlank(flowAssignee.getId())){ flowAssignee.setTaskDef(taskDefExtension); flowAssignee.preInsert(); flowAssigneeMapper.insert(flowAssignee); }else{ flowAssignee.preUpdate(); flowAssigneeMapper.update(flowAssignee); } }else{ flowAssigneeMapper.delete(flowAssignee); } } for (FlowButton flowButton : taskDefExtension.getFlowButtonList()){ if (flowButton.getId() == null){ continue; } if (FlowButton.DEL_FLAG_NORMAL.equals(flowButton.getDelFlag())){ if (StringUtils.isBlank(flowButton.getId())){ flowButton.setTaskDef(taskDefExtension); flowButton.preInsert(); flowButtonMapper.insert(flowButton); }else{ flowButton.preUpdate(); flowButtonMapper.update(flowButton); } }else{ flowButtonMapper.delete(flowButton); } } for (FlowCondition flowCondition : taskDefExtension.getFlowConditionList()){ if (flowCondition.getId() == null){ continue; } if (FlowCondition.DEL_FLAG_NORMAL.equals(flowCondition.getDelFlag())){ if (StringUtils.isBlank(flowCondition.getId())){ flowCondition.setTaskDef(taskDefExtension); flowCondition.preInsert(); flowConditionMapper.insert(flowCondition); }else{ flowCondition.preUpdate(); flowConditionMapper.update(flowCondition); } }else{ flowConditionMapper.delete(flowCondition); } } } @Transactional(readOnly = false) public void delete(TaskDefExtension taskDefExtension) { super.delete(taskDefExtension); flowAssigneeMapper.delete(new FlowAssignee(taskDefExtension)); flowButtonMapper.delete(new FlowButton(taskDefExtension)); flowConditionMapper.delete(new FlowCondition(taskDefExtension)); } @Transactional(readOnly = false) public void deleteByProcessDefId(String processDefId) { TaskDefExtension taskDefExtension = new TaskDefExtension(); taskDefExtension.setProcessDefId(processDefId); List<TaskDefExtension> list = mapper.findList(taskDefExtension); for(TaskDefExtension taskDefExtension1: list){ super.delete(taskDefExtension1); flowAssigneeMapper.delete(new FlowAssignee(taskDefExtension1)); flowButtonMapper.delete(new FlowButton(taskDefExtension1)); flowConditionMapper.delete(new FlowCondition(taskDefExtension1)); } } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/web/FormDefinitionJsonController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.extension.entity.FormDefinitionJson; import com.jeeplus.modules.extension.service.FormDefinitionJsonService; /** * 流程表单Controller * @author 刘高峰 * @version 2020-02-02 */ @RestController @RequestMapping(value = "/extension/formDefinitionJson") public class FormDefinitionJsonController extends BaseController { @Autowired private FormDefinitionJsonService formDefinitionJsonService; public FormDefinitionJson get(String id) { FormDefinitionJson entity = null; if (StringUtils.isNotBlank(id)){ entity = formDefinitionJsonService.get(id); } if (entity == null){ entity = new FormDefinitionJson(); } return entity; } /** * 流程表单列表数据 */ @GetMapping("list") public AjaxJson list(FormDefinitionJson formDefinitionJson, HttpServletRequest request, HttpServletResponse response) { Page<FormDefinitionJson> page = formDefinitionJsonService.findPage(new Page<FormDefinitionJson>(request, response), formDefinitionJson); return AjaxJson.success().put("page",page); } /** * 根据Id获取流程表单数据 */ @GetMapping("queryById") public AjaxJson queryById(FormDefinitionJson formDefinitionJson) { formDefinitionJson = this.get(formDefinitionJson.getId()); return AjaxJson.success().put("formDefinitionJson", formDefinitionJson); } /** * 根据Id获取流程表单数据 */ @PostMapping("updatePrimary") public AjaxJson updatePrimary(FormDefinitionJson formDefinitionJson) { formDefinitionJson = this.get(formDefinitionJson.getId()); //其余版本更新为非主版本 FormDefinitionJson formDefinitionJson1 = new FormDefinitionJson(); formDefinitionJson1.setIsPrimary("0"); formDefinitionJson1.setFormDefinitionId(formDefinitionJson.getFormDefinitionId()); formDefinitionJsonService.updatePrimary(formDefinitionJson1); formDefinitionJson.setIsPrimary("1"); formDefinitionJsonService.save(formDefinitionJson); return AjaxJson.success("设置主表单成功!"); } /** * 保存流程表单 */ @PostMapping("save") public AjaxJson save(FormDefinitionJson formDefinitionJson, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(formDefinitionJson); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } if(StringUtils.isBlank(formDefinitionJson.getId())){//新增 formDefinitionJson.setVersion(0); formDefinitionJson.setIsPrimary("1"); //设置为主版本 }else {//更新 FormDefinitionJson old = this.get(formDefinitionJson.getId()); if("1".equals(old.getStatus())){//已发布, 如果表单已经发布,不可修改,只能发布为新版本 formDefinitionJson.setId("");//发布新版本 formDefinitionJson.setVersion(formDefinitionJsonService.getMaxVersion(formDefinitionJson)+1); } formDefinitionJson.setIsPrimary("1");//设置为主版本 //其余版本更新为非主版本 FormDefinitionJson formDefinitionJson1 = new FormDefinitionJson(); formDefinitionJson1.setIsPrimary("0"); formDefinitionJson1.setFormDefinitionId(formDefinitionJson.getFormDefinitionId()); formDefinitionJsonService.updatePrimary(formDefinitionJson1); } formDefinitionJsonService.save(formDefinitionJson);//保存 return AjaxJson.success("保存流程表单成功"); } /** * 批量删除流程表单 */ @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ formDefinitionJsonService.delete(formDefinitionJsonService.get(id)); } return AjaxJson.success("删除流程表单成功"); } /** * 导出excel文件 */ @GetMapping("export") public AjaxJson exportFile(FormDefinitionJson formDefinitionJson, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "流程表单"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<FormDefinitionJson> page = formDefinitionJsonService.findPage(new Page<FormDefinitionJson>(request, response, -1), formDefinitionJson); new ExportExcel("流程表单", FormDefinitionJson.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出流程表单记录失败!失败信息:"+e.getMessage()); } } /** * 导入Excel数据 */ @PostMapping("import") public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<FormDefinitionJson> list = ei.getDataList(FormDefinitionJson.class); for (FormDefinitionJson formDefinitionJson : list){ try{ formDefinitionJsonService.save(formDefinitionJson); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条流程表单记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条流程表单记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入流程表单失败!失败信息:"+e.getMessage()); } } /** * 下载导入流程表单数据模板 */ @GetMapping("import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "流程表单数据导入模板.xlsx"; List<FormDefinitionJson> list = Lists.newArrayList(); new ExportExcel("流程表单数据", FormDefinitionJson.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } } <file_sep>/jeeplus-module/committee/src/main/java/com/jeeplus/modules/committee/entity/IntegralDetail.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.committee.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 积分明细Entity * @author tangxin * @version 2021-03-20 */ @Data public class IntegralDetail extends DataEntity<IntegralDetail> { private static final long serialVersionUID = 1L; private CommitteeIntegral ci; // 积分外键 父类 @ExcelField(title="积分", align=2, sort=2) private Integer integral; // 积分 @ExcelField(title="积分类型", dictType="integral_type", align=2, sort=3) private Integer integralType; // 积分类型 public IntegralDetail() { super(); } public IntegralDetail(String id){ super(id); } public IntegralDetail(CommitteeIntegral ci){ this.ci = ci; } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/moments/service/RemindService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.moments.service; import java.util.List; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.test.moments.entity.Share; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.test.moments.entity.Remind; import com.jeeplus.modules.test.moments.mapper.RemindMapper; /** * 提醒人Service * @author lh * @version 2021-03-18 */ @Service @Transactional(readOnly = true) public class RemindService extends CrudService<RemindMapper, Remind> { public Remind get(String id) { return super.get(id); } public List<Remind> findList(Remind remind) { return super.findList(remind); } public Page<Remind> findPage(Page<Remind> page, Remind remind) { return super.findPage(page, remind); } @Transactional(readOnly = false) public void save(Remind remind) { super.save(remind); } @Transactional(readOnly = false) public void delete(Remind remind) { super.delete(remind); } @Transactional(readOnly = false) public void saveList(User user,String share_id) { Remind remind = new Remind(); remind.setName(user.getName()); remind.setShareId(share_id); remind.setUser(user.getId()); super.save(remind); } @Transactional(readOnly = false) public void deleteByShare(Share share) { mapper.deleteByShare(share); } public List<Remind> findListByShare(Share share){ return mapper.findListByShare(share); }; }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/entity/NodeSetting.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 节点设置Entity * @author 刘高峰 * @version 2021-01-11 */ @Data public class NodeSetting extends DataEntity<NodeSetting> { private static final long serialVersionUID = 1L; @ExcelField(title="流程定义id", align=2, sort=1) private String processDefId; // 流程定义id @ExcelField(title="节点id", align=2, sort=2) private String taskDefId; // 节点id @ExcelField(title="变量名", align=2, sort=3) private String key; // 变量名 @ExcelField(title="变量值", align=2, sort=4) private String value; // 变量值 public NodeSetting() { super(); } public NodeSetting(String id){ super(id); } }<file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/web/app/AppActCategoryController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.web.app; import com.google.common.collect.Lists; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.extension.entity.ActCategory; import com.jeeplus.modules.extension.service.ActCategoryService; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.List; /** * 流程分类Controller * @author 刘高峰 * @version 2019-10-09 */ @RestController @RequestMapping("/app/extension/actCategory") public class AppActCategoryController extends BaseController { @Autowired private ActCategoryService actCategoryService; @ModelAttribute public ActCategory get(@RequestParam(required=false) String id) { ActCategory entity = null; if (StringUtils.isNotBlank(id)){ entity = actCategoryService.get(id); } if (entity == null){ entity = new ActCategory(); } return entity; } /** * 流程分类树表数据 */ @RequiresPermissions("extension:actCategory:list") @GetMapping("list") public AjaxJson list(ActCategory actCategory) { return AjaxJson.success().put("list", actCategoryService.findList(actCategory)); } /** * 查看,增加,编辑流程分类表单页面 * params: * mode: add, edit, view, 代表三种模式的页面 */ @RequiresPermissions(value={"extension:actCategory:view","extension:actCategory:add","extension:actCategory:edit"},logical=Logical.OR) @GetMapping("queryById") public AjaxJson queryById(ActCategory actCategory) { return AjaxJson.success().put("actCategory", actCategory); } /** * 保存流程分类 */ @RequiresPermissions(value={"extension:actCategory:add","extension:actCategory:edit"},logical=Logical.OR) @PostMapping("save") public AjaxJson save(ActCategory actCategory, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(actCategory); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 actCategoryService.save(actCategory);//保存 return AjaxJson.success("保存流程分类成功"); } /** * 删除流程分类 */ @RequiresPermissions("extension:actCategory:del") @DeleteMapping("delete") public AjaxJson delete(ActCategory actCategory) { actCategoryService.delete(actCategory); return AjaxJson.success("删除流程分类成功"); } /** * 获取JSON树形数据。 * @param extId 排除的ID * @return */ @RequiresPermissions("user") @GetMapping("treeData") public AjaxJson treeData(@RequestParam(required = false) String extId) { List<ActCategory> list = actCategoryService.findList(new ActCategory()); List rootTree = getActCategoryTree(list, extId); return AjaxJson.success().put("treeData", rootTree); } private List<ActCategory> getActCategoryTree(List<ActCategory> list, String extId) { List<ActCategory> actCategorys = Lists.newArrayList(); List<ActCategory> rootTrees = actCategoryService.getChildren("0"); for (ActCategory root : rootTrees) { if (StringUtils.isBlank(extId) || !extId.equals(root.getId())) { actCategorys.add(getChildOfTree(root, list, extId)); } } return actCategorys; } private ActCategory getChildOfTree(ActCategory actCategory, List<ActCategory> actCategoryList, String extId) { actCategory.setChildren(Lists.newArrayList()); for (ActCategory child : actCategoryList) { if (StringUtils.isBlank(extId) || (!extId.equals(child.getId()) && child.getParentIds().indexOf("," + extId + ",") == -1)) { if (child.getParentId().equals(actCategory.getId())) { actCategory.getChildren().add(getChildOfTree(child, actCategoryList, extId)); } } } return actCategory; } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/web/app/AppUserController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.web.app; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.FileUtils; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.config.properties.FileProperties; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.sys.entity.Office; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.sys.service.OfficeService; import com.jeeplus.modules.sys.service.UserService; import com.jeeplus.modules.sys.utils.FileKit; import com.jeeplus.modules.sys.utils.UserUtils; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 用户Controller * * @author jeeplus * @version 2016-8-29 */ @RestController @RequestMapping("/app/sys/user") @Api(tags ="用户管理") public class AppUserController extends BaseController { @Autowired private UserService userService; @Autowired private OfficeService officeService; @Autowired private FileProperties fileProperties; @ModelAttribute public User get(@RequestParam(required = false) String id) { if (StringUtils.isNotBlank(id)) { return userService.get(id); } else { return new User(); } } @GetMapping("list") public AjaxJson list(User user, HttpServletRequest request, HttpServletResponse response) { Page<User> page = userService.findPage(new Page<User>(request, response), user); return AjaxJson.success().put("page", page); } /** * 用户头像显示编辑保存 * * @return * @throws IOException * @throws IllegalStateException */ @PostMapping("imageUpload") @ApiOperation(value = "上传头像") public AjaxJson imageUpload(@RequestParam("file")MultipartFile file) throws IllegalStateException, IOException { User currentUser = UserUtils.getUser(); // 判断文件是否为空 if (!file.isEmpty()) { if(fileProperties.isImage (file.getOriginalFilename ())){ // 文件保存路径 String realPath = FileKit.getAttachmentDir() + "sys/user/images/"; // 转存文件 FileUtils.createDirectory(realPath); file.transferTo(new File(realPath + file.getOriginalFilename())); currentUser.setPhoto(FileKit.getAttachmentUrl() + "sys/user/images/" + file.getOriginalFilename()); userService.updateUserInfo(currentUser); return AjaxJson.success("上传成功!").put("path", FileKit.getAttachmentUrl() + "sys/user/images/" + file.getOriginalFilename()); }else { return AjaxJson.error ("请上传图片!"); } }else{ return AjaxJson.error ("文件不存在!"); } } /** * 返回用户信息 * * @return */ @GetMapping("info") @ApiOperation(value = "获取当前用户信息") public AjaxJson infoData() { return AjaxJson.success("获取个人信息成功!").put("role", UserUtils.getRoleList()).put("user", UserUtils.getUser()); } @PostMapping("savePwd") @ApiOperation(value = "修改密码") public AjaxJson savePwd(String oldPassword, String newPassword, Model model) { User user = UserUtils.getUser(); if (StringUtils.isNotBlank(oldPassword) && StringUtils.isNotBlank(newPassword)) { if (jeePlusProperites.isDemoMode()) { return AjaxJson.error("演示模式,不允许操作!"); } if (UserService.validatePassword(oldPassword, user.getPassword())) { userService.updatePasswordById(user.getId(), user.getLoginName(), newPassword); return AjaxJson.success("修改密码成功!"); } else { return AjaxJson.error("修改密码失败,旧密码错误!"); } } return AjaxJson.error("参数错误!"); } /** * 获取机构JSON数据。 * @return */ @RequiresPermissions("user") @GetMapping("treeData") public AjaxJson treeData(){ List<Office> list = UserUtils.getOfficeAllList (); List rootTree = getRootTree(list); return AjaxJson.success().put("treeData",rootTree); } private List<Map> getRootTree(List<Office> list) { List<Map> offices = Lists.newArrayList(); List<Office> rootTrees = officeService.getChildren("0"); for (Office root:rootTrees){ offices.add(getChildOfTree(root, list)); } return offices; } private Map getChildOfTree(Office officeItem, List<Office> officeList) { Map oMap = new HashMap (); oMap.put ("id","o_" + officeItem.getId ()); oMap.put ("type", "office"); oMap.put ("label", officeItem.getName ()); List children = Lists.newArrayList (); oMap.put ("children",children); List<User> list = userService.findUserByOfficeId(officeItem.getId ()); for (int i = 0; i < list.size(); i++) { User e = list.get(i); Map<String, Object> map = Maps.newHashMap(); map.put("id", e.getId()); map.put ("type", "user"); map.put("label", e.getName()); children.add(map); } for (Office child : officeList) { if (child.getParentId().equals(officeItem.getId())) { children.add(getChildOfTree (child, officeList)); } } return oMap; } } <file_sep>/jeeplus-module/committee/src/main/java/com/jeeplus/modules/committee/entity/CommitteeIntegral.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.committee.entity; import java.util.List; import com.google.common.collect.Lists; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 委员积分Entity * @author tangxin * @version 2021-03-20 */ @Data public class CommitteeIntegral extends DataEntity<CommitteeIntegral> { private static final long serialVersionUID = 1L; @ExcelField(title="单位", fieldType=String.class, value="", align=2, sort=1) private String org; // 单位 @ExcelField(title="总分", align=2, sort=2) private Integer integral; // 总分 @ExcelField(title="委员ID", fieldType=String.class, value="", align=2, sort=3) private String committeeId; // 委员ID private String committee; // 委员 private String office; // 委员 private List<IntegralDetail> integralDetailList = Lists.newArrayList(); // 子表列表 public CommitteeIntegral() { super(); } public CommitteeIntegral(String id){ super(id); } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/books/mapper/ListenReadMapper.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.books.mapper; import org.springframework.stereotype.Repository; import com.jeeplus.core.persistence.BaseMapper; import org.apache.ibatis.annotations.Mapper; import com.jeeplus.modules.test.books.entity.ListenRead; /** * 在线听书看书MAPPER接口 * @author lc * @version 2021-03-16 */ @Mapper @Repository public interface ListenReadMapper extends BaseMapper<ListenRead> { }<file_sep>/jeeplus-platform/jeeplus-core/src/main/java/com/jeeplus/config/properties/FileProperties.java package com.jeeplus.config.properties; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; @Configuration @Data public class FileProperties { @Value("${userfiles.allowedType}") private String fileType; @Value("${userfiles.extensions.file}") private String fileExtensions; @Value("${userfiles.extensions.image}") private String imageExtensions; @Value("${userfiles.extensions.video}") private String videoExtensions; @Value("${userfiles.extensions.audio}") private String audioExtensions; @Value("${userfiles.extensions.office}") private String officeExtensions; public boolean isAvailable(String fileName) { switch (fileType){ case "all": return true; case "file": return isContain (fileExtensions, fileName); case "image": return isContain (imageExtensions, fileName); case "video": return isContain (videoExtensions, fileName); case "audio": return isContain (audioExtensions, fileName); case "office": return isContain (officeExtensions, fileName); } return false; } public boolean isImage(String fileName) { return isContain (imageExtensions, fileName); } public boolean isContain(String extensions, String fileName){ String[] extensionArray = extensions.split (","); String fileExtension = fileName.substring (fileName.lastIndexOf (".")+1); for(String extension: extensionArray){ if(extension.trim ().equals (fileExtension)){ return true; } } return false; } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/video/service/MemberService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.video.service; import java.util.List; import com.jeeplus.ding.utils.TimeUtil; import com.jeeplus.modules.sys.entity.User; import com.jeeplus.modules.test.video.entity.Live; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.test.video.entity.Member; import com.jeeplus.modules.test.video.mapper.MemberMapper; /** * 参与人Service * @author lh * @version 2021-03-17 */ @Service @Transactional(readOnly = true) public class MemberService extends CrudService<MemberMapper, Member> { public Member get(String id) { return super.get(id); } public List<Member> findList(Member member) { return super.findList(member); } public Page<Member> findPage(Page<Member> page, Member member) { return super.findPage(page, member); } @Transactional(readOnly = false) public void save(Member member) { super.save(member); } @Transactional(readOnly = false) public void delete(Member member) { super.delete(member); } @Transactional(readOnly = false) public void saveByUser(User user, Live live){ Member member = new Member(); member.setUserId(user.getId()); member.setUid(user.getUserId()); member.setIsIn("0"); member.setLiveId(live.getId()); member.setLaunch("0"); if(live.getCreateBy().getId().equals(user.getId())){ member.setLaunch("1"); } super.save(member); } public List<Member> findListByLive(Live live) { return mapper.findListByLive(live); } public void deleteByLive(Live live) { mapper.deleteByLive(live); } }<file_sep>/jeeplus-plugins/jeeplus-mail/src/main/java/com/jeeplus/modules/mail/web/app/AppMailTrashController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.mail.web.app; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.mail.entity.MailTrash; import com.jeeplus.modules.mail.service.MailTrashService; import com.jeeplus.modules.sys.utils.UserUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 垃圾箱Controller * @author 刘高峰 * @version 2020-08-28 */ @RestController @RequestMapping(value = "/app/mail/mailTrash") public class AppMailTrashController extends BaseController { @Autowired private MailTrashService mailTrashService; @ModelAttribute public MailTrash get(@RequestParam(required=false) String id) { MailTrash entity = null; if (StringUtils.isNotBlank(id)){ entity = mailTrashService.get(id); } if (entity == null){ entity = new MailTrash(); } return entity; } /** * 垃圾邮件列表数据 */ @GetMapping("list") public AjaxJson list(MailTrash mailTrash, HttpServletRequest request, HttpServletResponse response) { mailTrash.setCreateBy (UserUtils.getUser ()); Page<MailTrash> page = mailTrashService.findPage(new Page<MailTrash>(request, response), mailTrash); return AjaxJson.success().put("page",page); } /** * 根据Id获取邮件数据 */ @GetMapping("queryById") public AjaxJson queryById(MailTrash mailTrash) { return AjaxJson.success().put("mailTrash", mailTrash); } /** * 保存邮件 */ @PostMapping("save") public AjaxJson save(MailTrash mailTrash, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(mailTrash); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 mailTrashService.save(mailTrash);//保存 return AjaxJson.success("保存邮件成功"); } /** * 批量删除垃圾邮件 */ @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ mailTrashService.delete(new MailTrash(id)); } return AjaxJson.success("删除邮件成功"); } } <file_sep>/jeeplus-plugins/jeeplus-mail/src/main/java/com/jeeplus/modules/mail/web/MailTrashController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.mail.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import com.jeeplus.modules.sys.utils.UserUtils; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.mail.entity.MailTrash; import com.jeeplus.modules.mail.service.MailTrashService; /** * 垃圾箱Controller * @author 刘高峰 * @version 2020-08-28 */ @RestController @RequestMapping(value = "/mail/mailTrash") public class MailTrashController extends BaseController { @Autowired private MailTrashService mailTrashService; @ModelAttribute public MailTrash get(@RequestParam(required=false) String id) { MailTrash entity = null; if (StringUtils.isNotBlank(id)){ entity = mailTrashService.get(id); } if (entity == null){ entity = new MailTrash(); } return entity; } /** * 垃圾邮件列表数据 */ @GetMapping("list") public AjaxJson list(MailTrash mailTrash, HttpServletRequest request, HttpServletResponse response) { mailTrash.setCreateBy (UserUtils.getUser ()); Page<MailTrash> page = mailTrashService.findPage(new Page<MailTrash>(request, response), mailTrash); return AjaxJson.success().put("page",page); } /** * 根据Id获取邮件数据 */ @GetMapping("queryById") public AjaxJson queryById(MailTrash mailTrash) { return AjaxJson.success().put("mailTrash", mailTrash); } /** * 批量删除垃圾邮件 */ @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ mailTrashService.delete(new MailTrash(id)); } return AjaxJson.success("删除邮件成功"); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/treetable/entity/Car.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.treetable.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 车辆Entity * @author lgf * @version 2021-01-05 */ @Data public class Car extends DataEntity<Car> { private static final long serialVersionUID = 1L; @ExcelField(title="品牌", align=2, sort=1) private String name; // 品牌 private CarKind kind; // 车系 父类 public Car() { super(); } public Car(String id){ super(id); } public Car(CarKind kind){ this.kind = kind; } }<file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/entity/Post.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.entity; import javax.validation.constraints.NotNull; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; /** * 岗位Entity * @author 刘高峰 * @version 2020-08-17 */ public class Post extends DataEntity<Post> { private static final long serialVersionUID = 1L; private String name; // 岗位名称 private String code; // 岗位编码 private String type; // 岗位类型 private String status; // 岗位状态 private Integer sort; // 岗位排序 public Post() { super(); } public Post(String id){ super(id); } @ExcelField(title="岗位名称", align=2, sort=1) public String getName() { return name; } public void setName(String name) { this.name = name; } @ExcelField(title="岗位编码", align=2, sort=2) public String getCode() { return code; } public void setCode(String code) { this.code = code; } @ExcelField(title="岗位类型", dictType="sys_post_type", align=2, sort=3) public String getType() { return type; } public void setType(String type) { this.type = type; } @ExcelField(title="岗位状态", dictType="yes_no", align=2, sort=4) public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } @NotNull(message="岗位排序不能为空") @ExcelField(title="岗位排序", align=2, sort=5) public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } }<file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/java/com/jeeplus/modules/database/datamodel/service/DataSetService.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.database.datamodel.service; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.database.datalink.jdbc.DBPool; import com.jeeplus.modules.database.datamodel.entity.DataMeta; import com.jeeplus.modules.database.datamodel.entity.DataParam; import com.jeeplus.modules.database.datamodel.entity.DataSet; import com.jeeplus.modules.database.datamodel.mapper.DataSetMapper; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringEscapeUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.servlet.http.HttpServletRequest; import java.util.*; /** * 数据模型Service * * @author 刘高峰 * @version 2018-08-07 */ @Service @Transactional(readOnly = true) public class DataSetService extends CrudService<DataSetMapper, DataSet> { @Autowired private DataParamService dataParamService; @Autowired private DataMetaService dataMetaService; public DataSet get(String id) { DataSet dataSet = super.get(id); return dataSet; } public DataSet detail(String id) { DataSet dataSet = super.get(id); if (dataSet == null) { return null; } DataMeta dataMeta = new DataMeta(); dataMeta.setDataSet(dataSet); dataSet.setColumnList(dataMetaService.findList(dataMeta)); DataParam dataParam = new DataParam(); dataParam.setDataSet(dataSet); dataSet.setParams(dataParamService.findList(dataParam)); return dataSet; } public List<DataSet> findList(DataSet dataSet) { return super.findList(dataSet); } public Page<DataSet> findPage(Page page, DataSet dataSet) { return super.findPage(page, dataSet); } @Transactional(readOnly = false) public void save(DataSet dataSet) { super.save(dataSet); dataMetaService.deleteByDsId(dataSet.getId()); dataParamService.deleteByDataSetId(dataSet.getId()); for (DataMeta modelMeta : dataSet.getColumnList()) { modelMeta.setDataSet(dataSet); dataMetaService.save(modelMeta); } for (DataParam params : dataSet.getParams()) { params.setDataSet(dataSet); dataParamService.save(params); } } @Transactional(readOnly = false) public void delete(DataSet dataSet) { super.delete(dataSet); dataParamService.deleteByDataSetId(dataSet.getId()); dataMetaService.deleteByDsId(dataSet.getId()); } public List<Map<String, Object>> queryForListById(String id, HttpServletRequest request) throws Exception { Map paramsMap = dataParamService.getParamsForMap(get(id)); if(request != null){ Enumeration<String> names = request.getParameterNames(); while(names.hasMoreElements()){ String param = names.nextElement().toString(); paramsMap.put(param, request.getParameter(param)); } } String sql = mergeSql(get(id).getSqlcmd(), paramsMap); return DBPool.getInstance().getDataSource(get(id).getDb().getEnName()).queryForList(sql); } public String mergeSql(String sql, String[] field, String[] value) { //转换成MAP Map<String, String> paramsMap = new HashMap<>(); if (field != null) { for (int i = 0; i < field.length; i++) { paramsMap.put(field[i], value[i]); } } return mergeSql(sql, paramsMap); } public String mergeSql(String sql, Map<String, String> paramsMap) { sql = StringEscapeUtils.unescapeHtml4(sql); for (String key : paramsMap.keySet()) { sql = sql.replace("{#"+key+"#}", paramsMap.get(key)); } return sql; } public JSONArray toJSON(List<Map<String, Object>> list) { JSONArray data = new JSONArray(); for (Map<String, Object> map : list) { JSONObject obj = new JSONObject(); for (String key : map.keySet()) { Object value = map.get(key); if (value != null) obj.element(key, value.toString()); else obj.element(key, ""); } data.add(obj); } return data; } public String toXML(List<Map<String, Object>> data) { StringBuffer xml = new StringBuffer(); xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<list>\n"); for (Map<String, Object> map : data) { xml.append(" <data>\n"); Iterator<String> iter = map.keySet().iterator(); while (iter.hasNext()) { String key = iter.next(); Object val = map.get(key); xml.append(" <prop key=\"" + key + "\">\n <![CDATA[" + val + "]]>\n </prop>\n"); } xml.append(" </data>\n"); } xml.append("</list>\n"); return xml.toString(); } public String toHTML(List<Map<String, Object>> data) { StringBuffer html = new StringBuffer("<table class='table table-bordered table-condensed'>"); StringBuffer head = new StringBuffer("<thead><tr>"); StringBuffer body = new StringBuffer("<tbody><tr>"); for (int i = 0; i < data.size(); i++) { Map<String, Object> map = data.get(i); for (Map.Entry<String, Object> entry : map.entrySet()) { if (i == 0) { head.append("<th>").append(entry.getKey()).append("</th>"); } body.append("<td>").append(entry.getValue()).append("</td>"); } body.append("</tr><tr>"); } head.append("</tr></thead>"); body.append("</tr></tbody>"); html.append(head).append(body).append("</table>"); return html.toString(); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/manytomany/entity/StudentCourse.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.manytomany.entity; import com.jeeplus.modules.test.manytomany.entity.Student; import javax.validation.constraints.NotNull; import com.jeeplus.modules.test.manytomany.entity.Course; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 学生课程记录Entity * @author lgf * @version 2021-01-05 */ @Data public class StudentCourse extends DataEntity<StudentCourse> { private static final long serialVersionUID = 1L; @NotNull(message="学生不能为空") @ExcelField(title="学生", fieldType=Student.class, value="student.name", align=2, sort=1) private Student student; // 学生 @NotNull(message="课程不能为空") @ExcelField(title="课程", fieldType=Course.class, value="course.name", align=2, sort=2) private Course course; // 课程 @NotNull(message="分数不能为空") @ExcelField(title="分数", align=2, sort=3) private Double score; // 分数 public StudentCourse() { super(); } public StudentCourse(String id){ super(id); } }<file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/note/entity/TestNote.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.note.entity; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.common.utils.excel.annotation.ExcelField; import lombok.Data; /** * 富文本测试Entity * @author liugf * @version 2021-01-05 */ @Data public class TestNote extends DataEntity<TestNote> { private static final long serialVersionUID = 1L; @ExcelField(title="标题", align=2, sort=7) private String title; // 标题 @ExcelField(title="内容", align=2, sort=8) private String contents; // 内容 public TestNote() { super(); } public TestNote(String id){ super(id); } }<file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/java/com/jeeplus/modules/database/datalink/entity/DataSourceTree.java package com.jeeplus.modules.database.datalink.entity; import com.google.common.collect.Lists; import java.util.List; public class DataSourceTree { private String id; private String label; private String parentId; private DataSourceTree parent; private String enName; private String type; private String dbType; private boolean disabled = false; private List<DataSourceTree> children = Lists.newArrayList(); public DataSourceTree(String id, String label, String parentId, String enName, String type){ this.id = id; this.label = label; this.parentId = parentId; this.enName = enName; this.type = type; } public DataSourceTree(String id, String label, String parentId, String enName, String type, String dbType ){ this.id = id; this.label = label; this.parentId = parentId; this.enName = enName; this.type = type; this.dbType = dbType; } public DataSourceTree(String id, String label, String parentId, String enName, String type, boolean disabled){ this.id = id; this.label = label; this.parentId = parentId; this.enName = enName; this.type = type; this.disabled = disabled; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public DataSourceTree getParent() { return parent; } public void setParent(DataSourceTree parent) { this.parent = parent; } public String getEnName() { return enName; } public void setEnName(String enName) { this.enName = enName; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List<DataSourceTree> getChildren() { return children; } public void setChildren(List<DataSourceTree> children) { this.children = children; } public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { this.disabled = disabled; } public String getDbType() { return dbType; } public void setDbType(String dbType) { this.dbType = dbType; } } <file_sep>/jeeplus-module/committee/src/main/java/com/jeeplus/modules/committee/web/StandingCommitteeController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.committee.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.committee.entity.StandingCommittee; import com.jeeplus.modules.committee.service.StandingCommitteeService; /** * 委员相关功能Controller * @author tangxin * @version 2021-03-24 */ @RestController @RequestMapping(value = "/committee/standingCommittee") public class StandingCommitteeController extends BaseController { @Autowired private StandingCommitteeService standingCommitteeService; @ModelAttribute public StandingCommittee get(@RequestParam(required=false) String id) { StandingCommittee entity = null; if (StringUtils.isNotBlank(id)){ entity = standingCommitteeService.get(id); } if (entity == null){ entity = new StandingCommittee(); } return entity; } /** * 委员会列表数据 */ @RequiresPermissions("committee:standingCommittee:list") @GetMapping("list") public AjaxJson list(StandingCommittee standingCommittee, HttpServletRequest request, HttpServletResponse response) { Page<StandingCommittee> page = standingCommitteeService.findPage(new Page<StandingCommittee>(request, response), standingCommittee); return AjaxJson.success().put("page",page); } /** * 根据Id获取委员会数据 */ @RequiresPermissions(value={"committee:standingCommittee:view","committee:standingCommittee:add","committee:standingCommittee:edit"},logical=Logical.OR) @GetMapping("queryById") public AjaxJson queryById(StandingCommittee standingCommittee) { return AjaxJson.success().put("standingCommittee", standingCommittee); } /** * 保存委员会 */ @RequiresPermissions(value={"committee:standingCommittee:add","committee:standingCommittee:edit"},logical=Logical.OR) @PostMapping("save") public AjaxJson save(StandingCommittee standingCommittee, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(standingCommittee); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 standingCommitteeService.save(standingCommittee);//保存 return AjaxJson.success("保存委员会成功"); } /** * 批量删除委员会 */ @RequiresPermissions("committee:standingCommittee:del") @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ standingCommitteeService.delete(new StandingCommittee(id)); } return AjaxJson.success("删除委员会成功"); } /** * 导出excel文件 */ @RequiresPermissions("committee:standingCommittee:export") @GetMapping("export") public AjaxJson exportFile(StandingCommittee standingCommittee, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "委员会"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<StandingCommittee> page = standingCommitteeService.findPage(new Page<StandingCommittee>(request, response, -1), standingCommittee); new ExportExcel("委员会", StandingCommittee.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出委员会记录失败!失败信息:"+e.getMessage()); } } /** * 导入Excel数据 */ @RequiresPermissions("committee:standingCommittee:import") @PostMapping("import") public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<StandingCommittee> list = ei.getDataList(StandingCommittee.class); for (StandingCommittee standingCommittee : list){ try{ standingCommitteeService.save(standingCommittee); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条委员会记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条委员会记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入委员会失败!失败信息:"+e.getMessage()); } } /** * 下载导入委员会数据模板 */ @RequiresPermissions("committee:standingCommittee:import") @GetMapping("import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "委员会数据导入模板.xlsx"; List<StandingCommittee> list = Lists.newArrayList(); new ExportExcel("委员会数据", StandingCommittee.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } }<file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/web/app/AppOfficeController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.web.app; import com.google.common.collect.Lists; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.config.properties.JeePlusProperites; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.sys.entity.Office; import com.jeeplus.modules.sys.service.OfficeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.util.List; /** * 机构Controller * @author jeeplus * @version 2019-5-15 */ @RestController @RequestMapping("/app/sys/office") public class AppOfficeController extends BaseController { @Autowired private OfficeService officeService; /** * 获取机构JSON数据。 * @param extId 排除的ID * @param type 类型(1:公司;2:部门/小组/其它) * @param grade 显示级别 * @param response * @return */ @GetMapping("treeData") public AjaxJson treeData(@RequestParam(required=false) String extId, @RequestParam(required=false) String type, @RequestParam(required=false) Long grade, @RequestParam(required=false) Boolean isAll, HttpServletResponse response) { List<Office> list = officeService.findList(isAll); List rootTree = getRootTree(list, extId, type, grade, isAll); return AjaxJson.success().put("treeData",rootTree); } private List<Office> getRootTree(List<Office> list, String extId, String type, Long grade, Boolean isAll) { List<Office> offices = Lists.newArrayList(); List<Office> rootTrees = officeService.getChildren("0"); for (Office root:rootTrees){ if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(root.getId()) && root.getParentIds().indexOf(","+extId+",")==-1)) && (type == null || (type != null && (type.equals("1") ? type.equals(root.getType()) : true))) && (grade == null || (grade != null && Integer.parseInt(root.getGrade()) <= grade.intValue())) && JeePlusProperites.YES.equals(root.getUseable())){ offices.add(getChildOfTree(root, list, extId, type, grade, isAll)); } } return offices; } private Office getChildOfTree(Office officeItem, List<Office> officeList, String extId, String type, Long grade, Boolean isAll) { officeItem.setChildren(Lists.newArrayList()); if("2".equals(type) && officeItem.getType().equals("1")){ officeItem.setDisabled(true); }else { officeItem.setDisabled(false); } for (Office child : officeList) { if ((StringUtils.isBlank(extId) || (extId!=null && !extId.equals(child.getId()) && child.getParentIds().indexOf(","+extId+",")==-1)) && (type == null || (type != null && (type.equals("1") ? type.equals(child.getType()) : true))) && (grade == null || (grade != null && Integer.parseInt(child.getGrade()) <= grade.intValue())) && JeePlusProperites.YES.equals(child.getUseable())){ if (child.getParentId().equals(officeItem.getId())) { officeItem.getChildren().add(getChildOfTree(child, officeList, extId, type, grade, isAll)); } } } return officeItem; } } <file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/service/PostService.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.service.CrudService; import com.jeeplus.modules.sys.entity.Post; import com.jeeplus.modules.sys.mapper.PostMapper; /** * 岗位Service * @author 刘高峰 * @version 2020-08-17 */ @Service @Transactional(readOnly = true) public class PostService extends CrudService<PostMapper, Post> { public Post get(String id) { return super.get(id); } public List<Post> findList(Post post) { return super.findList(post); } public Page<Post> findPage(Page<Post> page, Post post) { return super.findPage(page, post); } @Transactional(readOnly = false) public void save(Post post) { super.save(post); } @Transactional(readOnly = false) public void delete(Post post) { super.delete(post); } }<file_sep>/jeeplus-platform/jeeplus-admin/src/main/java/com/jeeplus/modules/sys/web/DictController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.sys.web; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.sys.entity.DictType; import com.jeeplus.modules.sys.entity.DictValue; import com.jeeplus.modules.sys.service.DictTypeService; import com.jeeplus.modules.sys.utils.DictUtils; import com.jeeplus.modules.sys.utils.MenuUtils; import com.jeeplus.modules.sys.utils.RouterUtils; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 字典Controller * @author jeeplus * @version 2017-05-16 */ @RestController @RequestMapping("/sys/dict") public class DictController extends BaseController { @Autowired private DictTypeService dictTypeService; @ModelAttribute public DictType get(@RequestParam(required=false) String id) { if (StringUtils.isNotBlank(id)){ return dictTypeService.get(id); }else{ return new DictType(); } } @RequiresPermissions("sys:dict:list") @GetMapping("getDictValue") public AjaxJson getDictValue(String dictTypeId) { Map<String, Object> page = new HashMap<String, Object>(); if(dictTypeId == null || "".equals(dictTypeId)){ page.put("list","[]"); page.put("count",0); }else{ List<DictValue> list = dictTypeService.get(dictTypeId).getDictValueList(); page.put("list",list); page.put("count", list.size()); } return AjaxJson.success().put("page", page); } @RequiresPermissions("sys:dict:list") @GetMapping("type/list") public AjaxJson data(DictType dictType, HttpServletRequest request, HttpServletResponse response, Model model) { Page<DictType> page = dictTypeService.findPage(new Page<DictType>(request, response), dictType); return AjaxJson.success().put("page",page); } @RequiresPermissions(value={"sys:dict:view","sys:dict:add","sys:dict:edit"},logical=Logical.OR) @GetMapping("queryById") public AjaxJson queryById(DictType dictType) { return AjaxJson.success().put("dictType", dictType); } @RequiresPermissions(value={"sys:dict:view","sys:dict:add","sys:dict:edit"},logical=Logical.OR) @GetMapping("queryDictValue") public AjaxJson queryDictValue(String dictValueId) { DictValue dictValue; if(dictValueId == null || "".equals(dictValueId)){ dictValue = new DictValue(); }else{ dictValue = dictTypeService.getDictValue(dictValueId); } return AjaxJson.success().put("dictValue", dictValue); } @RequiresPermissions(value={"sys:dict:add","sys:dict:edit"},logical=Logical.OR) @PostMapping("save") public AjaxJson save(DictType dictType, Model model) { if(jeePlusProperites.isDemoMode()){ return AjaxJson.error("演示模式,不允许操作!"); } /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(dictType); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } dictTypeService.save(dictType); return AjaxJson.success("保存字典类型'" + dictType.getDescription() + "'成功!"); } @RequiresPermissions(value={"sys:dict:add","sys:dict:edit"},logical=Logical.OR) @PostMapping("saveDictValue") public AjaxJson saveDictValue(String dictValueId, DictValue dictValue, Model model) { if(jeePlusProperites.isDemoMode()){ return AjaxJson.error("演示模式,不允许操作!"); } /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(dictValue); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } dictValue.setId(dictValueId); dictTypeService.saveDictValue(dictValue); return AjaxJson.success("保存键值'" + dictValue.getLabel() + "'成功!"); } @RequiresPermissions("sys:dict:edit") @DeleteMapping("deleteDictValue") public AjaxJson deleteDictValue(String ids, Model model) { AjaxJson j = new AjaxJson(); if(jeePlusProperites.isDemoMode()){ return AjaxJson.error("演示模式,不允许操作!"); } dictTypeService.batchDeleteDictValue(ids.split(",")); return AjaxJson.success("删除键值成功!"); } /** * 批量删除 */ @RequiresPermissions("sys:dict:del") @DeleteMapping("delete") public AjaxJson delete(String ids) { AjaxJson j = new AjaxJson(); if(jeePlusProperites.isDemoMode()){ return AjaxJson.error("演示模式,不允许操作!"); } String idArray[] =ids.split(","); dictTypeService.batchDelete(idArray); return AjaxJson.success("删除字典成功!"); } @GetMapping("listData") public AjaxJson listData(@RequestParam(required=false) String type) { DictType dictType = new DictType(); dictType.setType(type); return AjaxJson.success().put("list", dictTypeService.findList(dictType)); } @GetMapping("getDictMap") public AjaxJson getDictMap() { AjaxJson j = new AjaxJson(); j.put("dictList", DictUtils.getDictMap()); return j; } } <file_sep>/jeeplus-plugins/jeeplus-datasource/src/main/java/com/jeeplus/modules/database/datalink/web/DataSourceController.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.database.datalink.web; import java.util.HashSet; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.modules.database.datalink.entity.DataSource; import com.jeeplus.modules.database.datalink.entity.DataSourceTree; import com.jeeplus.modules.database.datalink.jdbc.DBPool; import com.jeeplus.modules.sys.utils.DictUtils; import org.apache.ibatis.mapping.DatabaseIdProvider; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import com.jeeplus.modules.database.datalink.service.DataSourceService; /** * 数据库连接Controller * * @author 刘高峰 * @version 2018-08-06 */ @RestController @RequestMapping(value = "/database/datalink/dataSource") public class DataSourceController extends BaseController { @Autowired private DataSourceService dataSourceService; @Autowired private DatabaseIdProvider databaseIdProvider; @ModelAttribute public DataSource get(@RequestParam(value = "id", required = false) String id) { DataSource entity = null; if (StringUtils.isNotBlank(id)) { entity = dataSourceService.get(id); } if (entity == null) { entity = new DataSource(); } return entity; } /**查询实体 */ @RequiresPermissions(value = {"database:datalink:dataSource:view", "database:datalink:dataSource:add", "database:datalink:dataSource:edit"}, logical = Logical.OR) @RequestMapping(value = "queryById") public AjaxJson queryById(DataSource dataSource) { return AjaxJson.success().put("dataSource", dataSource); } @RequiresPermissions("database:datalink:dataSource:list") @RequestMapping(value = "list") public AjaxJson list(DataSource dataSource, HttpServletRequest request, HttpServletResponse response, Model model) { Page<DataSource> page = dataSourceService.findPage(new Page<DataSource>(request, response), dataSource); return AjaxJson.success().put("page", page); } @RequestMapping(value = "treeData") public AjaxJson treeData(HttpServletResponse response) { List<Map<String, Object>> mapList = Lists.newArrayList(); List<DataSource> list = dataSourceService.findList(new DataSource()); HashSet<String> set = new HashSet(); for (int i = 0; i < list.size(); i++) { DataSource e = list.get(i); Map<String, Object> map = Maps.newHashMap(); map.put("id", e.getId()); map.put("parent", e.getHost()); map.put("text", e.getName()); map.put("type", "db"); mapList.add(map); set.add(e.getHost()); } for (String host : set) { Map<String, Object> map = Maps.newHashMap(); map.put("id", host); map.put("parent", "#"); map.put("text", host); map.put("type", "host"); Map<String, Object> state = Maps.newHashMap(); state.put("opened", true); map.put("state", state); mapList.add(map); } return AjaxJson.success().put("treeData", mapList); } @RequestMapping(value = "treeData2") public AjaxJson treeData2(HttpServletResponse response) { List<DataSourceTree> treelist = Lists.newArrayList(); List<DataSourceTree> treeRoots = Lists.newArrayList(); String dbType ; try{ dbType = databaseIdProvider.getDatabaseId(SpringContextHolder.getBean(javax.sql.DataSource.class)); }catch (Exception e){ dbType = "mysql"; } treeRoots.add(new DataSourceTree("master-parent","默认数据源","0","","host", true)); treelist.add(new DataSourceTree("master","本地数据库","master-parent","master","db", dbType)); List<DataSource> list = dataSourceService.findList(new DataSource()); HashSet<String> set = new HashSet(); for (int i = 0; i < list.size(); i++) { DataSource e = list.get(i); treelist.add(new DataSourceTree(e.getId(),e.getName(),e.getHost(),e.getEnName(),"db", e.getType())); set.add(e.getHost()); } for (String host : set) { treeRoots.add(new DataSourceTree(host,host,"0","","host", true)); } List rootTree = getRootTree(treeRoots,treelist); return AjaxJson.success().put("treeData", rootTree); } private List<DataSourceTree> getRootTree(List<DataSourceTree> rootTrees, List<DataSourceTree> list) { List<DataSourceTree> trees = Lists.newArrayList(); for (DataSourceTree root : rootTrees) { trees.add(getChildOfTree(root, list)); } return trees; } private DataSourceTree getChildOfTree(DataSourceTree area, List<DataSourceTree> areaList) { area.setChildren(Lists.newArrayList()); for (DataSourceTree child : areaList) { if (child.getParentId().equals(area.getId())) { area.getChildren().add(getChildOfTree(child, areaList)); } } return area; } /** * 保存数据库连接 */ @RequiresPermissions(value = {"database:datalink:dataSource:add", "database:datalink:dataSource:edit"}, logical = Logical.OR) @RequestMapping(value = "save") public AjaxJson save(DataSource dataSource, Model model) throws Exception { AjaxJson j = new AjaxJson(); /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(dataSource); if (StringUtils.isNotBlank(errMsg)) { j.setSuccess(false); j.setMsg(errMsg); return j; } String oldName = ""; if(StringUtils.isNotBlank(dataSource.getId())){ oldName = dataSourceService.get(dataSource.getId()).getEnName(); } String driver = DictUtils.getDictValue(dataSource.getType(), "db_driver", "mysql"); dataSource.setDriver(driver); dataSource.setUrl(dataSourceService.toUrl(dataSource.getType(), dataSource.getHost(), Integer.valueOf(dataSource.getPort()), dataSource.getDbname())); //新增或编辑表单保存 dataSourceService.save(dataSource);//保存 if(StringUtils.isNotBlank(oldName)){ DBPool.getInstance().destroy(oldName); } DBPool.getInstance().create(dataSource); j.setSuccess(true); j.setMsg("保存数据库连接成功"); return j; } /** * 批量删除数据库连接 */ @RequiresPermissions("database:datalink:dataSource:del") @RequestMapping(value = "delete") public AjaxJson delete(@RequestParam(value = "ids", required = false)String ids) { AjaxJson j = new AjaxJson(); String idArray[] = ids.split(","); for (String id : idArray) { DataSource dataSource = dataSourceService.get(id); dataSourceService.delete(dataSource); DBPool.getInstance().destroy(dataSource.getEnName()); } j.setMsg("删除数据库连接成功"); return j; } /** * 验证数据库唯一key是否存在 * @param oldEnName * @param enName * @return */ @RequestMapping(value = "checkEnName") public AjaxJson checkLoginName(@RequestParam(value = "oldEnName", required = false)String oldEnName, @RequestParam(value = "enName", required = false)String enName) { if (enName !=null && enName.equals(oldEnName)) { return AjaxJson.success(); } else if (enName !=null && dataSourceService.findUniqueByProperty("enName", enName) == null) { return AjaxJson.success(); } return AjaxJson.error("数据库连接英文名已存在"); } /** * 测试数据源是否可用 * * @param type 数据库类型 * @param host * @param port * @param dbname * @param username * @param password * @return */ @RequestMapping("/test") public AjaxJson test(@RequestParam(value = "type", required = false)String type, @RequestParam(value = "host", required = false)String host, @RequestParam(value = "port", required = false)Integer port, @RequestParam(value = "dbname", required = false)String dbname, @RequestParam(value = "username", required = false)String username, @RequestParam(value = "password", required = false)String password) { AjaxJson j = new AjaxJson(); if (StringUtils.isBlank(type) || StringUtils.isBlank(host) || StringUtils.isBlank(dbname) || StringUtils.isBlank(username)) { j.setSuccess(false); j.setMsg("配置信息不全"); return j; } if (DBPool.getInstance().test(dataSourceService.getDriver(type), dataSourceService.toUrl(type, host, port, dbname), username, password)) { j.setSuccess(true); j.setMsg("连接成功"); return j; } else { j.setSuccess(false); j.setMsg("连接失败"); return j; } } } <file_sep>/jeeplus-plugins/jeeplus-mail/src/main/java/com/jeeplus/modules/mail/entity/MailCompose.java /** * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.mail.entity; import com.jeeplus.common.utils.SpringContextHolder; import com.jeeplus.modules.sys.service.UserService; import org.hibernate.validator.constraints.Length; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonFormat; import com.google.common.collect.Lists; import com.jeeplus.common.utils.Collections3; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.core.persistence.DataEntity; import com.jeeplus.modules.sys.entity.User; /** * 发件箱Entity * * @author jeeplus * @version 2015-11-15 */ public class MailCompose extends DataEntity<MailCompose> { private static final long serialVersionUID = 1L; private String status; // 状态 0 草稿 1 已发送 private User sender; // 发送者 private String receiverIds; //收信人ID private Date sendtime; // 发送时间 private Mail mail; // 邮件id 父类 public MailCompose() { super(); } public MailCompose(String id) { super(id); } public MailCompose(Mail mail) { this.mail = mail; } @Length(min = 0, max = 45, message = "状态 0 草稿 1 已发送长度必须介于 0 和 45 之间") public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public User getSender() { return sender; } public void setSender(User sender) { this.sender = sender; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getSendtime() { return sendtime; } public void setSendtime(Date sendtime) { this.sendtime = sendtime; } @Length(min = 0, max = 64, message = "邮件id长度必须介于 0 和 64 之间") public Mail getMail() { return mail; } public void setMail(Mail mail) { this.mail = mail; } /** * 获取收件人用户ID * * @return */ public String getReceiverIds() { return this.receiverIds; } /** * 设置收件人用户ID * * @return */ public void setReceiverIds(String receiverIds) { this.receiverIds = receiverIds; } /** * 获取收件人用户Name * * @return */ public String getReceiverNames() { if(StringUtils.isBlank(receiverIds)){ return ""; } List receiverList = Lists.newArrayList(); for (String id : StringUtils.split(receiverIds, ",")) { receiverList.add(SpringContextHolder.getBean(UserService.class).get(id)); } return Collections3.extractToString(receiverList, "name", ","); } /** * 获取收件人用户 * * @return */ public List<User> getReceiverList() { List receiverList = Lists.newArrayList(); if(StringUtils.isBlank(receiverIds)){ return receiverList; } for (String id : StringUtils.split(receiverIds, ",")) { receiverList.add(new User(id)); } return receiverList; } } <file_sep>/jeeplus-plugins/jeeplus-flowable/src/main/java/com/jeeplus/modules/extension/web/NodeSettingController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.extension.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.extension.entity.NodeSetting; import com.jeeplus.modules.extension.service.NodeSettingService; /** * 节点设置Controller * @author 刘高峰 * @version 2021-01-11 */ @RestController @RequestMapping(value = "/extension/nodeSetting") public class NodeSettingController extends BaseController { @Autowired private NodeSettingService nodeSettingService; @ModelAttribute public NodeSetting get(@RequestParam(required=false) String id) { NodeSetting entity = null; if (StringUtils.isNotBlank(id)){ entity = nodeSettingService.get(id); } if (entity == null){ entity = new NodeSetting(); } return entity; } /** * 节点列表数据 */ @GetMapping("list") public AjaxJson list(NodeSetting nodeSetting, HttpServletRequest request, HttpServletResponse response) { Page<NodeSetting> page = nodeSettingService.findPage(new Page<NodeSetting>(request, response), nodeSetting); return AjaxJson.success().put("page",page); } /** * 根据Id获取节点数据 */ @GetMapping("queryById") public AjaxJson queryById(NodeSetting nodeSetting) { return AjaxJson.success().put("nodeSetting", nodeSetting); } /** * 根据Id获取节点数据 */ @GetMapping("queryValueByKey") public AjaxJson queryById(String processDefId, String taskDefId, String key) { NodeSetting nodeSetting = nodeSettingService.queryByKey (processDefId, taskDefId, key); if(nodeSetting == null){ return AjaxJson.success ().put ("value", ""); }else{ return AjaxJson.success ().put ("value", nodeSetting.getValue ()); } } /** * 保存节点 */ /** * 保存表单只读配置 */ @PostMapping("save") public AjaxJson save(@RequestBody List<NodeSetting> nodeSettingList) throws Exception{ for(NodeSetting nodeSetting: nodeSettingList){ nodeSettingService.deleteByDefIdAndTaskId(nodeSetting);//删除节点旧的属性 } for(NodeSetting nodeSetting: nodeSettingList){ nodeSettingService.save (nodeSetting); } return AjaxJson.success("保存配置成功"); } /** * 批量删除节点 */ @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ nodeSettingService.delete(new NodeSetting(id)); } return AjaxJson.success("删除节点成功"); } } <file_sep>/jeeplus-module/jeeplus-test/src/main/java/com/jeeplus/modules/test/comm/web/ComFilesController.java /** * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved. */ package com.jeeplus.modules.test.comm.web; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.ConstraintViolationException; import org.apache.shiro.authz.annotation.Logical; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import com.google.common.collect.Lists; import com.jeeplus.common.utils.DateUtils; import com.jeeplus.common.json.AjaxJson; import com.jeeplus.core.persistence.Page; import com.jeeplus.core.web.BaseController; import com.jeeplus.common.utils.StringUtils; import com.jeeplus.common.utils.excel.ExportExcel; import com.jeeplus.common.utils.excel.ImportExcel; import com.jeeplus.modules.test.comm.entity.ComFiles; import com.jeeplus.modules.test.comm.service.ComFilesService; /** * 公共Controller * @author lh * @version 2021-03-12 */ @RestController @RequestMapping(value = "/test/comm/comFiles") public class ComFilesController extends BaseController { @Autowired private ComFilesService comFilesService; @ModelAttribute public ComFiles get(@RequestParam(required=false) String id) { ComFiles entity = null; if (StringUtils.isNotBlank(id)){ entity = comFilesService.get(id); } if (entity == null){ entity = new ComFiles(); } return entity; } /** * 公共列表数据 */ @RequiresPermissions("test:comm:comFiles:list") @GetMapping("list") public AjaxJson list(ComFiles comFiles, HttpServletRequest request, HttpServletResponse response) { Page<ComFiles> page = comFilesService.findPage(new Page<ComFiles>(request, response), comFiles); return AjaxJson.success().put("page",page); } /** * 根据Id获取公共数据 */ @RequiresPermissions(value={"test:comm:comFiles:view","test:comm:comFiles:add","test:comm:comFiles:edit"},logical=Logical.OR) @GetMapping("queryById") public AjaxJson queryById(ComFiles comFiles) { return AjaxJson.success().put("comFiles", comFiles); } /** * 保存公共 */ @RequiresPermissions(value={"test:comm:comFiles:add","test:comm:comFiles:edit"},logical=Logical.OR) @PostMapping("save") public AjaxJson save(ComFiles comFiles, Model model) throws Exception{ /** * 后台hibernate-validation插件校验 */ String errMsg = beanValidator(comFiles); if (StringUtils.isNotBlank(errMsg)){ return AjaxJson.error(errMsg); } //新增或编辑表单保存 comFilesService.save(comFiles);//保存 return AjaxJson.success("保存公共成功"); } /** * 批量删除公共 */ @RequiresPermissions("test:comm:comFiles:del") @DeleteMapping("delete") public AjaxJson delete(String ids) { String idArray[] =ids.split(","); for(String id : idArray){ comFilesService.delete(new ComFiles(id)); } return AjaxJson.success("删除公共成功"); } /** * 导出excel文件 */ @RequiresPermissions("test:comm:comFiles:export") @GetMapping("export") public AjaxJson exportFile(ComFiles comFiles, HttpServletRequest request, HttpServletResponse response) { try { String fileName = "公共"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx"; Page<ComFiles> page = comFilesService.findPage(new Page<ComFiles>(request, response, -1), comFiles); new ExportExcel("公共", ComFiles.class).setDataList(page.getList()).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error("导出公共记录失败!失败信息:"+e.getMessage()); } } /** * 导入Excel数据 */ @RequiresPermissions("test:comm:comFiles:import") @PostMapping("import") public AjaxJson importFile(@RequestParam("file")MultipartFile file, HttpServletResponse response, HttpServletRequest request) { try { int successNum = 0; int failureNum = 0; StringBuilder failureMsg = new StringBuilder(); ImportExcel ei = new ImportExcel(file, 1, 0); List<ComFiles> list = ei.getDataList(ComFiles.class); for (ComFiles comFiles : list){ try{ comFilesService.save(comFiles); successNum++; }catch(ConstraintViolationException ex){ failureNum++; }catch (Exception ex) { failureNum++; } } if (failureNum>0){ failureMsg.insert(0, ",失败 "+failureNum+" 条公共记录。"); } return AjaxJson.success( "已成功导入 "+successNum+" 条公共记录"+failureMsg); } catch (Exception e) { return AjaxJson.error("导入公共失败!失败信息:"+e.getMessage()); } } /** * 下载导入公共数据模板 */ @RequiresPermissions("test:comm:comFiles:import") @GetMapping("import/template") public AjaxJson importFileTemplate(HttpServletResponse response) { try { String fileName = "公共数据导入模板.xlsx"; List<ComFiles> list = Lists.newArrayList(); new ExportExcel("公共数据", ComFiles.class, 1).setDataList(list).write(response, fileName).dispose(); return null; } catch (Exception e) { return AjaxJson.error( "导入模板下载失败!失败信息:"+e.getMessage()); } } }
7be333cf65042b44807d885be7ecafd62e24f94d
[ "Markdown", "Java", "Maven POM", "INI" ]
116
Java
PerseveranceGroup/jeep
ed4d0c0fb6ec471c0f78a40c12e69252705f14b8
3367adc39429681b36bf7d3a6747c7752ddb4eb0
refs/heads/master
<file_sep>import {Component, ViewChild} from '@angular/core'; import {Nav, Platform} from 'ionic-angular'; import {StatusBar} from '@ionic-native/status-bar'; import {SplashScreen} from '@ionic-native/splash-screen'; import {MyTeamsPage, TournamentsPage, TeamHomePage} from '../pages/pages'; import {UserSettings, EliteApi} from '../shared/shared'; import {Events, LoadingController} from 'ionic-angular'; import { AgmCoreModule } from 'angular2-google-maps/core'; @Component({ templateUrl: 'app.html' }) export class MyApp { @ViewChild(Nav) nav: Nav; favoriteTeams: any[]; rootPage: any = MyTeamsPage; pages: Array<{ title: string, component: any }>; constructor( public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, private eliteApi: EliteApi, private userSettings: UserSettings, private events: Events, private loadingController: LoadingController) { this.initializeApp(); } initializeApp() { this.platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. this.statusBar.styleDefault(); this.refreshFavorites(); this.events.subscribe('favorites:changed', () => this.refreshFavorites()); this.splashScreen.hide(); }); } goHome() { this.nav.push(MyTeamsPage); } refreshFavorites() { this.userSettings.getAllFavorites().then(favs => this.favoriteTeams = favs); } goToTeam(favorite) { let loader = this.loadingController.create({ content: 'Getting data...', dismissOnPageChange: true }); loader.present(); this.eliteApi.getTournamentData(favorite.tournamentId).subscribe(l => this.nav.push(TeamHomePage, favorite.team)); } goToTournaments() { this.nav.push(TournamentsPage); } } <file_sep>import {Injectable} from '@angular/core'; import {Events} from 'ionic-angular'; import {Storage} from '@ionic/storage'; import _ from 'lodash'; //import { SqlStorage } from './sql-storage.service'; @Injectable() export class UserSettings { constructor(private storage: Storage, private events: Events) { } favoriteTeam(team, tournamentId, tournamentName) { let item = {team: team, tournamentId: tournamentId, tournamentName: tournamentName}; return new Promise(resolve => { this.storage.set(team.id.toString(), JSON.stringify(item)).then(() => { this.events.publish('favorites:changed'); resolve(); }); }); } unfavoriteTeam(team) { return new Promise(resolve => { this.storage.remove(team.id.toString()).then(() => { this.events.publish('favorites:changed'); resolve(); }); }); } isFavoriteTeam(teamId) { return this.storage.get(teamId).then(value => value ? true : false); } getAllFavorites() : Promise<any[]> { return new Promise(resolve => { let results = []; this.storage.forEach(data => { console.log('***inside foreach', data); results.push(JSON.parse(data)); }); return resolve(results); }); } } <file_sep>import {BrowserModule} from '@angular/platform-browser'; import {ErrorHandler, NgModule} from '@angular/core'; import {IonicApp, IonicErrorHandler, IonicModule} from 'ionic-angular'; import {IonicStorageModule} from '@ionic/storage'; import {SQLite} from '@ionic-native/sqlite'; import {MyApp} from './app.component'; import { AgmCoreModule } from 'angular2-google-maps/core'; import { MyTeamsPage, GamePage, TeamDetailPage, TeamsPage, TournamentsPage, TeamHomePage, StandingsPage, MapPage } from '../pages/pages'; import {HttpModule} from '@angular/http'; import {EliteApi, UserSettings} from '../shared/shared'; import {StatusBar} from '@ionic-native/status-bar'; import {SplashScreen} from '@ionic-native/splash-screen'; @NgModule({ declarations: [ MyApp, MyTeamsPage, GamePage, TeamDetailPage, TeamsPage, TournamentsPage, TeamHomePage, StandingsPage, MapPage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp), IonicStorageModule.forRoot(), AgmCoreModule.forRoot({apiKey: '<KEY>'}), HttpModule ], bootstrap: [IonicApp], entryComponents: [ MyApp, MyTeamsPage, GamePage, TeamDetailPage, TeamsPage, TournamentsPage, TeamHomePage, StandingsPage, MapPage ], providers: [ StatusBar, SplashScreen, {provide: ErrorHandler, useClass: IonicErrorHandler}, EliteApi, UserSettings, SQLite ] }) export class AppModule { }
2934a2a2e7a71b823efb6b92e54c6c6a6fec3815
[ "TypeScript" ]
3
TypeScript
maxenz/elite
7fcfb8d8b7747c04e05eed23711e4e2045879c78
2d70b8eac2251f44724f2e39aebf7d6ce1fc6e14
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Threading.Tasks; using Apache.Ignite.Core; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Linq; using Apache.Ignite.Core.Datastream; using System.Configuration; using Apache.Ignite.Core.Cluster; using System.Diagnostics; using System.Threading; namespace CacheService { class Program { static IIgnite ignite; static ICache<long, CustomerAccount_ignite> cache; static List<long> accountIDs = new List<long>(); const int numWriteThread = 20; const int numReadThread = 20; const int numDuration = 1; // minutes static long writeTotalLatency = 0L; static long writeCalls = 0L; static long writeSucceeded = 0L; static long writeFailed = 0L; static long totalLatency = 0L; static long calls = 0L; static long succeeded = 0L; static long failed = 0L; static void PopulateAccountIDs() { var queryable = cache.AsCacheQueryable(); var accounts = queryable.Select(customer => new { customer.Value._AccountId}).ToArray(); foreach (var account in accounts) { accountIDs.Add(account._AccountId); } } private static DataTable CreateDataTable(IEnumerable<long> ids) { DataTable table = new DataTable(); table.Columns.Add("Id", typeof(long)); foreach (long id in ids.Distinct()) { table.Rows.Add(id); } return table; } private static void Reset() { totalLatency = 0L; calls = 0L; succeeded = 0L; failed = 0L; } static void Main(string[] args) { //string conn_string = ConfigurationManager.ConnectionStrings["CacheService.Properties.Settings.testConnectionString"].Name; Ignition.ClientMode = true; using (ignite = Ignition.StartFromApplicationConfiguration()) { ICluster cluster = ignite.GetCluster(); ICollection<IClusterNode> t = cluster.ForRemotes().GetNodes(); List<IClusterNode> t1 = t.ToList<IClusterNode>(); Console.WriteLine("{0}", t1.ToString()); PreLoad preload = new PreLoad(); String CacheName = "Cache"; var caches = ignite.GetCacheNames(); cache = ignite.GetOrCreateCache<long, CustomerAccount_ignite>( new CacheConfiguration(CacheName, typeof(CustomerAccount_ignite)) { CacheMode = CacheMode.Partitioned } );//"Cache" IDataStreamer<long, CustomerAccount_ignite> streamer = ignite.GetDataStreamer<long, CustomerAccount_ignite>("Cache"); streamer.AllowOverwrite = true; IQueryable<ICacheEntry<long, CustomerAccount_ignite>> queryable = cache.AsCacheQueryable(); if (!caches.Contains(CacheName)) preload.Process(streamer); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Populating Account IDs"); PopulateAccountIDs(); Console.WriteLine(accountIDs.Count); Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " Start writing tasks"); CancellationTokenSource writeTokenSource = new CancellationTokenSource(); CancellationToken writeToken = writeTokenSource.Token; List<Task> writeTasks = new List<Task>(); for (int i = 0; i < numWriteThread; i++) { writeTasks.Add(new Task(() => { Thread.Sleep(2000); ///Console.Write("tasks1 start ", i); while (!writeToken.IsCancellationRequested) { Stopwatch sw = Stopwatch.StartNew(); try { long p = Helper.GetRandomAccountID(accountIDs); var accounts = queryable.Where(customer => customer.Value._AccountId ==p).ToArray(); foreach (var account in accounts) { account.Value._AgencyName = Helper.GetRandomString(20); streamer.AddData(account.Key, account.Value); } Interlocked.Increment(ref writeSucceeded); } catch (Exception ex) { Console.WriteLine(ex); Interlocked.Increment(ref writeFailed); } sw.Stop(); Interlocked.Add(ref writeTotalLatency, sw.ElapsedMilliseconds); Interlocked.Increment(ref writeCalls); } }, writeToken)); } Parallel.ForEach(writeTasks, task => task.Start()); { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; List<Task> tasks = new List<Task>(); for (int i = 0; i < numReadThread; i++) { tasks.Add(new Task(() => { Thread.Sleep(2000); //Console.Write("{0} tasks start" ,i); while (!token.IsCancellationRequested) { Stopwatch sw = Stopwatch.StartNew(); try { long p = Helper.GetRandomAccountID(accountIDs); var accounts = queryable.Where(customer => customer.Value._AccountId == p).ToArray(); foreach (var account in accounts) { // } Interlocked.Increment(ref succeeded); } catch (Exception ex) { Console.WriteLine(ex); Interlocked.Increment(ref failed); } sw.Stop(); Interlocked.Add(ref totalLatency, sw.ElapsedMilliseconds); Interlocked.Increment(ref calls); } }, token)); } Parallel.ForEach(tasks, task => task.Start()); Thread.Sleep(numDuration * 1000 * 60); tokenSource.Cancel(); Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); Console.WriteLine(" Reads:"); Console.WriteLine("averge latency: " + 1.0 * totalLatency / calls + " ms"); Console.WriteLine("throughput: {0} calls/sec", 1.0 * calls / (numDuration * 60)); Console.WriteLine("success rate: {0}, success: {1}, failed: {2}, calls: {3}", 1.0 * succeeded / calls, succeeded, failed, calls); } Reset(); { CancellationTokenSource tokenSource = new CancellationTokenSource(); CancellationToken token = tokenSource.Token; List<Task> tasks = new List<Task>(); for (int i = 0; i < numReadThread; i++) { tasks.Add(new Task(() => { Thread.Sleep(2000); while (!token.IsCancellationRequested) { Stopwatch sw = Stopwatch.StartNew(); try { long p = Helper.GetRandomAccountID(accountIDs); var accounts = queryable.Where(customer => customer.Value._AccountId == p).ToArray(); foreach (var account in accounts) { // } Interlocked.Increment(ref succeeded); } catch (Exception ex) { Console.WriteLine(ex); Interlocked.Increment(ref failed); } sw.Stop(); Interlocked.Add(ref totalLatency, sw.ElapsedMilliseconds); Interlocked.Increment(ref calls); } }, token)); } Parallel.ForEach(tasks, task => task.Start()); Thread.Sleep(numDuration * 1000 * 60); tokenSource.Cancel(); Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); Console.WriteLine(" Reads:"); Console.WriteLine("averge latency: " + 1.0 * totalLatency / calls + " ms"); Console.WriteLine("throughput: {0} calls/sec", 1.0 * calls / (numDuration * 60)); Console.WriteLine("success rate: {0}, success: {1}, failed: {2}, calls: {3}", 1.0 * succeeded / calls, succeeded, failed, calls); } writeTokenSource.Cancel(); Console.Write(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")); Console.WriteLine(" Writes:"); Console.WriteLine("averge latency: " + 1.0 * writeTotalLatency / writeCalls + " ms"); Console.WriteLine("throughput: {0} calls/sec", 1.0 * writeCalls / (numDuration * 60)); Console.WriteLine("success rate: {0}, success: {1}, failed: {2}, calls: {3}", 1.0 * writeSucceeded / writeCalls, writeSucceeded, writeFailed, writeCalls); /*long id = 1; int times = 10000; var stopwatch = new Stopwatch(); stopwatch.Start(); for (int i=0;i<times;i++) { query.Process(cache,id); id = (id + 3) % 100000; } stopwatch.Stop(); long elapsed_time = stopwatch.ElapsedMilliseconds; Console.WriteLine("Finish SQL querying\n"); Console.WriteLine("Preload Time on {0} times using {1} ms", times, elapsed_time); var cache = ignite.GetOrCreateCache<int, string>("myCache");*/ // Store keys in cache (values will end up on different cache nodes). /*for (int i = 0; i < 10; i++) cache.Put(i, i.ToString()); for (int i = 0; i < 10; i++) Console.WriteLine("Got [key={0}, val={1}]", i, cache.Get(i));*/ } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Apache.Ignite.Core; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Query; using Apache.Ignite.Linq; using Apache.Ignite.Core.Cache.Configuration; namespace CacheService { class Query { static void Main(string[] args) { } public void Process(ICache<long, CustomerAccount_ignite> cache,long id) { //var que = cache.AsCacheQueryable(); //IQueryable<ICacheEntry<long, CustomerAccount>> var queryable = cache.AsCacheQueryable( ); var accounts = queryable.Where(customer => customer.Value._AccountId==id).ToArray(); //var sql = new SqlQuery(typeof(CustomerAccount_ignite), "where _AccountId == ?", id); //IQueryCursor<ICacheEntry<long, CustomerAccount_ignite>> accounts = cache.Query(sql); foreach (var account in accounts) { //Console.WriteLine("{0} {1} {2}", account.Value.AccountId, account.Value.AccountName, account.Value.CustomerName); } /* foreach ( var cust in cache.Query(new ScanQuery<int, CustomerAccount>())) { var entry = cust.Value; Console.WriteLine("{0} {1} {2}", entry.CustomerId,entry.CustomerName,entry.CustomerNumber); } //var table = que.Where( x => true).ToArray();*/ } int Query_Func_1() { return 0; } } } <file_sep># Ignite_Accelerate_Aggregate ## What This is Software Engineer internship program among 3 months of Suzhou, Microsoft. The project aim to improve perfomance of U-SQL query from aggregation of databases. ## How Currently , Caching is the first option in our solution. Hi , everyone this is the conclusion of ignite performance test Some Issues: if you want to repeat this experience, follow following step will save your time. Ignite Environment Setting Procedure: 1. Download and unzip Ignite.Net Binary Package 2. Install Java Development Kit (correponding version) 3. Setting IGNITE_HOME to Ignite Package path without trailing "\" 4. Setting JAVA_HOME to Java Development kit 5. Copy and reference shared library in C#, in ./platforms/dotnet/bin/ Iginte Appliance: 1. Ignition.Start([config]) or Ignition.StartFromApplication() load content in app.config 2. Ignition.ClientMode = true for client node 3. Network Configuration: Using TcpDiscoveryStaticIpFinder with form of Ip:47500..47509 Choose correct local Ip address of given adapter! Ensure Client and Server of given IP are bi-directionally inter-connected SQL and Cache Grid: 1. A class is needed to identify a relational table 2. Ignite will call BinarySerialize to compress class into bits, add [Serializable] to class or implement IBinarizable 3. You need to add [QuerySqlField] to field you want to query and [QuerySqlField(IsIndexed = true)] to index them. Pay attention , it must add on the field not property! 4. Datastreamer would accelerate Cache loading. 5. A 3rd party class in ignite supports backend SQL DB as persistent storage. 6. SQL supports durable storage in disk and recovery from failure. Performance Result: Ignite: Read/Write thread Concurrent RW Latency(ms) Only Read Latency(ms) 1 1.3583625653584 1.21158337225596 2 2.24588572485207 2.0436455977463 4 4.12084323815992 4.29124409386553 Ignite client consume too much cpu load and test can only continue to this extent, Server load < 10% during this process , ignite have automatic query thread with quantity of cpu cores, and it could be the bottleneck. The Performance is not good compared OLTP, the problem is that Ignite is not native SQL engine, it's developed from its cache grid and lack of efficiency thus.<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CacheService { class QueryFeed { static void Main(string[] args) { // For test } string GetNextQuery() { return "NotImplement"; } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using Apache.Ignite.Core; using Apache.Ignite.Core.Cache; using System.Diagnostics; using Apache.Ignite.Core.Datastream; namespace CacheService { class PreLoad { static void Main(string[] args) { // Test } public void Process(IDataStreamer<long, CustomerAccount_ignite> streamer) { CustomerAccountsDataContext data = new CustomerAccountsDataContext() ; long cnt = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); data.ObjectTrackingEnabled = false; foreach (var customer in data.CustomerAccounts) { var customer_ignite = new CustomerAccount_ignite(customer); //Console.WriteLine("CustomerName {0}", customer.CustomerName); //cache.Put(cnt, customer_ignite); streamer.AddData(cnt, customer_ignite); cnt += 1; //if (cnt % 1000 == 0) // Console.Write("-"); //if (cnt == 100000) // break; } stopwatch.Stop(); long elapsed_time = stopwatch.ElapsedMilliseconds; Console.WriteLine("Finish Data Loading\n"); Console.WriteLine("Preload Time on {0} rows using {1} ms", cnt, elapsed_time); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CacheService { static class Helper { [ThreadStatic] static Random random = null; private static void EnsureRandom() { if (random == null) { random = new Random(); } } public static long GetRandomAccountID(List<long> accountIDs) { EnsureRandom(); return accountIDs[random.Next(accountIDs.Count)]; } public static IEnumerable<long> GetRandomAccountIDs(List<long> accountIDs, int howMany) { EnsureRandom(); List<long> result = new List<long>(); for (int i = 0; i < howMany; i++) { result.Add(accountIDs[random.Next(accountIDs.Count)]); } return result; } public static string GetRandomString(int length) { EnsureRandom(); const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string(Enumerable.Repeat(chars, length) .Select(s => s[random.Next(s.Length)]).ToArray()); } } }
0ee50cd7999cbb9380b537f7163c02d7d9faacc9
[ "Markdown", "C#" ]
6
C#
qiulingxu/Ignite_Accelerate_Aggregate
28a37bb715350a01951fde9bb50eeaed45d6ef31
7ce36e1055216bf9daf1527e3e84164730fb7ca3
refs/heads/master
<repo_name>miwa-takase9/ProjectPractice12<file_sep>/Printallclassroom.java /** * 教室情報の確認というユースケースの中の基本系列の1つである、”全教室の情報を表示”に対して責任を持つクラス * @author <NAME> * modified by 高瀬美和 * データベースの名前の違いのためにshowResultの””内を自分のデータベースに合わせて変更 */ import java.util.*; import java.sql.*; public class Printallclassroom extends AbstractExecuter { private Scanner scanner = new Scanner(System.in); public String makeQuery() { String query ="SELECT * " + "FROM classroom " + ";"; return query; } public void showResult(ResultSet r) throws SQLException { while(r.next()) { String name = r.getString("classroom_name"); int number = r.getInt("capacity"); int fee = r.getInt("fare"); String place = r.getString("location"); int light = r.getInt("light"); int air = r.getInt("air"); String phonenumber = r.getString("telephone_number"); System.out.println(name + "\t" + number + "\t" + fee + "\t" + place + "\t" + light + "\t" + air + "\t" + phonenumber); } } } <file_sep>/AbstractExecuter.java //基本的に以下の部分はそのまま使えるが、参照するDBの部分は変更の必要あり import java.sql.*; public abstract class AbstractExecuter { public abstract String makeQuery(); public abstract void showResult(ResultSet r) throws SQLException; public final void queryAndShow() { Connection conn = null; try { conn = DriverManager.getConnection( "jdbc:mysql://localhost/Reservation_System?useSSL=false", "root", "" ); Statement st=conn.createStatement(); String sqlString = makeQuery(); ResultSet res=st.executeQuery(sqlString); showResult(res); res.close(); st.close(); conn.close(); } catch (SQLException se) { System.out.println("SQL Error 1: " + se.toString() + " " + se.getErrorCode() + " " + se.getSQLState()); } catch (Exception e) { System.out.println("Error: " + e.toString() + e.getMessage()); } } } <file_sep>/cy18235.sql -- MySQL dump 10.13 Distrib 8.0.19, for macos10.15 (x86_64) -- -- Host: localhost Database: Reservation_System -- ------------------------------------------------------ -- Server version 8.0.19 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!50503 SET NAMES utf8mb4 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `Classroom` -- DROP TABLE IF EXISTS `Classroom`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `Classroom` ( `classroom_name` char(20) NOT NULL, `capacity` int DEFAULT NULL, `fare` int DEFAULT NULL, `location` char(10) DEFAULT NULL, `light` int DEFAULT NULL, `air` int DEFAULT NULL, `telephone_number` char(20) DEFAULT NULL, PRIMARY KEY (`classroom_name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `Classroom` -- LOCK TABLES `Classroom` WRITE; /*!40000 ALTER TABLE `Classroom` DISABLE KEYS */; INSERT INTO `Classroom` VALUES ('2101',100,400,'大宮',1,1,'476832020'),('2202',70,200,'田町',1,0,'367222600'),('2203',100,300,'大宮',1,1,'476832020'),('2301',100,300,'豊洲',0,1,'358597000'),('3101',70,100,'豊洲',0,0,'358597000'),('斎藤記念館',400,800,'大宮',1,1,'476832020'); /*!40000 ALTER TABLE `Classroom` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `external` -- DROP TABLE IF EXISTS `external`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `external` ( `telephone_number` char(20) NOT NULL, `profession` char(30) DEFAULT NULL, PRIMARY KEY (`telephone_number`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `external` -- LOCK TABLES `external` WRITE; /*!40000 ALTER TABLE `external` DISABLE KEYS */; INSERT INTO `external` VALUES ('435468409','会社員'),('578689523','デザイナー'); /*!40000 ALTER TABLE `external` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `Reservation` -- DROP TABLE IF EXISTS `Reservation`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `Reservation` ( `classroom_name` char(20) NOT NULL, `telephone_number` char(20) NOT NULL, `content` char(20) DEFAULT NULL, `date` datetime DEFAULT NULL, `time` int DEFAULT NULL, `lighting_time` int DEFAULT NULL, `usage_fee` int DEFAULT NULL, `carry` int DEFAULT NULL, `car` int DEFAULT NULL, `approval` int DEFAULT NULL, `contact` int DEFAULT NULL, PRIMARY KEY (`classroom_name`,`telephone_number`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `Reservation` -- LOCK TABLES `Reservation` WRITE; /*!40000 ALTER TABLE `Reservation` DISABLE KEYS */; INSERT INTO `Reservation` VALUES ('2101','0801111111','','2012-08-09 00:00:00',100,0,0,0,0,1,0),('2101','0801112222','サークル','2020-07-22 09:00:12',20,0,0,0,0,0,0),('2101','801112222','基礎力学','2020-07-20 09:00:00',100,100,0,0,0,1,1),('2101','802223333','微分積分','2020-07-20 09:00:00',100,100,0,0,0,2,0),('2202','903334444','線形代数','2020-07-21 10:50:00',100,100,0,0,0,0,0),('2203','904445555','地域活動','2020-07-25 10:00:00',60,60,800,1,1,0,0),('2301','905556666','英語購読','2020-07-21 10:50:00',100,100,0,0,0,0,0),('2301','906667777','中国語','2020-07-22 13:10:00',100,100,0,0,0,0,0),('3101','907778888','部活','2020-07-20 18:40:00',120,120,0,1,1,2,0),('斉藤記念館','435468409','講演会','2020-07-26 13:00:00',180,180,10000,1,1,0,0),('斉藤記念館','578689523','リハーサル','2020-07-27 15:00:00',180,180,0,1,1,0,0),('斉藤記念館','908889999','基礎表現演習','2020-07-22 15:00:00',100,100,0,1,0,0,0); /*!40000 ALTER TABLE `Reservation` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `student` -- DROP TABLE IF EXISTS `student`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `student` ( `telephone_number` char(20) NOT NULL, `studentID` char(20) DEFAULT NULL, PRIMARY KEY (`telephone_number`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `student` -- LOCK TABLES `student` WRITE; /*!40000 ALTER TABLE `student` DISABLE KEYS */; INSERT INTO `student` VALUES ('801112222','cy18301'),('802223333','cy18302'),('903334444','cy18203'),('904445555','cy18204'); /*!40000 ALTER TABLE `student` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `Student_Section` -- DROP TABLE IF EXISTS `Student_Section`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `Student_Section` ( `telephone_number` char(20) NOT NULL, `place` char(30) DEFAULT NULL, `campus` char(10) DEFAULT NULL, `person` char(20) DEFAULT NULL, PRIMARY KEY (`telephone_number`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `Student_Section` -- LOCK TABLES `Student_Section` WRITE; /*!40000 ALTER TABLE `Student_Section` DISABLE KEYS */; INSERT INTO `Student_Section` VALUES (' 03-5859-7000','〒135-8548 東京都江東区豊洲3丁目7−5','豊洲','遠藤'),(' 03-6722-2600','〒108-8548 東京都港区芝浦3-9-14','芝浦','石田'),(' 048-683-2020','〒337-8570 埼玉県さいたま市見沼区大字深作307番地','大宮','伊藤'); /*!40000 ALTER TABLE `Student_Section` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `teacher` -- DROP TABLE IF EXISTS `teacher`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `teacher` ( `telephone_number` char(20) NOT NULL, `teacherID` char(20) DEFAULT NULL, PRIMARY KEY (`telephone_number`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `teacher` -- LOCK TABLES `teacher` WRITE; /*!40000 ALTER TABLE `teacher` DISABLE KEYS */; INSERT INTO `teacher` VALUES ('905556666','t001'),('906667777','t002'),('907778888','t003'),('908889999','t004'); /*!40000 ALTER TABLE `teacher` ENABLE KEYS */; UNLOCK TABLES; -- -- Table structure for table `user` -- DROP TABLE IF EXISTS `user`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `user` ( `telephone_number` char(20) NOT NULL, `name` char(20) DEFAULT NULL, PRIMARY KEY (`telephone_number`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `user` -- LOCK TABLES `user` WRITE; /*!40000 ALTER TABLE `user` DISABLE KEYS */; INSERT INTO `user` VALUES ('435468409','松田恵美'),('578689523','斎藤佳代子'),('801112222','野田真由美'),('802223333','芥川敦'),('903334444','松本清'),('904445555','内久保綾子'),('905556666','青木太輔'),('906667777','佐々木洋子'),('907778888','倉持剛'),('908889999','山崎和義'); /*!40000 ALTER TABLE `user` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-08-08 16:50:41
387839a06645eb4498f1fd10a7ea6527bf9b78f7
[ "Java", "SQL" ]
3
Java
miwa-takase9/ProjectPractice12
b251db1389e91f6a76bee2d2e59f61ada9f8829c
4dea7434d56096b6b06a6c55d6d50577228f1019
refs/heads/master
<repo_name>ozod9/reallaba<file_sep>/2scr4.sh #!/bin/bash grep bin < $1 >&2 <file_sep>/1scr2.sh #!/bin/bash find ~ -maxdepth 1 -name '*.txt' |wc -l| cut -f1 -d' ' <file_sep>/2scr1.sh #!/bin/bash wc -l /tmp/run.log | cut -d' ' -f1 >&2 date >> /tmp/run.log echo "Hello" <file_sep>/3scr6.sh #!/bin/bash echo "$USER$HOME" > ./ffd echo -n "$USER $HOME " > ./ffd wc -c ffd | cut -d' ' -f1 >> ./ffd cat ./ffd rm ./ffd <file_sep>/1scr9.sh #!/bin/bash ps -ely | sort -r -k8 | head -6 | tr -s ' ' ' '| cut -d' ' -f13 <file_sep>/2scr2.sh #!/bin/bash ./logger less /tmp/run.log <file_sep>/1scr4.sh +#!/bin/bash +echo "Доброе утро!" +date | cut -d' ' -f4 +cal +cat ~/TODO <file_sep>/1scr8.sh #!/bin/bash echo 'Процессов пользователя' whoami ps axu | grep $USER | wc -l| cut -d ' ' -f1 echo 'Процессов пользователя root' ps axu | grep root | wc -l| cut -d ' ' -f1 <file_sep>/3scr5.sh #!/bin/bash grep -n -m"$3" "$1" "$2" | sort -k2 <file_sep>/1scr10.sh #!/bin/bash du ~ -d1 | sort -n <file_sep>/2scr3.sh #!/bin/bash grep 000000 ~/bash.txt > /tmp/zeros grep -v 000000 ~/bash.txt > /tmp/nozeros head /tmp/zeros tail /tmp/zeros head /tmp/nozeros tail /tmp/nozeros <file_sep>/3scr3.sh #!/bin/bash "$1" 1 2 3 "$1" @RANDOM @RANDOM @RANDOM @RANDOM @RANDOM "$1" foo "$1" bar "$1" foobar "$1" "foo bar" "$1" --foo "$1" --help "$1" -l
cd2a59ecb1907467603eb0e31c28cd1dd2e76105
[ "Shell" ]
12
Shell
ozod9/reallaba
6b6c113add1d21f9f191b4a69a6f3ca7e0a6fc09
f88bbd9ba981b8f13e1d6cacb4111d0802ac98fc
refs/heads/main
<repo_name>ZhiliShen/SiZeLet<file_sep>/config.py # -*- coding: utf-8 -*- # # @Time : 2021-05-10 11:40 # @Email : <EMAIL> # @Author : <NAME> # @File : config.py # @Notice : import argparse def get_argument(): parser = argparse.ArgumentParser() # Directory option parser.add_argument('--train_data_root', type=str, default='./product_fit/train.txt') parser.add_argument('--test_data_root', type=str, default='./product_fit/test.txt') parser.add_argument('--output_data_root', type=str, default='./output/output.txt') parser.add_argument('--vocab_dir', type=str, default='./cache') parser.add_argument('--saved_models_dir', type=str, default='./saved_models') # Model parameters parser.add_argument('--body_type', type=int, default=7) parser.add_argument('--category', type=int, default=68) parser.add_argument('--rented_for', type=int, default=9) parser.add_argument('--user_id', type=int, default=105571) parser.add_argument('--item_id', type=int, default=5850) parser.add_argument('--user_embedding_dim', type=int, default=10) parser.add_argument('--item_embedding_dim', type=int, default=10) parser.add_argument('--review_embedding_dim', type=int, default=100) parser.add_argument('--kernel_sizes', type=list, default=[3, 4, 5]) parser.add_argument('--num_channels', type=list, default=[100, 100, 100]) parser.add_argument('--num_hidden', type=int, default=100) parser.add_argument('--num_layers', type=int, default=2) parser.add_argument('--user_numeric_num', type=int, default=5) parser.add_argument('--item_numeric_num', type=int, default=2) parser.add_argument('--activation', type=str, default="relu") parser.add_argument('--dropout', type=float, default=0.3) parser.add_argument('--num_targets', type=int, default=3) parser.add_argument('--num_epochs', type=int, default=20) parser.add_argument('--lr', type=float, default=0.0005) parser.add_argument('--vocab_name', type=str, default='twitter.27B') parser.add_argument('--vocab_embedding_dim', type=int, default=100) parser.add_argument('--train_test_proportion', type=float, default=0.8) parser.add_argument('--batch_size', type=int, default=128) parser.add_argument('--max_norm', type=float, default=1.0) parser.add_argument('--user_item_embedding_flag', type=bool, default=True) parser.add_argument('--TextCNNorBiRNN', type=str, default='TextCNN') parser.add_argument('--max_length_sentence', type=int, default=300) parser.add_argument('--min_frequency', type=int, default=400) parser.add_argument('--use_pretrained_model', type=bool, default=False) return parser <file_sep>/README.md ![](https://img.shields.io/badge/pytorch-1.7.0-orange.svg) ![](https://img.shields.io/badge/sklearn-0.24.2-brightgreen.svg) ![](https://img.shields.io/badge/pandas-1.1.5-blue.svg) # SiZeLet The implementation of SiZeLet (SZL) proposed in the paper [*Everything Can Be Embedded*](https://github.com/ZhiliShen/SiZeLet/blob/main/paper/Everything%20Can%20Be%20Embedded.pdf) by <NAME>. ## Prerequisites 1. Create *`./output`*, *`./cache`*, *`./saved_models`* under the project folder 2. Download the **Product Fit** dataset from this [link](https://cs.nju.edu.cn/liyf/aml21/product_fit.zip), and unzip it in the project folder. 3. Download the **GloVE Word Embedding** from this [link](https://apache-mxnet.s3.cn-north-1.amazonaws.com.cn/gluon/embeddings/glove/glove.twitter.27B.zip), move it to the *`./cache`* folder after unzipping *glove.twitter.27B.zip*. ## Model Architecture of SiZeLet <br> <img src="images/SiZeLet.png" width="500"/> <br> ## Usage 1. You can configure SiZeLet in *`config.py`*, SiZeLet has these options: * **train_test_proportion**: proportion of training set and validation set. * **TextCNNorBiRNN**: use textCNN or BiRNN. * **max_length_sentence**: the length of the longest sentence. * **min_frequency**: words with word frequency lower than this number will be deleted. * **use_pretrained_model**: whether to use a pre-trained model. * **user_embedding_dim**: user discrete attribute embedding dimension. * **item_embedding_dim**: item discrete attribute embedding dimension. * **review_embedding_dim**: review discrete attribute embedding dimension. * **kernel_sizes**: textCNN convolution kernel size. * **num_channels**: textCNN channel size. * **num_hidden**: BiRNN hidden layer dimension. * **num_layers**: BiRNN hidden layer number. * **lr**: learing rate. 2. Run *`train.py`* file ``` python train.py ``` 3. The result will appear in *`./output/output.txt`* ## Performance on Validation Set F1-score | Accuracy | AUC | |:--------:|:--------:|:-----:| | 0.713 | 0.831 | 0.886 | <file_sep>/train.py # -*- coding: utf-8 -*- # # @Time : 2021-05-04 12:38 # @Email : <EMAIL> # @Author : <NAME> # @File : train.py # @Notice : import os import torch import numpy as np import torch.nn as nn import torchtext.vocab as Vocab from torch.utils.data import DataLoader, random_split from model import SiZeLet from dataset import ProductFitDataset from utils import device, train, predict, process_data, load_pretrained_embedding from config import get_argument opt = get_argument().parse_args() trainDataRoot = opt.train_data_root testDataRoot = opt.test_data_root if __name__ == '__main__': glove_vocab = Vocab.GloVe(name=opt.vocab_name, dim=opt.vocab_embedding_dim, cache=opt.vocab_dir) train_data, test_data, num2fit, vocab = process_data(trainDataRoot, testDataRoot) product_fit_labeled_data = ProductFitDataset(train_data) product_fit_unlabeled_data = ProductFitDataset(test_data, train=False) labeled_dataset_size = len(product_fit_labeled_data) train_size = int(np.floor(opt.train_test_proportion * labeled_dataset_size)) valid_size = labeled_dataset_size - train_size train_dataset, valid_dataset = random_split(product_fit_labeled_data, [train_size, valid_size]) train_data_loader = DataLoader( dataset=train_dataset, batch_size=opt.batch_size, shuffle=True ) valid_data_loader = DataLoader( dataset=valid_dataset, batch_size=opt.batch_size, shuffle=False ) test_data_loader = DataLoader( dataset=product_fit_unlabeled_data, batch_size=1, shuffle=False, ) net = SiZeLet(vocab) if opt.use_pretrained_model: saved_models = os.listdir(opt.saved_models_dir) if len(saved_models) == 0: raise Exception("Oops, the saved models dir is empty, please train the model from scratch.") else: net = net.to(device) net.load_state_dict(torch.load(os.path.join(opt.saved_models_dir, saved_models[-1]))) print("We have trained the model: {:s}!".format(saved_models[-1])) else: net.review_transform_blocks.embedding.weight.data.copy_( load_pretrained_embedding(vocab.itos, glove_vocab) ) if opt.TextCNNorBiRNN == 'TextCNN': net.review_transform_blocks.constant_embedding.weight.data.copy_( load_pretrained_embedding(vocab.itos, glove_vocab) ) net.review_transform_blocks.constant_embedding.weight.requires_grad = False else: net.review_transform_blocks.embedding.weight.requires_grad = False optimizer = torch.optim.Adam(params=filter(lambda p: p.requires_grad, net.parameters()), lr=opt.lr) loss = nn.CrossEntropyLoss() train(train_data_loader, valid_data_loader, net, loss, optimizer, opt.num_epochs) print("We have trained the model!") predict(test_data_loader, net, num2fit) print("We have written outputs to file!") <file_sep>/model.py # -*- coding: utf-8 -*- # # @Time : 2021-05-03 23:37 # @Email : <EMAIL> # @Author : <NAME> # @File : model.py # @Notice : import torch import torch.nn as nn import torch.nn.functional as F from config import get_argument opt = get_argument().parse_args() class SiZeLet(nn.Module): def __init__(self, vocab): super(SiZeLet, self).__init__() self.vocab = vocab self.body_type_embedding = nn.Embedding( num_embeddings=opt.body_type, embedding_dim=opt.user_embedding_dim, max_norm=opt.max_norm ) self.category_embedding = nn.Embedding( num_embeddings=opt.category, embedding_dim=opt.item_embedding_dim, max_norm=opt.max_norm ) self.rented_for_embedding = nn.Embedding( num_embeddings=opt.rented_for, embedding_dim=opt.item_embedding_dim, max_norm=opt.max_norm ) self.item_id_embedding = nn.Embedding( num_embeddings=opt.item_id, embedding_dim=opt.item_embedding_dim, max_norm=opt.max_norm ) user_feature = 1 * opt.user_embedding_dim + opt.user_numeric_num self.user_transform_way = [user_feature, 64, 32] self.user_transform_blocks = [] for i in range(1, len(self.user_transform_way)): self.user_transform_blocks.append( ResBlock( self.user_transform_way[i - 1], self.user_transform_way[i], opt.activation, ) ) self.user_transform_blocks.append(nn.Dropout(p=opt.dropout)) self.user_transform_blocks = nn.Sequential(*self.user_transform_blocks) item_feature = 3 * opt.item_embedding_dim + opt.item_numeric_num self.item_transform_way = [item_feature, 64, 32] self.item_transform_blocks = [] for i in range(1, len(self.item_transform_way)): self.item_transform_blocks.append( ResBlock( self.item_transform_way[i - 1], self.item_transform_way[i], opt.activation, ) ) self.item_transform_blocks.append(nn.Dropout(p=opt.dropout)) self.item_transform_blocks = nn.Sequential(*self.item_transform_blocks) if opt.TextCNNorBiRNN == 'TextCNN': self.review_transform_blocks = TextCNN(self.vocab, opt.review_embedding_dim, opt.kernel_sizes, opt.num_channels) else: self.review_transform_blocks = BiRNN(self.vocab, opt.review_embedding_dim, opt.num_hidden, opt.num_layers) if opt.user_item_embedding_flag: combined_layer_input_size = 32 + 32 + 64 self.combined_transform_way = [combined_layer_input_size, 64, 32] else: combined_layer_input_size = 64 self.combined_transform_way = [combined_layer_input_size, 32, 16] self.combined_blocks = [] for i in range(1, len(self.combined_transform_way)): self.combined_blocks.append( ResBlock( self.combined_transform_way[i - 1], self.combined_transform_way[i], opt.activation, ) ) self.combined_blocks.append(nn.Dropout(p=opt.dropout)) self.combined_blocks = nn.Sequential(*self.combined_blocks) self.hidden2output = nn.Linear(self.combined_transform_way[-1], opt.num_targets) def forward(self, batch_input): # User Transform Way body_type_emb = self.body_type_embedding(batch_input["body type"]) user_representation = torch.cat( [body_type_emb, batch_input["user_numeric"]], dim=-1 ) user_representation = self.user_transform_blocks(user_representation) # Item Transform Way rented_for_emb = self.rented_for_embedding(batch_input["rented for"]) item_id_emb = self.item_id_embedding(batch_input["item_id"]) category_emb = self.category_embedding(batch_input["category"]) item_representation = torch.cat( [category_emb, rented_for_emb, item_id_emb, batch_input["item_numeric"]], dim=-1 ) item_representation = self.item_transform_blocks(item_representation) # Review Transform Way review_representation = self.review_transform_blocks(batch_input["review"]) # Combine the Transform Ways if opt.user_item_embedding_flag: combined_representation = torch.cat( [user_representation, item_representation, review_representation], dim=-1 ) else: combined_representation = review_representation combined_representation = self.combined_blocks(combined_representation) # Output layer of logit and pred_prob logit = self.hidden2output(combined_representation) pred_prob = F.softmax(logit, dim=-1) return logit, pred_prob class ResBlock(nn.Module): def __init__(self, input_dim, output_dim, activation): super(ResBlock, self).__init__() if activation == "relu": self.activation = F.relu elif activation == "tanh": self.activation = F.tanh self.inp_transform = nn.Linear(input_dim, output_dim) self.out_transform = nn.Linear(output_dim, output_dim) self.inp_projection = nn.Linear(input_dim, output_dim) def forward(self, x): y = self.activation(self.inp_transform(x)) z = self.activation(self.out_transform(y) + self.inp_projection(x)) return z class GlobalMaxPool1d(nn.Module): def __init__(self): super(GlobalMaxPool1d, self).__init__() def forward(self, x): return F.max_pool1d(x, kernel_size=x.shape[2]) class TextCNN(nn.Module): def __init__(self, vocab, embed_size, kernel_sizes, num_channels): super(TextCNN, self).__init__() self.embedding = nn.Embedding(len(vocab), embed_size) self.constant_embedding = nn.Embedding(len(vocab), embed_size) self.dropout = nn.Dropout(opt.dropout) self.decoder = nn.Linear(sum(num_channels), 64) self.pool = GlobalMaxPool1d() self.convs = nn.ModuleList() for c, k in zip(num_channels, kernel_sizes): self.convs.append(nn.Conv1d(in_channels=2 * embed_size, out_channels=c, kernel_size=k)) def forward(self, inputs): embeddings = torch.cat((self.embedding(inputs), self.constant_embedding(inputs)), dim=2) embeddings = embeddings.permute(0, 2, 1) encoding = torch.cat([self.pool(F.relu(conv(embeddings))).squeeze(-1) for conv in self.convs], dim=1) outputs = self.decoder(self.dropout(encoding)) return outputs class BiRNN(nn.Module): def __init__(self, vocab, embed_size, num_hidden, num_layers): super(BiRNN, self).__init__() self.embedding = nn.Embedding(len(vocab), embed_size) self.encoder = nn.LSTM(input_size=embed_size, hidden_size=num_hidden, num_layers=num_layers, bidirectional=True) self.decoder = nn.Linear(4 * num_hidden, 64) def forward(self, inputs): embeddings = self.embedding(inputs.permute(1, 0)) outputs, _ = self.encoder(embeddings) encoding = torch.cat((outputs[0], outputs[1]), -1) outputs = self.decoder(encoding) return outputs <file_sep>/dataset.py # -*- coding: utf-8 -*- # # @Time : 2021-05-04 18:47 # @Email : <EMAIL> # @Author : <NAME> # @File : dataset.py # @Notice : import numpy as np from torch.utils.data import Dataset class ProductFitDataset(Dataset): def __init__(self, data, train=True): self.data = data self.train = train def __len__(self): return len(self.data) def __getitem__(self, item): features = { "body type": np.asarray(self.data["body type"][item], dtype=np.int64), "user_numeric": np.asarray( [self.data[feature][item] for feature in ["age", "height", "weight", "bust size a", "bust size b"]], dtype=np.float32), "category": np.asarray(self.data["category"][item], dtype=np.int64), "rented for": np.asarray(self.data["rented for"][item], dtype=np.int64), "item_id": np.asarray(self.data["item_id"][item], dtype=np.int64), "item_numeric": np.asarray( [self.data[feature][item] for feature in ["rating", "size"]], dtype=np.float32), "review": np.asarray(self.data["review"][item], dtype=np.int64) } if self.train: label = np.asarray(self.data["fit"][item], dtype=np.int64) return features, label else: return features if __name__ == "__main__": pass <file_sep>/utils.py # -*- coding: utf-8 -*- # # @Time : 2021-05-02 19:24 # @Email : <EMAIL> # @Author : <NAME> # @File : utils.py # @Notice : import os import re import time import torch import collections import numpy as np import pandas as pd import torchtext.vocab as Vocab from sklearn import metrics from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler from sklearn.preprocessing import OrdinalEncoder from config import get_argument opt = get_argument().parse_args() trainDataRoot = opt.train_data_root testDataRoot = opt.test_data_root cacheDir = opt.vocab_dir vocab = None device = torch.device("cuda" if torch.cuda.is_available() else "cpu") def tokenized(text): return [tok.lower() for tok in text.split(' ')] def get_tokenized_product_fit(data): return [tokenized(review) for review in data] def get_vocab_product_fit(data): tokenize_data = get_tokenized_product_fit(data) counter = collections.Counter([tk for st in tokenize_data for tk in st]) return Vocab.Vocab(counter, min_freq=opt.min_frequency) def pre_process_product_fit(words): max_l = opt.max_length_sentence def pad(x): return x[:max_l] if len(x) > max_l else x + [0] * (max_l - len(x)) tokenize_words = tokenized(words) features = pad([vocab.stoi[word] for word in tokenize_words]) return features def bust_size2vec(bust_size): alpha_bust_sizes = ['aa', 'a', 'b', 'c', 'd', 'd+', 'dd', 'ddd/e', 'f', 'g', 'h', 'i', 'j'] numeric_bust_sizes = [num for num in range(len(alpha_bust_sizes))] bust_size2num_dict = {alpha_bust_size: numeric_bust_size for alpha_bust_size, numeric_bust_size in zip(alpha_bust_sizes, numeric_bust_sizes)} bust_size_a = int(bust_size[:2]) bust_size_b = bust_size2num_dict[bust_size[2:]] return bust_size_a, bust_size_b def height2num(height): height_pattern = re.compile(r"(\d)' (\d{1,2})") height_results = height_pattern.search(height) feet_num = height_results.group(1) inch_num = height_results.group(2) metres = int(feet_num) * 0.3048 + int(inch_num) * 0.0254 return metres def weight2num(weight): weight_pattern = re.compile(r"(\d{1,4})") weight_results = weight_pattern.search(weight) weight_num = weight_results.group(1) metres = int(weight_num) return metres def transform(data): data[['bust size a', 'bust size b']] = data['bust size'].apply(bust_size2vec).apply(pd.Series) data['height'] = data['height'].apply(height2num) data['weight'] = data['weight'].apply(weight2num) data['review'] = data['review_summary'] + data['review_text'] data['review'] = data['review'].apply(pre_process_product_fit) data.drop(['bust size', 'review_date', 'review_summary', 'review_text'], axis=1, inplace=True) def get_vocab(data): global vocab vocab = get_vocab_product_fit(data['review']) def get_attr_num(data): attr_cols = data.select_dtypes(include=['int64']) attr_num_dict = {} for col in attr_cols: attr_num_dict[col] = len(data[col].unique()) return attr_num_dict def load_pretrained_embedding(words, pretrained_vocab): embed = torch.zeros(len(words), pretrained_vocab.vectors[0].shape[0]) oov_count = 0 for i, word in enumerate(words): try: idx = pretrained_vocab.stoi[word] embed[i, :] = pretrained_vocab.vectors[idx] except KeyError: oov_count += 0 if oov_count > 0: print("Oops! there are {:d} oov words".format(oov_count)) return embed def train(train_iter, valid_iter, net, loss, optimizer, num_epochs): net = net.to(device) print("training on", device) batch_count = 0 for epoch in range(num_epochs): train_l_sum, train_acc_sum, n, start = 0.0, 0.0, 0, time.time() for x, y in train_iter: for k, v in x.items(): if torch.is_tensor(v): x[k] = v.to(device) y = y.to(device) y_hat, pred_probs = net(x) l = loss(y_hat, y) optimizer.zero_grad() l.backward() optimizer.step() train_l_sum += l.cpu().item() train_acc_sum += (y_hat.argmax(dim=1) == y).sum().cpu().item() n += y.shape[0] batch_count += 1 valid_acc, f1_score, auc = evaluate_accuracy(valid_iter, net) torch.save(net.state_dict(), os.path.join(opt.saved_models_dir, '{:s}-f1_score{:.3f}-epoch{:d}.pt'.format(opt.TextCNNorBiRNN, f1_score, epoch+1))) print('epoch: {:d}, loss: {:.5f}, train accuracy: {:.3f}, valid accuracy: {:.3f}, valid f1 score: {:.3f}, ' 'test auc: {:.3f}, time: {:.1f} ' 'sec.'.format( epoch + 1, train_l_sum / batch_count, train_acc_sum / n, valid_acc, f1_score, auc, time.time() - start)) def evaluate_accuracy(data_iter, net): acc_sum, n = 0.0, 0 preds = [] target = [] pred_probs = [] with torch.no_grad(): for x, y in data_iter: for k, v in x.items(): if torch.is_tensor(v): x[k] = v.to(device) net.eval() y = y.to(device) y_hat, pred_prob = net(x) acc_sum += (y_hat.argmax(dim=1) == y.to(device)).float().sum().cpu().item() n += y.shape[0] preds.append(y_hat.argmax(dim=1).cpu().numpy()) pred_probs.append(pred_prob.cpu().data.numpy()) target.append(y.cpu().numpy()) net.train() pred_tracker = np.stack(preds[:-1]).reshape(-1) target_tracker = np.stack(target[:-1]).reshape(-1) pred_probs_tracker = np.stack(pred_probs[:-1], axis=0).reshape(-1, 3) f1_score = metrics.f1_score(target_tracker, pred_tracker, average="macro") auc = metrics.roc_auc_score(target_tracker, pred_probs_tracker, average="macro", multi_class="ovr") return acc_sum / n, f1_score, auc def predict(test_iter, net, num2fit): preds = [] with torch.no_grad(): for x in test_iter: for k, v in x.items(): if torch.is_tensor(v): x[k] = v.to(device) net.eval() y_hat, pred_prob = net(x) preds.append(y_hat.argmax(dim=1).cpu().numpy()) net.train() preds = np.stack(preds[:]).reshape(-1) preds = [num2fit[i] for i in preds] preds = [line + "\n" for line in preds[:-1]] + [preds[-1]] with open(opt.output_data_root, "w") as f: f.writelines(preds) def process_data(train_data_root, test_data_root): train_data = pd.read_csv(train_data_root) test_data = pd.read_csv(test_data_root) numeric_col = train_data.select_dtypes(include=['float64', 'int64']) numeric_col_with_null = [col_name for col_name in numeric_col if train_data[col_name].isnull().any()] string_col = train_data.select_dtypes(include=['object']) string_col_with_null = [col_name for col_name in string_col if train_data[col_name].isnull().any()] median_imputer = SimpleImputer(missing_values=np.nan, strategy='median') frequent_imputer = SimpleImputer(missing_values=np.nan, strategy='most_frequent') for col in numeric_col_with_null: median_imputer.fit(np.array(train_data[col]).reshape(-1, 1)) train_data[col] = median_imputer.transform(np.array(train_data[col]).reshape(-1, 1)).squeeze() test_data[col] = median_imputer.transform(np.array(test_data[col]).reshape(-1, 1)).squeeze() for col in string_col_with_null: frequent_imputer.fit(np.array(train_data[col]).reshape(-1, 1)) train_data[col] = frequent_imputer.transform(np.array(train_data[col]).reshape(-1, 1)).squeeze() test_data[col] = frequent_imputer.transform(np.array(test_data[col]).reshape(-1, 1)).squeeze() train_test_data = pd.concat([train_data, test_data]) train_test_data['review'] = train_test_data['review_summary'] + train_test_data['review_text'] get_vocab(train_test_data) transform(train_data) transform(test_data) numeric_col = train_data.select_dtypes(include=['float64', 'int64']) numeric_col_names = [col_name for col_name in numeric_col if col_name != 'item_id' and col_name != 'user_id'] string_col = train_data.select_dtypes(include=['object']) string_col_names = [col_name for col_name in string_col if col_name != 'review' and col_name != 'fit'] string_col_names.extend(['user_id', 'item_id']) train_test_data = pd.concat([train_data, test_data]) scaler = StandardScaler() scaler.fit(train_test_data.loc[:, numeric_col_names]) train_data_numeric = pd.DataFrame(scaler.transform(train_data.loc[:, numeric_col_names]), columns=numeric_col_names) test_data_numeric = pd.DataFrame(scaler.transform(test_data.loc[:, numeric_col_names]), columns=numeric_col_names) ordinal_enc = OrdinalEncoder() ordinal_enc.fit(train_test_data.loc[:, string_col_names]) train_data_categorical = pd.DataFrame(np.array(ordinal_enc.transform(train_data.loc[:, string_col_names]), dtype=np.int64), columns=string_col_names) test_data_categorical = pd.DataFrame(np.array(ordinal_enc.transform(test_data.loc[:, string_col_names]), dtype=np.int64), columns=string_col_names) ordinal_enc.fit(np.array(train_data['fit']).reshape(-1, 1)) train_data['fit'] = np.array(ordinal_enc.transform(np.array(train_data['fit']).reshape(-1, 1)).squeeze(), dtype=np.int64) num2fit = {num: fit for num, fit in zip([0, 1, 2], ordinal_enc.inverse_transform([[0], [1], [2]]).squeeze())} processed_train_data = pd.concat( [train_data_numeric, train_data_categorical, train_data[['review', 'fit']]], axis=1) processed_test_data = pd.concat( [test_data_numeric, test_data_categorical, test_data[['review']]], axis=1) global vocab return processed_train_data, processed_test_data, num2fit, vocab if __name__ == '__main__': pass
78763f949d2463319100e6b45b528e0a5f8f9d73
[ "Markdown", "Python" ]
6
Python
ZhiliShen/SiZeLet
1f8b4c0bd9dd5eb85b5010673ed3e2f47c8037d3
17bdcce096cecdc895bcb3ed669ecb9a06db44bc
refs/heads/master
<repo_name>HemantArya/Tic-Tac-Toe<file_sep>/main.py class TicTacToe: def __init__(self): self.gameList = [ ['_', '_', '_'], ['_', '_', '_'], ['_', '_', '_'], ] self.gameMsg = [ 'Draw', 'X wins', 'O wins', ] self.errMsg = [ 'This cell is occupied! Choose another one!', 'You should enter numbers!', 'Coordinates should be from 1 to 3!' ] def printGameList(self): print("---------") [print('| ' + ' '.join(row) + ' |') for row in self.gameList] print("---------") def isXwins(self): for row in self.gameList: if row.count('X') == 3: return True for col in zip(*self.gameList): if col.count('X') == 3: return True a = self.gameList[0][0] b = self.gameList[1][1] c = self.gameList[2][2] if a == b and b == c and c == 'X': return True a = self.gameList[0][2] b = self.gameList[1][1] c = self.gameList[2][0] if a == b and b == c and c == 'X': return True return False def isOwins(self): for row in self.gameList: if row.count('O') == 3: return True for col in zip(*self.gameList): if col.count('O') == 3: return True a = self.gameList[0][0] b = self.gameList[1][1] c = self.gameList[2][2] if a == b and b == c and c == 'O': return True a = self.gameList[0][2] b = self.gameList[1][1] c = self.gameList[2][0] if a == b and b == c and c == 'O': return True return False def isFinished(self): if self.gameList[0].count('_') + self.gameList[1].count('_') + self.gameList[2].count('_') > 0: return False return True def inputCoordinates(self, turn): coordinates = input("Enter the coordinates:") if len(coordinates) == 3 and coordinates[0] in '123' and coordinates[1] == ' ' and coordinates[2] in '123': a, b = coordinates.split() a, b = int(a), int(b) if a < 1 or a > 3 or b < 1 or b > 3: print(self.errMsg[2]) self.inputCoordinates(turn) elif self.gameList[b - 1][a - 1] != '_': print(self.errMsg[0]) self.inputCoordinates(turn) else: self.gameList[b - 1][a - 1] = turn else: print(self.errMsg[1]) self.inputCoordinates(turn) def start(self): self.printGameList() turn = 'X' while not any([self.isXwins(), self.isOwins(), self.isFinished()]): self.gameList.reverse() self.inputCoordinates(turn) self.gameList.reverse() self.printGameList() if turn == 'X': turn = 'O' else: turn = 'X' if self.isXwins(): print(self.gameMsg[1]) elif self.isOwins(): print(self.gameMsg[2]) else: print(self.gameMsg[0]) game = TicTacToe() game.start()
90146efc56b2728c01e3074a01ca47f8fef01630
[ "Python" ]
1
Python
HemantArya/Tic-Tac-Toe
25b1ed509907acad37ab5133a667acacc981719c
3cf41e640f009bbe57055b3eb7126a612ed04688
refs/heads/master
<file_sep>$(function () { $('.menu__btn').on('click', function () { $('.header__list').slideToggle(); }); $('.slider').slick({ dots: false, infinite: false, arrows: true, slidesToShow: 3, slidesToScroll: 1, variableWidth: true }); new WOW().init(); });
c5e68d2a579a7270123c01d5f4532f75201363cb
[ "JavaScript" ]
1
JavaScript
Efrem4ik/pegasus
5dae35687e5ba2926e96febe65f2149852466e93
c9243a23e4139850d05b999d62c350b001b62ae5
refs/heads/master
<file_sep>require 'test/unit' require 'test/test_helper' class GitRepositoryTest < Test::Unit::TestCase def test_type assert_equal('git', GitRepository.new(nil).scm_type) end uses_mocha 'test_git_system_calls_for_install_and_update_process' do def test_should_raise_exception_for_unexistent_repository Kernel.expects(:system).with('git clone unexistent').raises(Errno::ENOENT) repository = GitRepository.new(create_plugin(nil, 'unexistent')) assert_raise(Errno::ENOENT) { repository.install } end def test_should_raise_exception_for_non_repository_url Kernel.expects(:system).with('git clone http://github.com/jodosha.git').raises(Errno::ENOENT) repository = GitRepository.new(create_plugin(nil, 'http://github.com/jodosha.git')) assert_raise(Errno::ENOENT) { repository.install } end def test_should_create_git_repository repository.with_path plugins_path do FileUtils.mkdir_p('sashimi') Kernel.expects(:system).with('git clone git://github.com/jodosha/sashimi.git').returns true GitRepository.new(plugin).install File.expects(:exists?).with('.git').returns(true) assert File.exists?('.git') end end def test_should_raise_exception_if_git_was_not_available assert_raise Sashimi::GitNotFound do Kernel.expects(:system).with('git clone git://github.com/jodosha/sashimi.git').returns false GitRepository.new(plugin).install end end end end <file_sep>Dir[File.dirname(__FILE__) + '/core_ext/*.rb'].each{|f| require f} <file_sep>Gem::Specification.new do |s| s.name = "sashimi" s.version = "0.2.2" s.date = "2008-10-03" s.summary = "Rails plugins manager" s.author = "<NAME>" s.email = "<EMAIL>" s.homepage = "http://lucaguidi.com/pages/sashimi" s.description = "Sashimi is a local repository for Rails plugins." s.has_rdoc = true s.rubyforge_project = %q{sashimi} s.executables = [ 'sashimi' ] s.files = ["CHANGELOG", "MIT-LICENSE", "README", "Rakefile", "bin/sashimi", "lib/sashimi.rb", "lib/sashimi/commands.rb", "lib/sashimi/core_ext.rb", "lib/sashimi/core_ext/array.rb", "lib/sashimi/core_ext/class.rb", "lib/sashimi/core_ext/string.rb", "lib/sashimi/plugin.rb", "lib/sashimi/repositories.rb", "lib/sashimi/repositories/abstract_repository.rb", "lib/sashimi/repositories/git_repository.rb", "lib/sashimi/repositories/svn_repository.rb", "lib/sashimi/version.rb", "sashimi.gemspec", "setup.rb", "test/test_helper.rb", "test/unit/core_ext/array_test.rb", "test/unit/core_ext/class_test.rb", "test/unit/core_ext/string_test.rb", "test/unit/plugin_test.rb", "test/unit/repositories/abstract_repository_test.rb", "test/unit/repositories/git_repository_test.rb", "test/unit/repositories/svn_repository_test.rb", "test/unit/version_test.rb"] s.test_files = ["test/unit/core_ext/array_test.rb", "test/unit/core_ext/class_test.rb", "test/unit/core_ext/string_test.rb", "test/unit/plugin_test.rb", "test/unit/repositories/abstract_repository_test.rb", "test/unit/repositories/git_repository_test.rb", "test/unit/repositories/svn_repository_test.rb", "test/unit/version_test.rb"] s.extra_rdoc_files = ['README', 'CHANGELOG'] s.add_dependency("activesupport", ["> 0.0.0"]) end<file_sep>Dir[File.dirname(__FILE__) + '/repositories/*.rb'].sort.each{|f| require f} <file_sep>class Class # Dinamically creates a proxy for given class methods. # # Example: # # class Repository # def self.path # @@path # end # # class_method_proxy :path # end # # It produces: # # Proxy method for <tt>Repository#path</tt> # def path # self.class.path # end # private :path def class_method_proxy(*method_names) method_names.each do |m| self.class_eval %{ # Proxy method for <tt>#{self.class.name}##{m}</tt> def #{m}(*args, &block) self.class.#{m}(*args, &block) end private :#{m} }, __FILE__, __LINE__ end end end <file_sep>#!/usr/bin/env ruby $LOAD_PATH.unshift "#{File.dirname(__FILE__)}/../lib" require 'sashimi' require 'sashimi/commands' $rails_app = Dir.pwd Sashimi::Commands::Command.parse! <file_sep>module Sashimi class Plugin attr_reader :url, :name def initialize(name, url = '') @url = URI::parse(url).to_s @name = name end # Install the plugin def install repository.install end # Uninstall the plugin def uninstall repository.uninstall end # Update the plugin def update repository.update end # Add to a Rails app def add repository.add end def repository #:nodoc: @repository ||= instantiate_repository end # Returns the informations about the plugin. def about @about ||= repository.about end # Return the plugin summary. def summary about['summary'] end # Try to guess the plugin name. def guess_name name = File.basename(@url) if name == 'trunk' || name.empty? name = File.basename(File.dirname(@url)) end name.gsub!(/\.git$/, '') if name =~ /\.git$/ name end # Serialize the plugin to +Hash+ format. def to_hash { self.guess_name => { 'type' => repository.scm_type, 'summary' => self.summary } } end class << self # List all installed plugins. def list AbstractRepository.list end end private # Instantiate the repository. # Look at <tt>AbstractRepository#instantiate_repository</tt> documentation. def instantiate_repository AbstractRepository.instantiate_repository(self) end end end <file_sep>require 'test/unit' require 'test/test_helper' class AbstractRepositoryTest < Test::Unit::TestCase include Sashimi def test_initialize assert repository.plugin end def test_plugins_path assert_equal 'sashimi_test/.rails/plugins', repository.class.plugins_path end def test_cache_file assert_equal cache_file, repository.class.cache_file end def test_plugins_names assert_equal cached_plugins.keys.sort, repository.class.plugins_names end def test_temp_suffix assert_equal '-tmp', AbstractRepository::TEMP_SUFFIX end ### INSTANTIATE def test_instantiate_repository assert_kind_of GitRepository, repository.class.instantiate_repository(plugin) assert_kind_of GitRepository, repository.class.instantiate_repository(create_plugin('sashimi', plugin.url)) end def test_should_instantiate_repository_by_url assert_equal SvnRepository, AbstractRepository.instantiate_repository_by_url(create_plugin(nil, 'http://svn.com')) assert_equal GitRepository, AbstractRepository.instantiate_repository_by_url(plugin) end def test_should_instantiate_repository_by_cache assert repository.class.instantiate_repository_by_cache(create_plugin('sashimi', plugin.url)) end ### COMMANDS # ADD def test_should_add_plugin_to_rails_app with_path rails_app_path do repository.add assert_path_exists "vendor/plugins/#{repository.plugin.name}" end end def test_should_raise_exception_on_adding_missing_plugin with_path rails_app_path do assert_raise PluginNotFound do create_repository('unexistent').add end end end # UNINSTALL def test_should_uninstall_plugin_from_repository repository.uninstall with_path plugins_path do assert_path_not_exists repository.plugin.name end assert_not repository.class.plugins_names.include?(repository.plugin.name) end def test_should_raise_exception_on_uninstalling_missing_plugin assert_raise PluginNotFound do create_repository('unexistent').uninstall end end # LIST def test_should_list_installed_plugins assert_equal cached_plugins, repository.class.list end ### SCM uses_mocha 'AbstractRepositoryTestSCM' do def test_guess_version_control_system File.expects(:exists?).with('.git').returns true assert_equal :git, repository.class.guess_version_control_system File.expects(:exists?).with('.git').returns false assert_equal :svn, repository.class.guess_version_control_system end def test_scm_command File.stubs(:exists?).with('.git').returns true Kernel.expects(:system).with('git add file.rb') repository.class.scm_command('add', 'file.rb') end def test_scm_add File.stubs(:exists?).with('.git').returns true Kernel.expects(:system).with('git add file.rb') repository.class.scm_add('file.rb') end def test_scm_remove File.stubs(:exists?).with('.git').returns true Kernel.expects(:system).with('git rm file.rb') repository.class.scm_remove('file.rb') end def test_under_version_control Dir.expects(:glob).with(".{git,svn}").returns %w(.git) assert repository.class.under_version_control? end end def test_git_url assert repository.class.git_url?(plugin.url) assert repository.class.git_url?(plugin.url.gsub('git:', 'http:')) assert_not repository.class.git_url?('http://repository.com/plugin/trunk') end ### PATH uses_mocha 'AbstractRepositoryTestPath' do def test_local_repository_path AbstractRepository.expects(:find_home).returns '/Users/luca' File.stubs(:SEPARATOR).returns '/' expected = [ repository.class.find_home, repository.class.plugins_path ].to_path assert_equal expected, repository.local_repository_path end def _ignore_test_find_home flunk end def test_with_path old_path = Dir.pwd repository.with_path 'test' do assert_equal [old_path, 'test'].to_path, Dir.pwd end assert_equal old_path, Dir.pwd end end def test_path_to_rails_app with_path rails_app_path do assert_equal Dir.pwd, repository.class.path_to_rails_app end end def test_absolute_rails_plugins_path with_path rails_app_path do expected = "#{Dir.pwd}/vendor/plugins".to_path assert_equal expected, repository.class.absolute_rails_plugins_path end end def test_rails_plugins_path assert_equal 'vendor/plugins'.to_path, repository.class.rails_plugins_path end def test_plugin_path expected = [ plugins_path, repository.plugin.name ].to_path assert_equal expected, repository.plugin_path end ### FILES uses_mocha 'AbstractRepositoryTestFile' do def _ignore_test_copy_plugin_and_remove_hidden_folders flunk end def test_update_rails_plugins AbstractRepository.expects(:under_version_control?).returns true AbstractRepository.expects(:update_versioned_rails_plugins) AbstractRepository.update_rails_plugins plugin.name AbstractRepository.expects(:under_version_control?).returns false AbstractRepository.expects(:update_unversioned_rails_plugins) AbstractRepository.update_rails_plugins plugin.name end def _ignore_test_update_unversioned_rails_plugins FileUtils.stubs(:rm_rf) # because of teardown FileUtils.expects(:rm_rf).with 'sashimi' FileUtils.stubs(:cd) AbstractRepository.expects(:instantiate_repository_by_cache).returns GitRepository GitRepository.stubs(:cache_content).returns({ 'sashimi' => nil }) Plugin.expects(:add) FileUtils.expects(:cp_r).with [ plugins_path, repository.plugin.name ].to_path, [ repository.class.rails_plugins_path, repository.temp_plugin_name ].to_path FileUtils.expects(:mv).with [ repository.rails_plugins_path, repository.temp_plugin_name ].to_path, [ repository.rails_plugins_path, repository.plugin.name ].to_path AbstractRepository.update_unversioned_rails_plugins 'sashimi' end def _ignore_test_update_versioned_rails_plugins flunk end def _ignore_test_files_scheduled_for_add flunk end def _ignore_test_files_scheduled_for_remove flunk end def test_remove_temp_folder with_path rails_app_path do FileUtils.expects(:rm_rf).with [ repository.absolute_rails_plugins_path, repository.temp_plugin_name].to_path repository.remove_temp_folder FileUtils.stubs(:rm_rf) # because of teardown end end def test_prepare_installation FileUtils.expects(:mkdir_p).with repository.local_repository_path FileUtils.expects(:touch).with [ repository.local_repository_path, cache_file ].to_path repository.prepare_installation end def test_copy_plugin_to_rails_app FileUtils.expects(:mkdir_p).with repository.absolute_rails_plugins_path FileUtils.expects(:cp_r).with [ repository.local_repository_path, repository.plugin.name ].to_path, [ repository.absolute_rails_plugins_path, repository.temp_plugin_name ].to_path repository.copy_plugin_to_rails_app end end def _ignore_test_remove_hidden_folders flunk end ### CACHE def test_cache_content assert_equal cached_plugins, repository.class.cache_content end uses_mocha 'TestAbstractRepositoryCache' do def test_should_add_a_new_plugin_to_cache with_clear_cache do with_path local_repository_path do create_plugin_directory('brand_new') plugin = create_plugin(nil, 'git://github.com/jodosha/brand_new.git') repository.add_to_cache(plugin) assert_equal cached_plugins.merge(plugin.to_hash), repository.class.cache_content end end end def test_should_merge_an_existent_plugin_into_cache File.expects(:atomic_write).with('.plugins', "./") with_clear_cache do with_path local_repository_path do repository.add_to_cache(plugin) assert_equal cached_plugins.merge(plugin.to_hash), repository.class.cache_content end end end def test_remove_from_cache File.expects(:atomic_write).with('.plugins', "./") with_clear_cache do with_path local_repository_path do repository.remove_from_cache assert_not repository.class.plugins_names.include?(plugin.name) end end end def test_write_to_cache File.expects(:atomic_write).with('.plugins', "./") repository.class.expects(:cache_content).returns plugin.to_hash # mock the atomic write result with_clear_cache do with_path plugins_path do repository.write_to_cache(plugin.to_hash) assert_equal plugin.to_hash, repository.class.cache_content end end end end ### OTHER def test_should_load_about_yml assert_not_empty repository.about.keys end def test_should_return_empty_hash_for_unexistent_about_yml assert_nothing_raised Exception do assert_empty create_repository('plug-in').about.keys end end def test_temp_plugin_name assert_equal repository.plugin.name + AbstractRepository::TEMP_SUFFIX, repository.temp_plugin_name end uses_mocha 'AbstractRepositoryTestOther' do def test_should_run_install_hook File.expects(:exists?).returns true Kernel.expects(:load) repository.run_install_hook end def test_should_not_raise_exception_running_install_hook_with_missing_file assert_nothing_raised Exception do Kernel.expects(:load).never create_repository('plug-in').run_install_hook end end end end <file_sep>$:.unshift 'lib' require 'rake' require 'rake/testtask' require 'rake/rdoctask' repositories = %w( origin rubyforge ) desc 'Default: run unit tests.' task :default => :test desc 'Test the sashimi gem.' Rake::TestTask.new(:test) do |t| t.libs << 'lib' t.pattern = 'test/**/*_test.rb' t.verbose = true end desc 'Generate documentation for the sashimi gem.' Rake::RDocTask.new(:rdoc) do |rdoc| rdoc.rdoc_dir = 'rdoc' rdoc.title = 'Sashimi' rdoc.options << '--line-numbers' << '--inline-source' rdoc.rdoc_files.include('README') rdoc.rdoc_files.include('lib/**/*.rb') end desc 'Build and install the gem (useful for development purposes).' task :install do require 'sashimi' system "gem build sashimi.gemspec" system "sudo gem uninstall sashimi" system "sudo gem install --local --no-rdoc --no-ri sashimi-#{Sashimi::VERSION::STRING}.gem" system "rm sashimi-*.gem" end desc 'Build and prepare files for release.' task :dist => :clean do require 'sashimi' system "gem build sashimi.gemspec" system "cd .. && tar -czf sashimi-#{Sashimi::VERSION::STRING}.tar.gz sashimi" system "cd .. && tar -cjf sashimi-#{Sashimi::VERSION::STRING}.tar.bz2 sashimi" system "cd .. && cp sashimi-* sashimi" end desc 'Clean the working copy from release files.' task :clean do require 'sashimi' version = Sashimi::VERSION::STRING system "rm sashimi-#{version}.gem" if File.exist? "sashimi-#{version}.gem" system "rm sashimi-#{version}.tar.gz" if File.exist? "sashimi-#{version}.tar.gz" system "rm sashimi-#{version}.tar.bz2" if File.exist? "sashimi-#{version}.tar.bz2" end desc 'Show the file list for the gemspec file' task :files do puts "Files:\n #{Dir['**/*'].reject {|f| File.directory?(f)}.sort.inspect}" puts "Test files:\n #{Dir['test/**/*_test.rb'].reject {|f| File.directory?(f)}.sort.inspect}" end namespace :git do desc 'Push local Git commits to all remote centralized repositories.' task :push do repositories.each do |repository| puts "Pushing #{repository}...\n" system "git push #{repository} master" end end desc 'Perform a git-tag' task :tag do puts "Please enter the tag name: " tag_name = STDIN.gets.chomp exit(1) if tag_name.nil? or tag_name.empty? system "git tag -s #{tag_name}" end desc 'Push all the tags to remote centralized repositories.' task :push_tags do repositories.each do |repository| puts "Pushing tags to #{repository}...\n" system "git push --tags #{repository}" end end end <file_sep>require 'test/unit' require 'test/test_helper' class PluginTest < Test::Unit::TestCase def test_initialize assert plugin assert plugin.repository assert_nil plugin.name end def test_should_raise_invalid_uri_exception_on_nil_url assert_raise(URI::InvalidURIError) { create_plugin(nil, nil) } end def test_should_guess_name_for_git_url assert_equal 'sashimi', plugin.guess_name end def test_should_guess_name_for_svn_url assert_equal 'sashimi', create_plugin(nil, 'http://dev.repository.com/svn/sashimi').guess_name assert_equal 'sashimi', create_plugin(nil, 'http://dev.repository.com/svn/sashimi/trunk').guess_name end def test_should_instantiate_git_repository_for_git_url assert_kind_of GitRepository, plugin.repository end def test_should_instantiate_svn_repository_for_not_git_url assert_kind_of SvnRepository, create_plugin(nil, 'http://dev.repository.com/svn/sashimi/trunk').repository end # FIXME def _ignore_test_should_serialize_to_hash expected = {'plug-in' => {'type' => 'svn', 'summary' => nil}} assert_equal(expected, create_plugin('plug-in', 'http://dev.repository.com/svn/plug-in/trunk').to_hash) end end <file_sep>$: << File.dirname(__FILE__) + "/../lib" require 'sashimi' class Test::Unit::TestCase include Sashimi # Asserts the given condition is false. def assert_not(condition, message = nil) assert !condition, message end # Asserts the given collection is empty. def assert_empty(collection, message = nil) assert collection.empty?, message end # Asserts the given collection is *not* empty. def assert_not_empty(collection, message = nil) assert !collection.empty?, message end # Asserts the given path exists # It accepts path/to/be/asserted and automatically make it cross platform. def assert_path_exists(path, message = nil) assert File.exists?(path.to_path), message end # Asserts the given path doesn't exists def assert_path_not_exists(path, message = nil) assert !File.exists?(path.to_path), message end private def create_test_repository prepare_installation with_path plugins_path do create_cache_file create_plugin_directories create_rails_app end end def destroy_test_repository FileUtils.rm_rf local_repository_path end alias_method :setup, :create_test_repository alias_method :teardown, :destroy_test_repository def local_repository_path @local_repository_path ||= [ repository.class.find_home, 'sashimi_test' ].to_path end def plugins_path @plugins_path ||= [ local_repository_path, '.rails', 'plugins' ].to_path end def rails_app_path @rails_app_path ||= begin path = [ local_repository_path, '.rails', 'rails_app' ].to_path $rails_app = path path end end def repository @repository ||= create_repository end def plugin @plugin ||= create_plugin nil, 'git://github.com/jodosha/sashimi.git' end def create_repository(plugin_name = 'sashimi', url = 'git://github.com/jodosha/sashimi.git') AbstractRepository.new Plugin.new(plugin_name, url) end def create_plugin(name, url = nil) Plugin.new(name, url) end def cached_plugins { 'plug-in' => {'type' => 'svn'}, 'plugin' => {'type' => 'svn'}, 'sashimi' => {'type' => 'git'} } end def cache_file '.plugins' end def create_plugin_directories { 'sashimi' => true, 'plugin' => true, 'plug-in' => false }.each do |plugin, about| create_plugin_directory(plugin, about) end end def create_plugin_directory(plugin, about = true) with_path plugins_path do FileUtils.mkdir(plugin) unless File.exists?(plugin) File.open([ plugin, 'about.yml' ].to_path, 'w+') do |f| f.write({'summary' => "Plugin summary"}.to_yaml) end if about end end def create_rails_app FileUtils.mkdir_p [ rails_app_path, 'vendor', 'plugins' ].to_path end def prepare_installation FileUtils.mkdir_p plugins_path end def create_cache_file with_path plugins_path do File.open(cache_file, 'w+'){ |f| f.write cached_plugins.to_yaml } end end def with_local_repository_path(&block) with_path(local_repository_path, &block) end def with_path(path, &block) begin old_path = Dir.pwd FileUtils.cd(path) yield ensure FileUtils.cd(old_path) end end def with_clear_cache(&block) AbstractRepository.expire_cache yield create_cache_file AbstractRepository.expire_cache end end module Sashimi class AbstractRepository @@plugins_path = 'sashimi_test/.rails/plugins' cattr_accessor :plugins_path def self.expire_cache #:nodoc: @@cache_content = nil end public :add_to_cache, :cache_content, :cache_file, :copy_plugin_to_rails_app, :local_repository_path, :path_to_rails_app, :prepare_installation, :remove_from_cache, :rails_plugins_path, :remove_hidden_folders, :rename_temp_folder, :run_install_hook, :write_to_cache, :with_path, :plugin_path, :absolute_rails_plugins_path end end # Thanks to Rails Core Team def uses_mocha(description) require 'rubygems' require 'mocha' yield rescue LoadError $stderr.puts "Skipping #{description} tests. `gem install mocha` and try again." end def puts(message) #shut-up! end <file_sep>module Sashimi class SvnNotFound < ClientNotFound; end #:nodoc: class SvnRepository < AbstractRepository # Install the +plugin+. def install prepare_installation puts plugin.guess_name.titleize + "\n\n" with_path local_repository_path do result = Kernel.system("svn co #{plugin.url} #{plugin.guess_name}") raise SvnNotFound unless !!result add_to_cache(plugin.to_hash) end end # Update the +plugin+. def update puts plugin.name.titleize + "\n\n" with_path plugin_path do result = Kernel.system("svn up") raise SvnNotFound unless !!result end end end end <file_sep>require 'test/unit' require 'test/test_helper' class ArrayTest < Test::Unit::TestCase uses_mocha 'ArrayTest' do def setup File.stubs(:SEPARATOR).returns '/' end def test_to_path assert_equal 'path/to/app', %w(path to app).to_path end def test_to_absolute_path actual = File.dirname(__FILE__) expected = File.expand_path actual assert_equal expected, actual.split(File::SEPARATOR).to_path(true) assert_equal expected, actual.split(File::SEPARATOR).to_absolute_path assert_equal expected, actual.split(File::SEPARATOR).to_abs_path end end end <file_sep>module Sashimi class PluginNotFound < StandardError #:nodoc: def initialize(plugin_name, message = nil) @plugin_name, @message = plugin_name, message end def to_s @message || @plugin_name.to_s + " isn't in the local repository." end end class ClientNotFound < StandardError #:nodoc: def initialize(message = nil) @message = message end def client self.class.name.demodulize.gsub(/NotFound/, '') end def to_s @message || "#{client} wasn't installed or it isn't in your load path." end end class AbstractRepository TEMP_SUFFIX = '-tmp' # It's the path where the plugins are stored. @@plugins_path = ".rails/plugins".to_path # Conventional path where Rails applications use to place their plugins. @@rails_plugins_path = "vendor/plugins".to_path cattr_reader :rails_plugins_path # Cache file used to store informations about installed plugins. @@cache_file = '.plugins' cattr_accessor :cache_file attr_reader :plugin def initialize(plugin) @plugin = plugin end # Uninstall the current plugin. def uninstall with_path local_repository_path do raise PluginNotFound.new(plugin.name) unless File.exists?(plugin.name) FileUtils.rm_rf(plugin.name) remove_from_cache end end # Add the current plugin to a Rails app. def add raise PluginNotFound.new(plugin.name) unless cache_content.keys.include?(plugin.name) puts plugin.name.titleize + "\n" copy_plugin_and_remove_hidden_folders rename_temp_folder run_install_hook end # Copy a plugin to a Rails app and remove SCM hidden folders. def copy_plugin_and_remove_hidden_folders copy_plugin_to_rails_app remove_hidden_folders end class << self # Instantiate a repository (Svn or Git) for the given plugin. # # If the plugin was already installed it load from the cache, # otherwise it try to guess information from its url. def instantiate_repository(plugin) unless plugin.name.nil? instantiate_repository_by_cache(plugin) else instantiate_repository_by_url(plugin) end.new(plugin) end # Return all installed plugins names. def plugins_names cache_content.keys.sort end # Update the plugins installed in a rails app. # # If the application is under version control, +Sashimi+ cares about to # schedule add/remove plugin's files from/to your SCM of choice. def update_rails_plugins(plugins_names) if under_version_control? update_versioned_rails_plugins(plugins_names) else update_unversioned_rails_plugins(plugins_names) end end # Update the plugins installed in a <b>not versioned</b> Rails app. def update_unversioned_rails_plugins(plugins_names) plugins_names.each do |plugin_name| FileUtils.rm_rf [ absolute_rails_plugins_path, plugin_name ].to_path Plugin.new(plugin_name).add end end # Update the plugins installed in a <b>versioned</b> Rails app. def update_versioned_rails_plugins(plugins_names) with_path absolute_rails_plugins_path do plugins_names.each do |plugin_name| raise PluginNotFound.new(plugin_name) unless File.exists?(plugin_name) repository = Plugin.new(plugin_name).repository repository.copy_plugin_and_remove_hidden_folders files_scheduled_for_remove = repository.files_scheduled_for_remove files_scheduled_for_add = repository.files_scheduled_for_add FileUtils.cp_r(repository.temp_plugin_name+'/.', plugin_name) repository.remove_temp_folder with_path plugin_name do files_scheduled_for_remove.each {|file| scm_remove file} files_scheduled_for_add.each {|file| scm_add file} end end end end # Schedules an <b>add</b> for the given file on the current SCM system used by the Rails app. def scm_add(file) scm_command(:add, file) end # Schedules a <b>remove</b> for the given file on the current SCM system used by the Rails app. def scm_remove(file) scm_command(:rm, file) end # Execute the given command for the current SCM system used by the Rails app. def scm_command(command, file) scm = guess_version_control_system Kernel.system("#{scm} #{command} #{file}") end # It's the absolute path where the plugins are stored. # # Typically, it's under your home directory. def local_repository_path #:nodoc: @local_repository_path ||= [ find_home, @@plugins_path ].to_path end # Return the path to the Rails app where the user launched <tt>sashimi</tt> command. def path_to_rails_app $rails_app end # Read the cache file and return the content as an <tt>Hash</tt>. def cache_content with_path local_repository_path do @@cache_content ||= (YAML::load_file(cache_file) || {}).to_hash end end alias_method :list, :cache_content # Istantiate a +Repository+ for the given +plugin+, guessing if its url # refers to a Svn or Git repository. def instantiate_repository_by_url(plugin) git_url?(plugin.url) ? GitRepository : SvnRepository end # Instantiate a repository for the given +plugin+, loading informations # from the cache. def instantiate_repository_by_cache(plugin) cached_plugin = cache_content[plugin.name] raise PluginNotFound.new(plugin.name) if cached_plugin.nil? cached_plugin['type'] == 'git' ? GitRepository : SvnRepository end # It's absolute path of plugins in your Rails app. # # path/to/rails_app # => /Users/luca/path/to/rails_app/vendor/plugins def absolute_rails_plugins_path @@absolute_rails_plugins_path = [ path_to_rails_app, rails_plugins_path ].to_path(true) end # Check if the current working directory is under version control def under_version_control? !Dir.glob(".{git,svn}").empty? end # Guess the version control system for the current working directory. def guess_version_control_system File.exists?('.git') ? :git : :svn end # Find the user home directory def find_home ['HOME', 'USERPROFILE'].each do |homekey| return ENV[homekey] if ENV[homekey] end if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] return "#{ENV['HOMEDRIVE']}:#{ENV['HOMEPATH']}" end begin File.expand_path("~") rescue StandardError => ex if File::ALT_SEPARATOR "C:/" else "/" end end end # Try to guess if it's a Git url. def git_url?(url) url =~ /^git:\/\// || url =~ /\.git$/ end # Yield the given block executing it in the specified path def with_path(path, &block) begin old_path = Dir.pwd FileUtils.cd(path) yield ensure FileUtils.cd(old_path) end end end # Return the SCM type # # Subversion # => svn # Git # => git def scm_type self.class.name.demodulize.gsub(/Repository$/, '').downcase end # Read the content of the <tt>about.yml</tt>. # # New feature of Rails 2.1.0 http://github.com/rails/rails/commit/f5b991d76dc5d21f1870da067fb3101440256fba def about with_path plugin_path do (YAML::load_file('about.yml') rescue {}).to_hash end end # Returns a list of files that should be scheduled for SCM add. def files_scheduled_for_add Dir[temp_plugin_name+"/**/*"].collect {|fn| fn.gsub(temp_plugin_name, '.')} - Dir[plugin.name+"/**/*"].collect{|fn| fn.gsub(plugin.name, '.')} end # Returns a list of files that should be scheduled for SCM remove. def files_scheduled_for_remove Dir[plugin.name+"/**/*"].collect {|fn| fn.gsub(plugin.name, '.')} - Dir[temp_plugin_name+"/**/*"].collect {|fn| fn.gsub(temp_plugin_name, '.')} end # Remove the temp folder, used by update process. def remove_temp_folder FileUtils.rm_rf [ absolute_rails_plugins_path, temp_plugin_name ].to_path end # Returns the name used for temporary plugin folder. def temp_plugin_name plugin.name + TEMP_SUFFIX end class_method_proxy :local_repository_path, :cache_file, :cache_content, :path_to_rails_app, :rails_plugins_path, :with_path, :absolute_rails_plugins_path private # Returns the path to the plugin def plugin_path [ local_repository_path, plugin.name || plugin.guess_name ].to_path end # Prepare the plugin installation def prepare_installation FileUtils.mkdir_p local_repository_path FileUtils.touch [ local_repository_path, cache_file ].to_path end # Add a plugin into the cache def add_to_cache(plugin) write_to_cache cache_content.to_hash.merge!(plugin) end # Remove a plugin from the cache def remove_from_cache cache_content.delete(plugin.name) write_to_cache cache_content end # Write all the plugins into the cache def write_to_cache(plugins) File.atomic_write(cache_file, "./") do |file| file.write(plugins.to_yaml) end end # Copy a plugin to a Rails app. def copy_plugin_to_rails_app FileUtils.mkdir_p absolute_rails_plugins_path FileUtils.cp_r [ local_repository_path, plugin.name ].to_path, [ absolute_rails_plugins_path, temp_plugin_name ].to_path end # Rename the *-tmp folder used by the installation process. # # Example: # click-to-globalize-tmp # => click-to-globalize def rename_temp_folder FileUtils.mv [ rails_plugins_path, temp_plugin_name ].to_path, [ rails_plugins_path, plugin.name ].to_path end # Remove SCM hidden folders. def remove_hidden_folders require 'find' with_path [ absolute_rails_plugins_path, temp_plugin_name ].to_path do Find.find('./') do |path| if File.basename(path) == '.'+scm_type FileUtils.remove_dir(path, true) Find.prune end end end end # Run the plugin install hook. def run_install_hook install_hook_file = [ rails_plugins_path, plugin.name, 'install.rb' ].to_path Kernel.load install_hook_file if File.exists? install_hook_file end end end <file_sep>require 'optparse' module Sashimi module Commands class Command attr_reader :script_name def initialize @script_name = File.basename($0) end def options OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{@script_name} [OPTIONS] command" o.define_head "Rails plugin manager." o.separator "" o.separator "GENERAL OPTIONS" o.on("-v", "--verbose", "Turn on verbose output.") { |$verbose| } o.on("-h", "--help", "Show this help message.") { puts o; exit } o.separator "" o.separator "COMMANDS" o.separator " install Install plugin(s) from known URL(s)." o.separator " uninstall Uninstall plugin(s) from local repository." o.separator " update Update installed plugin(s)." o.separator " list List all installed plugins." o.separator " add Add installed plugin(s) to a Rails app." o.separator "" o.separator "EXAMPLES" o.separator " Install a plugin from a subversion URL:" o.separator " #{@script_name} install http://dev.rubyonrails.com/svn/rails/plugins/continuous_builder\n" o.separator " Install a plugin from a git URL:" o.separator " #{@script_name} install git://github.com/jodosha/click-to-globalize.git\n" o.separator " Uninstall a plugin:" o.separator " #{@script_name} uninstall continuous_builder\n" o.separator " Update a plugin:" o.separator " #{@script_name} update click-to-globalize\n" o.separator " Update all installed plugins:" o.separator " #{@script_name} update --all\n" o.separator " Update plugin(s) already added to a Rails app:" o.separator " #{@script_name} update --rails click-to-globalize\n" o.separator " List all installed plugins:" o.separator " #{@script_name} list\n" o.separator " Add installed plugin(s) to a Rails app:" o.separator " #{@script_name} add click-to-globalize\n" o.separator " Add installed plugin(s) to a Rails app:" o.separator " #{@script_name} install --rails click-to-globalize\n" end end def parse!(args=ARGV) general, sub = split_args(args) options.parse!(general) command = general.shift if command =~ /^(install|uninstall|update|list|add)$/ command = Commands.const_get(command.capitalize).new(self) command.parse!(sub) else puts "Unknown command: #{command}" puts options exit 1 end end def split_args(args) left = [] left << args.shift while args[0] and args[0] =~ /^-/ left << args.shift if args[0] return [left, args] end def self.parse!(args=ARGV) Command.new.parse!(args) rescue Exception => e puts e.message exit 1 end end class Install def initialize(base_command) @base_command = base_command end def options OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{@base_command.script_name} install [OPTIONS] URL [URL2, URL3]" o.define_head "Install plugin(s) from known URL(s)." o.on("-r", "--rails", "Install the plugin(s) in a Rails app.") { |@rails| } end end def parse!(args) options.parse!(args) args.each do |url_or_name| if @rails Plugin.new(url_or_name).add else Plugin.new(nil, url_or_name).install end end end end class Uninstall def initialize(base_command) @base_command = base_command end def options OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{@base_command.script_name} uninstall PLUGIN [PLUGIN2, PLUGIN3]" o.define_head "Uninstall plugin(s) from local repository." end end def parse!(args) options.parse!(args) args.each do |name| puts name.titleize + "\n" Plugin.new(name).uninstall end end end class Update def initialize(base_command) @base_command = base_command end def options OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{@base_command.script_name} update [OPTIONS] PLUGIN [PLUGIN2, PLUGIN3]" o.define_head "Update installed plugin(s)." o.on("-a", "--all", "Update all installed plugins.") { |@all| } o.on("-r", "--rails", "Install the plugin(s) in a Rails app.") { |@rails| } end end def parse!(args) options.parse!(args) raise "Can't use both --all and --rails arguments." if @all and @rails if @all update_plugins(AbstractRepository.plugins_names) elsif @rails AbstractRepository.update_rails_plugins(args) else update_plugins(args) end end def update_plugins(plugins) plugins.each do |plugin| Plugin.new(plugin).update end end end class List def initialize(base_command) @base_command = base_command end def options OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{@base_command.script_name} list" o.define_head "List all installed plugins." end end def parse!(args) options.parse!(args) output = Plugin.list.sort.collect do |plugin, contents| "#{plugin}\t\t#{contents['summary']}" end.join("\n") puts output end end class Add def initialize(base_command) @base_command = base_command end def options OptionParser.new do |o| o.set_summary_indent(' ') o.banner = "Usage: #{@base_command.script_name} add PLUGIN" o.define_head "Add installed plugin(s) to a Rails app." end end def parse!(args) options.parse!(args) args.each do |name| Plugin.new(name).add end end end end end <file_sep>module Sashimi class GitNotFound < ClientNotFound; end #:nodoc: class GitRepository < AbstractRepository # Install the +plugin+. def install prepare_installation puts plugin.guess_name.titleize + "\n\n" with_path local_repository_path do result = Kernel.system("git clone #{plugin.url}") raise GitNotFound unless !!result add_to_cache(plugin.to_hash) end end # Update the +plugin+. def update puts plugin.name.titleize + "\n\n" with_path plugin_path do result = Kernel.system('git pull') raise GitNotFound unless !!result end end end end <file_sep>require 'test/unit' require 'test/test_helper' class SvnRepositoryTest < Test::Unit::TestCase def test_type assert_equal('svn', SvnRepository.new(nil).scm_type) end uses_mocha 'test_svn_system_calls_for_install_and_update_process' do def test_should_raise_exception_for_unexistent_repository Kernel.expects(:system).with('svn co unexistent unexistent').raises(Errno::ENOENT) repository = SvnRepository.new(create_plugin(nil, 'unexistent')) assert_raise(Errno::ENOENT) { repository.install } end def test_should_raise_exception_for_non_repository_url Kernel.expects(:system).with('svn co http://sushistarweb.com sushistarweb.com').raises(Errno::ENOENT) repository = SvnRepository.new(create_plugin(nil, 'http://sushistarweb.com')) assert_raise(Errno::ENOENT) { repository.install } end def test_should_create_svn_repository repository.with_path plugins_path do FileUtils.mkdir_p('sashimi') Kernel.expects(:system).with('svn co http://dev.repository.com/svn/sashimi/trunk sashimi').returns true SvnRepository.new(create_plugin(nil, 'http://dev.repository.com/svn/sashimi/trunk')).install File.expects(:exists?).with('.svn').returns(true) assert File.exists?('.svn') end end def test_should_raise_exception_if_svn_was_not_available assert_raise Sashimi::SvnNotFound do Kernel.expects(:system).with('svn co http://dev.repository.com/svn/sashimi/trunk sashimi').returns false SvnRepository.new(create_plugin(nil, 'http://dev.repository.com/svn/sashimi/trunk')).install end end end end <file_sep>require 'test/unit' require 'test/test_helper' class StringTest < Test::Unit::TestCase uses_mocha 'StringTest' do def setup File.stubs(:SEPARATOR).returns '/' end def test_to_path assert_equal 'path/to/app', 'path/to/app'.to_path end def test_to_absolute_path actual = File.dirname(__FILE__) expected = File.expand_path actual assert_equal expected, actual.to_path(true) end end end <file_sep>require 'test/unit' require 'test/test_helper' class Repository def self.path @@path ||= 'path' end def self.another_path(another_path) another_path end def self.path_with_block(path, &block) block.call(path) if block_given? path end class_method_proxy :path, :another_path, :path_with_block public :path_with_block end class ClassTest < Test::Unit::TestCase def test_should_respond_to_proxied_methods repository = Repository.new assert_equal 'path', repository.send(:path) assert_equal 'path', repository.send(:another_path, 'path') assert_equal 'path', repository.path_with_block('path') { |path| path } end end <file_sep>require 'test/unit' require 'test/test_helper' class VersionTest < Test::Unit::TestCase def test_version assert_equal '0.2.2', Sashimi::VERSION::STRING end end <file_sep>class Array # Transform the current +Array+ to a path. # # It's an alias for <tt>File#join</tt>. # # %w(path to app).to_path # => path/to/app+ # %w(path to app).to_path(true) # => /Users/luca/path/to/app def to_path(absolute = false) path = File.join(self) path = File.expand_path(path) if absolute path end # Transform the current +Array+ to an absolute path. # # %w(path to app).to_absolute_path # => /Users/luca/path/to/app # %w(path to app).to_abs_path # => /Users/luca/path/to/app def to_absolute_path to_path(true) end alias_method :to_abs_path, :to_absolute_path end <file_sep>class String # Transform the current +String+ to a system path, # according to the current platform file system. # # "path/to/app".to_path # => path/to/app (on *nix) # "path/to/app".to_path # => path\to\app (on Windows) # # "path/to/app".to_path(true) # => /Users/luca/path/to/app (on *nix) # "path/to/app".to_path(true) # => C:\path\to\app (on Windows) def to_path(absolute = false) self.split(/\/\\/).to_path(absolute) end end
215bdc5ddb0649a12f52a692836de1f3eab1fc7b
[ "Ruby" ]
22
Ruby
jodosha/sashimi
edf5f7ad73dc49d008d02f8ec06e6d5f87222cfa
6a8b3dc03c2b282ab34fa19ac75064d66767b04f
refs/heads/master
<file_sep>package com.mult3.testemult3; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class Testemult3ApplicationTests { @Test void contextLoads() { } } <file_sep>package com.mult3.testemult3.repository; import java.util.List; import com.mult3.testemult3.model.Pessoa; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface RepositoryPessoa extends CrudRepository<Pessoa, Long> { public List<Pessoa> findAllByNomeContainingIgnoreCase(String nome); } <file_sep>package com.mult3.testemult3; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Testemult3Application { public static void main(String[] args) { SpringApplication.run(Testemult3Application.class, args); } }
10871069cfd5a23d782de733d79e2da9444b03d5
[ "Java" ]
3
Java
roullerk/TesteCRUDMult3
0d4982596f61c46e34dbae10bb394ce1d2cf872c
72e94cdfb022700a7c30e2d0f23b23d777ff11b3
refs/heads/master
<file_sep>package com.mydemos.collections; import java.util.ArrayList; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Vector; //set list //map //vector thread safe //arrayList thread unsafe (fast) no locking public class CollectionsMain { public static void main(String[] args) { HashSet<String> names=new HashSet<>(); names.add("raja"); names.add("raju"); names.add("raj"); names.add("raj"); names.add("rajesh"); for(String name:names) { System.out.println(name); } // TODO Auto-generated method stub } } <file_sep> interface MobileNumber{ boolean numberFormat(String str); } abstract class Country implements MobileNumber{ boolean isNumber(String d) { for (int i =0 ;i<d.length();i++) { char ch = d.charAt(i); if(!(ch>='0'&&ch<='9')) { return false; } } return true; } } class India extends Country{ public boolean numberFormat(String str) { if(str.length()!=14) { return false; } if((str.charAt(0)!='+')||(str.charAt(3)!='-')||(str.charAt(1)!='9')||(str.charAt(2)!='1')||(!isNumber(str.substring(4)))) { return false; } return true; } } public class Assignment { public static void main(String[] args) { India In = new India(); String num = "+91-9696147417"; System.out.println(In.numberFormat(num)); // TODO Auto-generated method stub } } <file_sep>package com.myhib.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; @Entity public class School { String day; @Column(name="sess") int session; @Id @Column(name="fac") String faculty; int room; int sem ; @Column(name="sub") String subject; public String getDay() { return day; } public void setDay(String day) { this.day = day; } public int getSession() { return session; } public void setSession(int session) { this.session = session; } public String getFaculty() { return faculty; } public void setFaculty(String faculty) { this.faculty = faculty; } public int getRoom() { return room; } public void setRoom(int room) { this.room = room; } public int getSem() { return sem; } public void setSem(int sem) { this.sem = sem; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } @Override public String toString() { return getDay()+" "+getSession()+" "+getFaculty()+" "+getRoom()+" "+getSem()+" "+getSubject(); } } <file_sep>import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Resturant } from './Resturant.model'; @Injectable({ providedIn: 'root' }) export class ResturantService { constructor(private http:HttpClient) { } saveResturant(resturant:Resturant) { return this.http.post<any>('http://localhost:1024/resturant',resturant); } updateResturant(resturant:Resturant) { return this.http.put<Resturant>('http://localhost:1024/resturant',resturant); } getAllResturants() { return this.http.get<Resturant[]>('http://localhost:1024/resturant'); } deleteResturant(resturantId:number) { return this.http.delete(`http://localhost:1024/resturant/${resturantId}`); } getResturant(resturantId:number) { return this.http.get<Resturant>(`http://localhost:1024/resturant/${resturantId}`); } }<file_sep>package com.mydemos.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import com.mydemos.dbutil.DbConn; import com.mydemos.pojo.Customer; import java.util.ArrayList; import java.util.Date; public class CustomerDao { public String saveCustomer(Customer customer) { try { Connection con=DbConn.getConnection(); int seq_id = 0; String sql = "select jdbc_seq.nextval from DUAL"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); if(rs.next()) { seq_id = rs.getInt(1); } sql="insert into customer values(?,?,?,?,?)"; PreparedStatement vkr = con.prepareStatement(sql); String id =null; vkr.setString(1, customer.getCustName()); vkr.setString(2, customer.getCustLastName()); if (seq_id < 10) { id = "00" + seq_id; } else if (seq_id >= 10 && seq_id < 100) { id = "0" + seq_id; } else { id = "" + seq_id; } id = customer.getCustName().substring(0, 2) + customer.getCustLastName().substring(0, 2) + id; customer.setCustId(id); vkr.setString(3, customer.getCustId()); vkr.setString(4, customer.getAddress()); Date utildob = customer.getcustDob(); java.sql.Date dob = new java.sql.Date(utildob.getYear() ,utildob.getMonth(),utildob.getDate()); vkr.setDate(5, dob); int res= vkr.executeUpdate(); if(res>0) return "customer saved"; } catch (Exception e) { e.printStackTrace(); } return "Cannot save Customer"; } public ArrayList<Customer> getAllCustomers() { ArrayList<Customer> custList=new ArrayList<Customer>(); try { Connection con= DbConn.getConnection(); String sql="select * from customer"; PreparedStatement stat=con.prepareStatement(sql); ResultSet rs=stat.executeQuery(); if(rs.next()) { do{ Customer customer=new Customer(); customer.setCustName(rs.getString(1)); customer.setCustLastName(rs.getString(2)); customer.setCustId(rs.getString(3)); customer.setAddress(rs.getString(4)); customer.setcustDob(rs.getDate(5)); custList.add(customer); } while(rs.next()); } else { return custList; } } catch (Exception e) { e.printStackTrace(); return null; } return custList; } } <file_sep>package com.myhib.dao; import java.util.ArrayList; import javax.management.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.myhib.model.User; public class UserDao { SessionFactory factory=new Configuration().configure().buildSessionFactory(); public void saveUser(User user) { Session session=factory.openSession(); Transaction tx= session.beginTransaction(); session.save(user); tx.commit(); session.close(); } public ArrayList<User> getUsers() { Session session=factory.openSession(); Transaction tx= session.beginTransaction(); //ArrayList<User> customers=(ArrayList<User>)session.createQuery("from User").list(); org.hibernate.query.Query query =session.createQuery("from User"); ArrayList<User> users =(ArrayList<User>) query.getResultList(); tx.commit(); session.close(); return users; } }<file_sep>package mypackage; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Set; public class Find_Car { public static void main(String[] args) { Car car1=new Car("100", "i10", "hyundai"); Car car2=new Car("800", "Alto", "Maruti"); Car car3=new Car("300", "verna", "Hyundai"); Car car4=new Car("600", "Amaze", "Honda"); Showroom showroom=new Showroom(); showroom.setCarName("SHOWROOM"); HashMap<String, Car> cars=new HashMap<>(); cars.put(car1.modelNo,car1); cars.put(car2.modelNo,car2); cars.put(car3.modelNo,car3); cars.put(car4.modelNo,car4); // TODO Auto-generated method stub showroom.setCars(cars); HashMap<String, Car> showroom_Cars=(HashMap<String, Car>)showroom.getCars(); System.out.println(showroom_Cars.get("100")); } } <file_sep>package com.myhib.model; import java.util.Date; import javax.persistence.AttributeOverride; import javax.persistence.AttributeOverrides; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; @Table(name="user_info") @Entity public class User { @Id @Column(name="user_id") int uid; String userName; @Column(name="date_info") Date date; @Embedded Address address; @Embedded @AttributeOverrides( { @AttributeOverride(name="city", column = @Column(name="Home_City") ), @AttributeOverride(name="pinCode", column = @Column(name="home_PinCode") ), @AttributeOverride(name="Street", column = @Column(name="home_Street") ) } ) Address homeaddress; public Address getHomeaddress() { return homeaddress; } public void setHomeaddress(Address homeaddress) { this.homeaddress = homeaddress; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } } <file_sep> package com.myspr.demo; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.myspr.dao.AuthorDao; import com.myspr.model.Author; @Controller public class HomeController { ArrayList<Author> lis = new ArrayList<Author>(); @RequestMapping(value = "/") public String home2(Locale locale,Model model) { return "home2"; } @Autowired AuthorDao authorDao; @RequestMapping(value = "/saveAuthor") public String saveresturant(@ModelAttribute Author res) { authorDao.saveAuthor(res); lis.add(res); return "display"; } @RequestMapping(value = "/backHome") public String backHome(@ModelAttribute Author res) { return "home2"; } @RequestMapping(value = "/dispData") public String dispData(Model model,@RequestParam("authorName") String name) { Author author=authorDao.getData(name); model.addAttribute("author",author); return "display"; } @RequestMapping(value = "/viewData") public String viewData(Model model,@ModelAttribute Author res) { ArrayList<Author> authors = authorDao.viewData(res); model.addAttribute("authors",authors); return "displayAll"; } @RequestMapping(value = "/updateData") public String updateData(@ModelAttribute Author res) { authorDao.updateData(res); return "home2"; } @RequestMapping(value = "/deleteDataDesign") public String deleteDataDesign() { return "deleteSearchDesign"; } @RequestMapping(value = "/deleteData") public String deleteData(Model model,@RequestParam("authorName") String name) { authorDao.deleteData(name); return "home2"; } } <file_sep>package com.mydemos.pojo; import java.util.Date;; public class Customer { String custName; String custLastName; String CustId; String address; java.util.Date custDob; public Date getcustDob() { return custDob; } public void setcustDob(Date custDob) { this.custDob = custDob; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustLastName() { return custLastName; } public void setCustLastName(String custLastName) { this.custLastName = custLastName; } public String getCustId() { return CustId; } public void setCustId(String id) { CustId = id; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Customer(String custName, String custLastName, String address) { super(); this.custName = custName; this.custLastName = custLastName; this.address = address; } public Customer() { } @Override public String toString() { // TODO Auto-generated method stub return getCustName()+" "+getCustLastName()+" "+getCustId()+" "+getAddress()+" "+getcustDob(); } } <file_sep>package com.myhib.dao; import java.util.ArrayList; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.myhib.model.School; public class SchoolDao { SessionFactory factory=new Configuration().configure().buildSessionFactory(); public ArrayList<School> getSchoolsBySession(int sessn , int sems) { Session session1= factory.openSession(); Transaction tx=session1.beginTransaction(); Query query=session1.createQuery("from School s where s.session=:sId and s.sem=:semester"); query.setParameter("sId", sessn); query.setParameter("semester", sems); ArrayList<School> studs=(ArrayList<School>)query.list(); return studs; } }
56f5014cee7f690675309e59b3ffa85ca9752706
[ "Java", "TypeScript" ]
11
Java
vkr4773/Training
f88a5fbe828fbd9bf4ac2c0598138dbb589c019c
f35b76b006b30b3644a68bb6a9695102deb69920
refs/heads/master
<repo_name>caIcutec/caIcutec.github.io<file_sep>/albums.js /** * * CoverFlow using CSS3 * <NAME> * **/ (function() { var idx = 0, covers = [], titles=[], descripts=[], // Constants OFFSET = 40; // pixels BASE_ZINDEX = -10; // MAX_ZINDEX = 0; // function get( selector ) { return document.querySelector( selector ); }; function render() { // loop through albums & transform positions for( var i = 0; i < covers.length; i++ ) { // before if( i < idx ) { covers[i].style.webkitTransform = "translateX(" + (-1*OFFSET*(idx-i)) + "% ) scale(" + Math.pow(0.9,(idx-i)) + ")"; covers[i].style.zIndex = BASE_ZINDEX + i; } // current if( i === idx ) { covers[i].style.webkitTransform = "translateZ( 1px )"; covers[i].style.zIndex = MAX_ZINDEX; document.getElementById("album-title").innerHTML = titles[i]; document.getElementById("album-descript").innerHTML=descripts[i]; } // after if( i > idx ) { covers[i].style.webkitTransform = "translateX(" + (OFFSET*(i-idx)) + "% ) scale(" + Math.pow(0.9,-1*(idx - i)) + ")"; covers[i].style.zIndex = BASE_ZINDEX + ( covers.length - i ); } } }; function shiftR() { if( idx ) { idx--; render(); } }; function shiftL() { if( covers.length > ( idx + 1) ) { idx++; render(); } }; function keyDown(event){ switch(event.keyCode){ case 37: shiftR(); break; case 39: shiftL(); } }; function registerEvents() { document.addEventListener('keydown', keyDown, false); }; function init() { covers = Array.prototype.slice.call( document.querySelectorAll( 'section' )); idx = Math.floor( covers.length / 2 ); _coverflow = get('#coverflow'); for( var i = 0; i < covers.length; i++ ) { var url = covers[i].getAttribute("data-cover"); covers[i].style.backgroundImage = "url("+ url +")"; titles[i] = covers[i].getAttribute("album-title"); descripts[i] = covers[i].getAttribute("descript"); } registerEvents(); render(); }; init(); $('section').hover(function(){ idx = covers.indexOf(this); render(); }); }());<file_sep>/README.md # caIcutec.github.io
ca34778946854006f5f806ccecfda82985b974d2
[ "JavaScript", "Markdown" ]
2
JavaScript
caIcutec/caIcutec.github.io
90f6d4d8caf743f5940d0491f38106ac29601209
80b04f5179ba16c6fafb385dac24339c8d8019d2
refs/heads/master
<file_sep>function shouldComponetupdate(){ console.log('render :'); } <file_sep>const echarts = require("./lib/echarts.js"); const jquery = require("./lib/jquery.js"); const antd = require("./lib/antd.js"); const babel = require("./lib/babel.js"); const charts = require("./lib/charts.js"); const ramda = require("./lib/ramda.js"); const less = require("./lib/less.js"); const three = require("./lib/three.js"); <file_sep>const path = require('path'); const webpack = require('webpack'); const webpackMajorVersion = Number(require('webpack/package.json').version.split('.')[0]); const WebpackBuildLogPlugin = require('../src/index.js'); const rimraf = require("rimraf"); const utils = require("../src/utils"); const OUTPUT_DIR = path.resolve(__dirname, '../dist/basic-spec'); const filename = 'compile-log.md'; if (isNaN(webpackMajorVersion)) { throw new Error('Cannot parse webpack major version'); } // 处理process.exit 导致jest进程退出 const setProperty = (object, property, value) => { const originalProperty = Object.getOwnPropertyDescriptor(object, property) Object.defineProperty(object, property, { value }) return originalProperty } const mockExit = jest.fn() setProperty(process, 'exit', mockExit); jest.setTimeout(30000); process.on('unhandledRejection', r => console.log(r)); process.traceDeprecation = true; //公共测试函数 function testwebpackBuildLogPlugin (webpackConfig, done) { webpack(webpackConfig, (err, stats) => { // jest 补捕获错误 // 在 JavaScript中,有六个falsy值:false,0,'',null,undefined,和NaN。其他一切都是真实的 expect(err).toBeFalsy(); expect(mockExit).toHaveBeenCalledWith(0); done(); }) } describe('WebpackBuildLogPlugin', () => { beforeEach(done => { rimraf(OUTPUT_DIR, done); }); test('utils', () => { expect(utils.getIp()).toMatch(/^(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i); }) it('Test file size out of range', done => { testwebpackBuildLogPlugin({ mode: 'production', entry: path.join(__dirname, 'fixtures/testMax.js'), output: { path: OUTPUT_DIR, filename: 'index_bundle.js' }, plugins: [ new WebpackBuildLogPlugin({ path: path.join(process.cwd(), 'log'), filename, deleteFile: true })] }, done); }); it('Test log file exists', done => { testwebpackBuildLogPlugin({ mode: 'production', entry: path.join(__dirname, 'fixtures/index.js'), output: { path: OUTPUT_DIR, filename: 'index_bundle.js' }, plugins: [ new WebpackBuildLogPlugin({ path: path.join(process.cwd(), 'log'), filename, deleteFile: true })] }, done); }); it('Test log in development', done => { testwebpackBuildLogPlugin({ mode: 'development', entry: path.join(__dirname, 'fixtures/index.js'), output: { path: OUTPUT_DIR, filename: 'index_bundle.js' }, plugins: [ new WebpackBuildLogPlugin({ path: path.join(process.cwd(), 'log'), filename, deleteFile: false })] }, done); }); }); <file_sep>{ "errors": [], "warnings": [], "version": "4.38.0", "hash": "035e787f16d65fc3cc4c", "time": 36, "builtAt": 1564407278703, "publicPath": "", "outputPath": "/Users/jiayali/Desktop/webpack-plugin/webpack-build-log-plugin/dist/basic-spec", "assetsByChunkName": { "main": "index_bundle.js" }, "assets": [ { "name": "index_bundle.js", "size": 930, "chunks": [ 0 ], "chunkNames": [ "main" ], "emitted": true } ], "filteredAssets": 0, "entrypoints": { "main": { "chunks": [ 0 ], "assets": [ "index_bundle.js" ], "children": {}, "childAssets": {} } }, "namedChunkGroups": { "main": { "chunks": [ 0 ], "assets": [ "index_bundle.js" ], "children": {}, "childAssets": {} } }, "chunks": [ { "id": 0, "rendered": true, "initial": true, "entry": true, "size": 62, "names": [ "main" ], "files": [ "index_bundle.js" ], "hash": "bc6947c0a6ba76bf67b0", "siblings": [], "parents": [], "children": [], "childrenByOrder": {}, "modules": [ { "id": 0, "identifier": "/Users/jiayali/Desktop/webpack-plugin/webpack-build-log-plugin/__tests__/fixtures/index.js", "name": "./__tests__/fixtures/index.js", "index": 0, "index2": 0, "size": 62, "cacheable": true, "built": true, "optional": false, "prefetched": false, "chunks": [ 0 ], "issuer": null, "issuerId": null, "issuerName": null, "issuerPath": null, "failed": false, "errors": 0, "warnings": 0, "assets": [], "reasons": [ { "moduleId": null, "moduleIdentifier": null, "module": null, "moduleName": null, "type": "single entry", "userRequest": "/Users/jiayali/Desktop/webpack-plugin/webpack-build-log-plugin/__tests__/fixtures/index.js", "loc": "main" } ], "usedExports": true, "providedExports": null, "optimizationBailout": [ "ModuleConcatenation bailout: Module is not an ECMAScript module" ], "depth": 0, "source": "function shouldComponetupdate(){\n console.log('render :');\n}\n" } ], "filteredModules": 0, "origins": [ { "module": "", "moduleIdentifier": "", "moduleName": "", "loc": "main", "request": "/Users/jiayali/Desktop/webpack-plugin/webpack-build-log-plugin/__tests__/fixtures/index.js", "reasons": [] } ] } ], "modules": [ { "id": 0, "identifier": "/Users/jiayali/Desktop/webpack-plugin/webpack-build-log-plugin/__tests__/fixtures/index.js", "name": "./__tests__/fixtures/index.js", "index": 0, "index2": 0, "size": 62, "cacheable": true, "built": true, "optional": false, "prefetched": false, "chunks": [ 0 ], "issuer": null, "issuerId": null, "issuerName": null, "issuerPath": null, "failed": false, "errors": 0, "warnings": 0, "assets": [], "reasons": [ { "moduleId": null, "moduleIdentifier": null, "module": null, "moduleName": null, "type": "single entry", "userRequest": "/Users/jiayali/Desktop/webpack-plugin/webpack-build-log-plugin/__tests__/fixtures/index.js", "loc": "main" } ], "usedExports": true, "providedExports": null, "optimizationBailout": [ "ModuleConcatenation bailout: Module is not an ECMAScript module" ], "depth": 0, "source": "function shouldComponetupdate(){\n console.log('render :');\n}\n" } ], "filteredModules": 0, "logging": { "webpack.buildChunkGraph.visitModules": { "entries": [], "filteredEntries": 2, "debug": false } }, "children": [] }
b349ee1702f84ecbb4287971e056b10b44c0a5cb
[ "JavaScript", "Markdown" ]
4
JavaScript
FreemenL/webpack-build-log-plugin
a15ea0b0ad2b0a12502e2d6beb3e00b847b20f97
693ff37e6ab8f9fd54cb5fe73249dbd6baaaf417
refs/heads/master
<repo_name>Skalextric/spark_no_evaluable<file_sep>/SimpleApp.py # -*- coding: utf-8 -*- from pyspark import SparkContext sc = SparkContext("local", "Simple App") import sys, os, bz2, json, re path = "30/01/" jsonpaths = [] for (dirpath, dirnames, files) in os.walk(path): for filename in files: filepath = os.path.join(dirpath, filename) zipfile = bz2.BZ2File(filepath) # open the file data = zipfile.read() # get the decompressed data # data es una cadena de texto con el contenido del archivo # en este ejemplo se guarda el contenido a otro fichero newfilepath = filepath[:-4] # assuming the filepath ends with .bz2 jsonpaths.append(newfilepath) open(newfilepath, 'wb').write(data) # write a uncompressed file rddPaths = sc.parallelize(jsonpaths) def parse_json(json_path): results = [] with open(json_path, 'r') as f: lines = f.readlines() for line in lines: j = json.loads(line) if 'user' in j and j['user']['lang'] == 'es': user = j['user']['screen_name'].encode("utf-8") date = j['created_at'].encode("utf-8") text = j['text'] results.append((user, date, text)) return results rddTweets = rddPaths.flatMap(parse_json) usuarioMax = rddTweets.map(lambda x: (x[0], 1)).reduceByKey(lambda c1, c2: c1 + c2).max(lambda (a, b): b) # print "Usuario mas tweets: ", usuarioMax # # # def quitaNoAlfa(s): # return re.sub(r'([^\s\wñáéíóú]|_)+', '', s.lower().encode('utf-8')) # # # stopwords = [u'como', u'pero', u'o', u'al', u'mas', u'esta', u'le', u'cuando', u'eso', u'su', u'porque', u'd', u'del', # u'los', u'mi', u'si', u'las', u'una', u'q', u'ya', u'yo', u'tu', u'el', u'ella', u'a', u'ante', u'bajo', # u'cabe', u'con', u'contra', u'de', u'desde', u'en', u'entre', u'hacia', u'hasta', u'para', u'por', # u'segun', u'sin', u'so', u'sobre', u'tras', u'que', u'la', u'no', u'y', u'el', u'me', u'es', u'te', u'se', # u'un', u'lo'] # # rddPalabras = rddTweets.flatMap(lambda x: quitaNoAlfa(x[2]).split(' ')).filter(lambda x: len(x) > 0) # diezPalabrasMasUsadas = rddPalabras.filter(lambda x: x not in stopwords).map(lambda x: (x, 1)).reduceByKey( # lambda c1, c2: c1 + c2).takeOrdered(10, lambda (p, c): -c) # # print "Palabras más usadas", diezPalabrasMasUsadas def quitaNoAlfaOHash(s): return re.sub(r'([^\s\w#áéíóúñ]|_)+', '', s.lower()) def sacaHashtags(tweet): hashtags = tweet.split('#')[1:] return map(lambda x: x if ' ' not in x.lower() else x.partition(' ')[0].lower(), hashtags) rddHashtags = rddTweets.flatMap(lambda x: quitaNoAlfaOHash(x[2]).split(' ')).filter( lambda x: (len(x) > 1) and x[0] == '#') rddAlcanceHashtags = rddHashtags.map(lambda x: (x[1:], 1)).reduceByKey(lambda c1, c2: c1 + c2) print "Hashtags mas usados: " print rddAlcanceHashtags.takeOrdered(3, lambda x: -x[1]) # rddLower = rddTweets.map(lambda (usuario, fecha, tweet): (usuario, fecha, tweet.lower())).filter( # lambda (usuario, fecha, tweet): '#ff' in tweet) # print "Tweets con el hashtag mas usado: ", rddLower.collect() rddConHashtag = rddTweets.filter(lambda x: '#' in x[2]) rddHashtagsUsuario = rddConHashtag.map(lambda (usuario, fecha, tweet): (usuario, sacaHashtags(tweet))) rddParesHashtagUsuario = rddHashtagsUsuario.flatMap(lambda (usuario, hashtags): map(lambda h: (h, usuario), hashtags)) rddAlcanceUsuarios = rddParesHashtagUsuario.join(rddAlcanceHashtags) rddAlcanceUsuarios = rddAlcanceUsuarios.map(lambda (h, (u, f)): (u, f)).reduceByKey(lambda p1, p2: p1 + p2) print "Usuarios que mas hashtags usa: " print rddAlcanceUsuarios.takeOrdered(5, lambda x: -x[1]) rddAlcanceUsuarios = rddParesHashtagUsuario.join(rddAlcanceHashtags.filter(lambda x: x[1] == 1)) rddAlcanceUsuarios = rddAlcanceUsuarios.map(lambda (h, (u, f)): (u, f)).reduceByKey(lambda p1, p2: p1 + p2) print "Usuarios con mayor cantidad de hasthags inutiles: " print rddAlcanceUsuarios.takeOrdered(3, lambda x: -x[1]) import time import datetime def fechaATimestamp(f): return time.mktime(datetime.datetime.strptime(f, "%a %b %d %H:%M:%S +0000 %Y").timetuple()) def creaTuplasConHashtags((usuario, fecha, tweet)): res = [] palabras = quitaNoAlfaOHash(tweet).split() for p in palabras: if len(p) > 1 and p[0] == '#': res.append((p[1:], (fechaATimestamp(fecha), usuario))) return res rddHashtagsConUsuarioYFecha = rddTweets.flatMap(creaTuplasConHashtags) # rddHashtagsConUsuarioYFecha = rddTweets.flatMap( # lambda (u, f, t): map(lambda y: (y, fechaATimestamp(f), u), quitaNoAlfaOHash(t).split(' '))).filter( # lambda x: (len(x[0]) > 1) and x[0][0] == '#') rddPrimerasMenciones = rddHashtagsConUsuarioYFecha.reduceByKey(lambda x, y: x if x[0] < y[0] else y) rddPuntuacionesUsuarios = rddPrimerasMenciones.join(rddAlcanceHashtags) rddPuntuacionesUsuarios = rddPuntuacionesUsuarios.map(lambda (h, ((f, u), p)): (u, (p, [h]))).reduceByKey( lambda p, t: (p[0] + t[0], p[1] + t[1])) print "Usuarios que crean tweets con mas alcance" print rddPuntuacionesUsuarios.takeOrdered(3, lambda x: -x[1][0])
8b04ba9dab61058ce15c84c8e35a619b66973649
[ "Python" ]
1
Python
Skalextric/spark_no_evaluable
3ed0a7a69bad7950121b3bf8cf59dfaa161f2376
a6bc723d4f888d113a5f2769ffaf7559114dc4f0
refs/heads/master
<repo_name>Saifinbox/R-Assignment-2<file_sep>/Saif_KHI_R_Assingnment.R #Question 1) library("ggplot2") library("lubridate") library("dplyr") library(tidyr) library("DataCombine") hospitaldata <- read.csv("hospitaldata.csv") names(hospitaldata)<-gsub("..","",names(hospitaldata),fixed = TRUE) names(hospitaldata)<-gsub(".","_",names(hospitaldata),fixed = TRUE) View(hospitaldata) #removing character M from age i.e 28M hospitaldata$Age <- as.numeric(gsub("[^0-9]",'',hospitaldata$Age)) #Question 2) hospitaldata$Date <- as.Date(strptime(hospitaldata$Date, "%a, %B %d, %Y")) Max_day <- hospitaldata %>% mutate(Day=weekdays(hospitaldata$Date),label=TRUE) %>% group_by(Day) %>% summarize(visits=length(Day)) %>% print ggplot(Max_day,aes(x=Day,y=visits))+geom_bar(stat="identity",fill="slateblue")+ggtitle("Visits per Weekday")+labs(x="Day",y="Visits") #Question 3) mean(hospitaldata$Age, na.rm = TRUE) #Question 4) child <- filter(hospitaldata, Age > 1 & Age < 13) %>% select(-(Date:Time)) %>% select(-(Sex:Next_Apt)) %>% count() %>% print #Question 5) hospitaldata$Sex <- gsub("f","F",hospitaldata$Sex) hospitaldata$Sex<-gsub("\\s|-",NA,hospitaldata$Sex) qplot(data=hospitaldata, Sex, fill=Procedure)+ggtitle("Procedure vs Gender")+labs(x='Gender',y='Procedure') #Question 6) qplot(data=hospitaldata, fill=ConsultingDoctor, as.numeric(TotalCharges))+ggtitle("Highest Salary")+labs(x='TotalCharges',y='ConsultingDoctor') #Question 7) qplot(data=hospitaldata, as.numeric(TotalCharges), fill=Procedure)+ggtitle("Procedure")+labs(x='TotalCharges',y='Procedure') #Question 8) hour_and_visits <- hospitaldata %>% select(Time) %>% mutate(Hour = hour(hm(format(strptime(hospitaldata$Time, "%I:%M %p"), "%H:%M")))) %>% group_by(Hour) %>% summarize(visits=length(Hour)) %>% arrange(desc(visits)) %>% print # printing 13 the highest hour, i.e. actaully 1 AM/PM in 12 hour format #Question 9) #Question 10) visitor_repeated <- select(hospitaldata,id) %>% group_by(id) %>% summarise(visits=length(id)) %>% arrange(desc(visits)) %>% filter(visits > 1) %>% print #Question 11) visitor_repeated <- select(hospitaldata,id) %>% group_by(id) %>% summarise(visits=length(id)) %>% arrange(desc(visits)) %>% filter(visits > 1) %>% print #Question 12) hospitaldata %>% count(id, Procedure) %>% slice(which(n>1))%>% filter(!is.na(Procedure))%>% select(id,Procedure) #Question 13) Age_median <- hospitaldata %>% select(Sex,Age) %>% group_by(Sex) %>% summarise(median(Age, na.rm = TRUE)) %>% print #Question 14) hospitaldata$TotalCharges<-as.numeric(as.character(hospitaldata$TotalCharges)) sum_of_Balance <- sum(hospitaldata$TotalCharges, na.rm = TRUE) print(sum_of_Balance) #Question 15) hospitaldata$TotalCharges<-as.numeric(as.character(hospitaldata$TotalCharges)) consult_amount <- hospitaldata%>% select(Procedure,TotalCharges) %>% group_by(Procedure) %>% filter(Procedure == 'Consultation') %>% summarise(sum(TotalCharges,na.rm=TRUE)) %>% print #Question 16) data <- hospitaldata %>% select(Age,TotalCharges) %>% filter(!is.na(Age),!is.na(TotalCharges)) cor(data$Age,data$TotalCharges) #Question 17) Number_of_visits_by_age <- hospitaldata %>% select(id,Age) %>% group_by(Age) %>% summarize(visits=length(Age)) %>% arrange(desc(visits)) %>% filter(!is.na(Age)) %>% print ggplot(data=Number_of_visits_by_age,aes(x=as.numeric(Age),y=visits))+geom_bar(stat='identity',fill='slate blue')+ggtitle("Number Of Visits By Age")+labs(x='Age',y='Visits') #Question 18) sum(hospitaldata$TotalCharges[hospitaldata$Procedure=="X Ray" | hospitaldata$Procedure=="Scalling"],na.rm = TRUE) write.csv("~/hospitaldata.csv", row.names = FALSE) View(hospitaldata)
493ca50a8fbe44725a6bb449d462579b09cd08a2
[ "R" ]
1
R
Saifinbox/R-Assignment-2
d0378d67abf03f7a1086f0092d32cd48a48d7a5e
6ef0a7c1c36824c5ddc10f7c59fec7337839e78e
refs/heads/master
<repo_name>17611495193/-hero<file_sep>/js/index.js // 轮播图动画 (function(){ var lbt_item = document.querySelector('#lbt_item #lbt_test'); var liItems = document.querySelectorAll('#lbt_index ul li'); var lbt_cont = document.querySelector('.lbt_cont'); var index = 1; var intervalId = null; //检查index的临界值 function checkIndex (){ //判断临界值,若index = 6,切回 第二张 if ( index === 6){ lbt_item.style.left = '-604px'; index = 1; } //如果 index 为0, 表示显示的应该是最后一张, //在index的取值上,与5的图像显示的是一致的 //所以此时平移过去 if (index === 0){ lbt_item.style.left = -604 * 5 + 'px'; index = 5; } } //更新下方索引序号 function updateLiIndex(){ //处理对应下面index //index在 0和6之外的时候,li对应的是index - 1 //index === 0的时候,索引是5, 对应下标4 //index === 6, 索引是1,下标0 for (var i = 0; i < liItems.length; i++ ){ liItems[i].className = ''; } if( index === 0){ liItems[4].className = 'current'; }else if( index === 6){ liItems[0].className = 'current'; }else{ liItems[ index - 1 ].className = 'current' } } function move (fangxiang){ fangxiang = fangxiang || 1; //判断临界值 checkIndex(); index += fangxiang; animate( lbt_item, -604 * index); //更新索引 updateLiIndex(); } intervalId = setInterval( move, 1000); lbt_cont.onmouseover = function (){ clearInterval(intervalId); }; lbt_cont.onmouseout = function (){ intervalId = setInterval( move, 2000) }; // 处理index 的点击 for (var i = 0; i < liItems.length; i++){ liItems[i].onclick = function(){ //测试单机是否有效 //alert(1); index = this.value; animate(lbt_item, -604 * index); updateLiIndex(); } } })(); //顶部现实与隐藏的导航 $(function(){ $('.image > .main_nav').mouseover(function(){ console.log('aaaaaaaaa'); $(this).children('.image_nav_down').show(); }) $('.image > .main_nav').mouseleave(function () { $(this).children('.image_nav_down').hide(); }) }) //中间新闻部分的切换 $(function(){ $('#tab > .tab_item').mouseover(function(){ $(this).addClass('active').siblings().removeClass('active'); var index = $(this).index(); $('#news .main').eq(index).addClass('selected').siblings().removeClass('selected') }) }); //广告入口处摸上去有动画的部分 $(function(){ $('#enter_ul span').mouseover(function () { $(this).stop().animate({ //top: 134 opacity: 0.1 },200) }); $() $('#enter_ul span').mouseout(function(){ $(this).stop().animate({ opacity: 0.9 },100) }) }); //攻略中心左边tab栏切换 $(function(){ //var la = $('.ban_left_cont .ban_left_cont'); //console.log(la) $('#nav > .nav_item').mouseover(function(){ $(this).addClass('active').siblings().removeClass('active'); var index = $(this).index(); $('.ban_left .ban_left_cont').eq(index).addClass('selected').siblings().removeClass('selected') }) }); //攻略中心右边tab栏切换 $(function () { $('.ban_right_nav > ul > li').mouseover(function(){ $(this).addClass('active').siblings().removeClass('active'); var index = $(this).index(); $('.ban_right .ban_right_cont').eq(index).addClass('selected').siblings().removeClass('selected'); }) }) //新英雄旋转图 $(function () { // 鼠标的移入与移出 $('#wrap').mouseover(function(){ $('#arrow').css('opacity', 1); }) $('#wrap').mouseout(function(){ $('#arrow').css('opacity', 0) }) // 新建一个数组,存储所有的类样式 var classArr = ['slide1', 'slide2','slide3', 'slide4', 'slide5']; // 获取所有的li var $list = $('.slide ul li'); // 下一张 $('#arrRight').click(function(){ // 取出数组的第一项 var last = classArr.pop(); // 放到最后一项 classArr.unshift(last); for(var i = 0; i < $list.length; i++){ // 它的整体是一个dom对象,当循环遍历到每一项的时候,就是一个dom对象了 // 这是一个dom对象 // $list[i].className = classArr[i]; // 另一种方式 // 这是jQuery对象的方式 $list.eq(i).removeClass().addClass(classArr[i]); } }) // 上一张 $('#arrLeft').click(function(){ // 把最后一张取出来 var first = classArr.shift(); // 放到最前面 classArr.push(first); // 循环遍历每一个 for(var i = 0; i < $list.length; i++){ // dom的方式: // $list[i].className = classArr[i]; // jQuery的方法 $list.eq(i).removeClass().addClass(classArr[i]) } }) }); //新皮肤手风琴效果图 $(function(){ $('.parentWrap li').mousemove(function(){ $('.parentWrap li div').stop().hide(100); $(this).children('div').stop().show(200); }); $() }) //回到顶部图标 $(function(){ $(window).scroll(function () { var scrollTop = $(window).scrollTop(); //如果滚动距离大于 0 if(scrollTop > 0){ $('#totop').show(); }else{ $('#totop').hide(); } }) $('#totop').on('click', function () { $('html, body').animate({ scrollTop: 0 }) }) })
b922d54407892f070f0161e37f3480f22ec899d5
[ "JavaScript" ]
1
JavaScript
17611495193/-hero
befa499c31055d32e02470eabd83fe92bc3f0a4f
651aa6ed90868fbe86e1dfb7a7ca22800850b084
refs/heads/master
<repo_name>jalalLearn/html-css-javascript<file_sep>/javapro.js $(document).ready(function(){ $('.fa-bars').click(function(){ $('.ul-kheroje').toggle(); $('.kolshi').addClass('sticky'); $('.div-search').css('width',1200) }); $('#ft').click(function(){ $('.ul-kheroje').toggle(); $('.kolshi').removeClass('sticky'); $('.div-search').css('width',1330) }) }); $(document).ready(function(){ $('.fa-search').click(function(){ $('.div-search').toggle(); $('nav').css('margin-top',60); }) $('#qqq').click(function(){ $('.div-search').toggle(); $('nav').css('margin-top',0); }) }); $(document).ready(function(){ $(window).scroll(function(){ if(this.scrollY>40){ $('.list-nav').addClass("sticky"); } else{ $('.list-nav').removeClass("sticky"); } }) }); $(document).ready(function(){ $(window).scroll(function(){ if(this.scrollY>40){ $('.ul-kheroje').addClass("sticky"); } else{ $('.ul-kheroje').removeClass("sticky"); } }) }); var btnContainer = document.getElementsById("list"); var btns = btnContainer.getElementsByClassName("rect"); for (var i = 0; i < btns.length; i++) { btns[i].addEventListener("click", function() { var current = document.getElementsByClassName("active"); current[0].className = current[0].className.replace(" active", ""); this.className += " active"; }); };
401aa83decb5520fefc05531cdbd0eb4e0e01d6b
[ "JavaScript" ]
1
JavaScript
jalalLearn/html-css-javascript
fa35764023aeba2b119e2e1abd16e6680ac8a546
417ac67a982b4d01f56cff9fa484d5edda02c603
refs/heads/master
<file_sep>su dd if=/dev/zero of=~/test.bin count=1000k losetup /dev/loop0 test.bin <file_sep>#ifndef HEADERS_CLIENT #define HEADERS_CLIENT #include <map> int socketfd; std::map<uint32_t, void*> nodes_in_memory; //std::map<int, uint32_t> sectors_retrieved; std::map<uint32_t, uint32_t> old_and_new_sector; #define SOCKET_ERROR ((int)-1) #define INPSIZE 100 #define DISK "/dev/loop0" #define SECTOR_SIZE 512 // Default order is 4. #define DEFAULT_ORDER 4 int order = DEFAULT_ORDER; #define NUM_VALUES 3 #define LEN_VALUES 15 // Minimum order is necessarily 3. We set the maximum // order arbitrarily. You may change the maximum order. #define MIN_ORDER 3 #define MAX_ORDER 20 // Constants for printing part or all of the GPL license. #define LICENSE_FILE "LICENSE.txt" #define LICENSE_WARRANTEE 0 #define LICENSE_WARRANTEE_START 592 #define LICENSE_WARRANTEE_END 624 #define LICENSE_CONDITIONS 1 #define LICENSE_CONDITIONS_START 70 #define LICENSE_CONDITIONS_END 625 typedef uint32_t sect_type; typedef struct info { sect_type root_sect; sect_type last_sect_used; } info; /* Type representing a node in the B+ tree. * This type is general enough to serve for both * the leaf and the internal node. * The heart of the node is the array * of keys and the array of corresponding * pointers. The relation between keys * and pointers differs between leaves and * internal nodes. In a leaf, the index * of each key equals the index of its corresponding * pointer, with a maximum of order - 1 key-pointer * pairs. The last pointer points to the * leaf to the right (or NULL in the case * of the rightmost leaf). * In an internal node, the first pointer * refers to lower nodes with keys less than * the smallest key in the keys array. Then, * with indices i starting at 0, the pointer * at i + 1 points to the subtree with keys * greater than or equal to the key in this * node at index i. * The num_keys field is used to keep * track of the number of valid keys. * In an internal node, the number of valid * pointers is always num_keys + 1. * In a leaf, the number of valid pointers * to data is always num_keys. The * last leaf pointer points to the next leaf. */ typedef struct node { void * pointers[DEFAULT_ORDER]; int keys[DEFAULT_ORDER]; uint32_t sectors[DEFAULT_ORDER]; struct node * parent; uint32_t sector_parent; bool is_leaf; int num_keys; struct node * next; // Used for queue. uint32_t sector_next; uint32_t sector; } node; // TYPES. /* Type representing the record * to which a given key refers. * In a real B+ tree system, the * record would hold data (in a database) * or a file (in an operating system) * or some other information. * Users can rewrite this part of the code * to change the type and content * of the value field. */ typedef struct record { int key; char values[NUM_VALUES][LEN_VALUES]; node * parent; uint32_t parent_sect; struct record * next; uint32_t next_sect; struct record * prev; uint32_t prev_sect; uint32_t sector; } record; // GLOBALS. /* The order determines the maximum and minimum * number of entries (keys and pointers) in any * node. Every node has at most order - 1 keys and * at least (roughly speaking) half that number. * Every leaf has as many pointers to data as keys, * and every internal node has one more pointer * to a subtree than the number of keys. * This global variable is initialized to the * default value. */ /* The queue is used to print the tree in * level order, starting from the root * printing each entire rank on a separate * line, finishing with the leaves. */ node * queue = NULL; /* The user can toggle on and off the "verbose" * property, which causes the pointer addresses * to be printed out in hexadecimal notation * next to their corresponding keys. */ bool verbose_output = false; info * retr; sect_type last_sect_used; #endif <file_sep>#include "constant.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdio.h> using namespace std; void * read_sect(int sect_num) { void *block = malloc(SECTOR_SIZE); //cout<<"Implementation of the File Handler Read Method..."<<endl; int l; int f = open("/dev/loop0", O_RDWR); if(f < 0) { cout<<"Error In Opening the HardDisk File Retuning Error..."<<endl; return NULL; } //Read One Block of Data to Buffer if(lseek(f, sect_num, SEEK_SET) != sect_num) { perror("Couldn't seek"); close(f); return NULL; } if ((l = read(f, block, SECTOR_SIZE)) <= 0) { cout << "error"; return NULL; } close(f); /* Do something with the data */ /*cout<<"Length : "<<length<<endl; cout << block;*/ return block; } /* int main() { void * block; cout << "sadfsa"; block = read_sect(44); //cout << *(char*)block; return 0; }*/ <file_sep>#include "constant.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <iostream> #include <unistd.h> #include <stdlib.h> #include <stdio.h> using namespace std; int write_sect(void * cont, int sect_num,int size) { //cout<<"Implementation of the File Handler Read Method..."<<endl; int l; int f = open("/dev/loop0", O_RDWR); if(f < 0) { cout<<"Error In Opening the HardDisk File Retuning Error..."<<endl; return -1; } //Read One Block of Data to Buffer if(lseek(f, sect_num, SEEK_SET) != sect_num) { perror("Couldn't seek"); close(f); return -1; } if ((l = write(f, cont, size)) <= 0) { cout << "error"; return -1; } close(f); /* Do something with the data */ /*cout<<"Length : "<<length<<endl; cout << block;*/ return 1; } /* int main() { char block[SECTOR_SIZE] = "0000000000"; write_sect((void *)block, 44); return 0; } * */ <file_sep>#ifndef CONSTANT_H #define CONSTANT_H #define DISK "/dev/loop0" #define SECTOR_SIZE 512 #endif <file_sep>#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <iostream> #include "header_cli.h" //write len bytes on the given socket int writen(int sock, char *buf, int len) { int nsent = 0, ris; while (nsent < len) { ris = send(sock, buf+nsent, len-nsent, MSG_NOSIGNAL); if (ris == -1 && errno == EINTR) continue; else if (ris <= 0) return ris; nsent += ris; } return nsent; } //here I can improve by sending few packages //read len bytes from the given socket int readn(int sock, char *buf, int len) { int nread = 0, ris; while (nread < len) { ris = read(sock, buf+nread, len-nread); if (ris == -1 && errno == EINTR) continue; else if (ris <= 0) return ris; nread += ris; } return nread; } int sendData(int sock, void * data, sect_type sect, int size){ uint32_t l, s, ack, ack_net, size_net; if (writen(sock, (char*)"wr", 3)<=0) { perror("command"); return -1; } s = htonl(sect); if (writen(sock, (char*)&s, 4)<=0) { perror("number of the sector"); return -1; } size_net = htonl(size); std::cout << size_net << "\n"; std::cout << size << "\n"; if (writen(sock, (char*)&size_net, 4)<=0) { perror("number of the sector"); return -1; } if (writen(sock, (char*)data, size)<=0) { perror("data of the sector"); return -1; } if (readn(sock,(char*)&ack_net, 4) <=0){ perror("ack"); return -1; } ack = ntohl(ack_net); if (ack != sect) { perror ("write failed"); return -1; } std::cout << "ack ok\n"; return 0; } void * retrieveData(int sock, sect_type sector) { uint32_t l, l_comm, ack, sect; int len, ack_int; char * ris; l = htonl(sizeof(uint32_t)); l_comm = htonl(2); sect = htonl(sector); //here I send that I want to read if (writen(sock, (char*)"re", 3)<=0) { perror("command"); return NULL; } //I have to send the number of the sector of the data to be retrieved if (writen(sock, (char*)&sect, 4)<=0) { perror("number of the sector"); return NULL; } //here I receive the length of te record /* if (readn(sock, (char*)&l, 4)<=0) { perror("receiving length"); return NULL; } len = ntohl(l);*/ //I suppose that all the records are 512 byte ris = (char*)malloc(SECTOR_SIZE); /* here I receive the answer */ if (readn(sock, ris, SECTOR_SIZE)<=0) { perror("record not retrieved"); free(ris); return NULL; } /* //this is the acknowledgment for the server if (writen(sock, (char*)sect, 4)<=0) { perror("ack client send"); return NULL; } //this is the acknowledgment of the server if (readn(sock, (char*)&ack, 4)<=0) { perror("receiving length"); return NULL; } if (ntohl(ack) != sector){ return NULL; }*/ return (void*) ris; } int serverConnectionFinish(int socketfd) { char ack[2]; if (writen(socketfd, (char*)"xx", 3)<=0) { perror("command"); return -1; } if (readn(socketfd, (char*)&ack, 3)<=0) { perror("receiving ack"); return -1; } if (strcmp(ack, "xx")!= 0) { return -1; } close(socketfd); return 1; } //here I need the socket file descriptor only int serverConnectionInit(char *ip_addr,char *port, int *socket_main) { struct sockaddr_in Local, Serv; char *string_remote_ip_address; short int remote_port_number; int ris, socketfd; char inp[INPSIZE]; string_remote_ip_address = (char *)ip_addr; remote_port_number = atoi(port); /* get a datagram socket */ socketfd = socket(AF_INET, SOCK_STREAM, 0); if (socketfd == SOCKET_ERROR) { printf ("socket() failed, Err: %d \"%s\"\n", errno,strerror(errno)); return 1; } /* name the socket */ memset ( &Local, 0, sizeof(Local) ); Local.sin_family = AF_INET; Local.sin_addr.s_addr = htonl(INADDR_ANY); /* wildcard */ Local.sin_port = htons(0); ris = bind(socketfd, (struct sockaddr*) &Local, sizeof(Local)); if (ris == SOCKET_ERROR) { printf ("bind() failed, Err: %d \"%s\"\n",errno,strerror(errno)); return 1; } /* assign our destination address */ memset ( &Serv, 0, sizeof(Serv) ); Serv.sin_family = AF_INET; Serv.sin_addr.s_addr = inet_addr(string_remote_ip_address); Serv.sin_port = htons(remote_port_number); /* connection request */ //std::cout << ip_addr << " " << port << "\n"; ris = connect(socketfd, (struct sockaddr*) &Serv, sizeof(Serv)); if (ris == SOCKET_ERROR) { printf ("connect() failed, Err: %d \"%s\"\n",errno,strerror(errno)); //in case of error must handle it and send an error message return 1; } *socket_main = socketfd; return 0; } /* int main(int argc, char * argv[]) { int sock, l, ri; char * read_res; char sent[512] = "llslsllslllslllslllsllslslls"; serverConnectionInit("127.0.0.1", "3333", &sock); ri = sendData(sock, sent, 44); printf("%d\n",ri ); read_res = (char *)retrieveData(sock, 44); printf("%s\n", read_res); l = serverConnectionFinish(sock); std::cout << l << "\n"; return 0; } */ <file_sep>#include "cli.cpp" //#include "bpt.cpp" #include "header_cli.h" #include <map> #include <list> #include <cctype> #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ #include <stdio.h> #include <iostream> void *retrieveDataFake(int socketfd, uint32_t sector){ std::list<uint32_t> nodes_to_retrieve; std::list<uint32_t>::const_iterator it_list; uint32_t list_to_put, old = 0; void * sec; int i, flag = 0; std::map<uint32_t, void*>::const_iterator it = nodes_in_memory.find(sector); if (it!=nodes_in_memory.end()) return nodes_in_memory[sector]; nodes_to_retrieve.push_back(sector); last_sect_used = retr->last_sect_used; for (i=0;i<2;i++) { //this is not working very well, can be better //std::cout << i << "in for\n"; while (1) { list_to_put = (rand() % last_sect_used) + 1; //std::cout << list_to_put << "\n"; if(((nodes_in_memory.size() == last_sect_used + 1 )&& i==0) || ((nodes_in_memory.size() == last_sect_used)&& i==1) ) { flag = 1; break; } if(nodes_in_memory.find(list_to_put) == nodes_in_memory.end() && list_to_put != sector) { //std::cout << i << " " << list_to_put << " " << old << "\n"; if (i==1 && list_to_put != old) { flag = 2; break; } else if(i == 0){ flag = 2; break; } } } //std::cout << list_to_put << "\n"; if (flag == 2) { if (i == 0) old = list_to_put; nodes_to_retrieve.push_back(list_to_put); } } //std::cout << "retrieving via socket\n"; nodes_to_retrieve.sort(); for(it_list=nodes_to_retrieve.begin();it_list!=nodes_to_retrieve.end(); ++it_list) { sec = retrieveData(socketfd, *it_list); nodes_in_memory[*it_list] = sec; //std::cout << "retrieved " << *it_list << "\n"; } return nodes_in_memory[sector]; } void * retrieveRoot(void) { node * root; retr = (info *)retrieveData(socketfd, 0); //std::cout << retr->root_sect << " " << retr->last_sect_used << "\n"; //std::cout << "retrievedInfo\n"; root = (node *)retrieveDataFake(socketfd, retr->root_sect); //std::cout << "retrievedRoot\n"; return root; } int sendTree (void * root) { } int main(int argc, char *argv[]) { node * root; srand (time(NULL)); serverConnectionInit(argv[1], argv[2], &socketfd); if((root = (node *)retrieveRoot()) == NULL) exit (1); //here I have to implement the queries }
a3c168817c193a5f56b1907dd5d924acb893311f
[ "C", "C++", "Shell" ]
7
Shell
ste93/thesis
1a159a747bc4cf80690ed4daf0dee0a23448dde0
e7f1ee6a2ebf5e32c691aeb52f2c333a7ebd15b2
refs/heads/master
<file_sep>package runnable.boundedBuffer; import structures.boundedbuffer.BoundedBuffer; /** * A single Bounded Buffer consumer thread * @author james * */ public class IntConsumerRunnable implements Runnable { private int numberOutputs; private BoundedBuffer<Integer> buffer = null; /** * Default (random) number of inputs to remove from the buffer. * @param buf - Bounded Buffer for use. */ public IntConsumerRunnable(BoundedBuffer<Integer> buf){ buffer = buf; numberOutputs = new Double(Math.random()*30).intValue(); System.out.println("cons runable num of inputs: " + numberOutputs); } /** * * @param buf - Bounded Buffer for use. * @param numOfInputs - Number of input to place in the buffer. */ public IntConsumerRunnable(BoundedBuffer<Integer> buf, int numOfInputs){ buffer = buf; numberOutputs = numOfInputs; System.out.println("cons runable num of inputs: " + numberOutputs); } /** * Overrides Runnable's run() method. Removes specified number of values from specified buffer. */ @Override public void run(){ if(buffer == null){ return; } for(int i = 0; i < numberOutputs; i ++){ System.out.println("popped: " + buffer.pop()); } System.out.println("Cons Runnable done"); } } <file_sep>package testing.boundedBuffer; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; import runnable.threadController.IntBoundedBufferController; import runnable.threadController.ThreadNumberException; public class BoundedBufferEdgeCase1 { IntBoundedBufferController controller; @Before public void setUp() throws Exception { controller = new IntBoundedBufferController(4, 3); } @After public void tearDown() throws Exception { controller = null; } @Test public void test() { try{ controller.run(); }catch(ThreadNumberException e){ System.out.println(e.getMessage()); } } } <file_sep>package runnable.boundedBuffer; import structures.boundedbuffer.BoundedBuffer; /** * A single Bounded Buffer producer thread * @author james * */ public class IntProducerRunnable implements Runnable{ private int numberInputs; private BoundedBuffer<Integer> buffer = null; /** * Default (random) number of inputs to place in the buffer. * @param buf - Bounded Buffer for use. */ public IntProducerRunnable(BoundedBuffer<Integer> buf){ buffer = buf; numberInputs = new Double(Math.random()*50).intValue(); System.out.println("prod runable num of inputs: " + numberInputs); } /** * * @param buf - Bounded Buffer for use. * @param numOfInputs - Number of input to place in the buffer. */ public IntProducerRunnable(BoundedBuffer<Integer> buf, int numOfInputs){ buffer = buf; numberInputs = numOfInputs; System.out.println("prod runable num of inputs: " + numberInputs); } /** * Overrides Runnable's run() method. Places specified number of values into specified buffer. */ @Override public void run() { if(buffer == null){ return; //Throw exception. } for(int i = 0; i < numberInputs; i++){ buffer.put(new Double(Math.random()*100).intValue()); } System.out.println("producerRunnable Complete"); } } <file_sep>package runnable.boundedBuffer; import java.util.Iterator; import structures.boundedbuffer.BoundedBuffer; public class IntDisplayRunnable implements Runnable { private BoundedBuffer<Integer> buffer; public IntDisplayRunnable(BoundedBuffer<Integer> buf){ buffer = buf; } @Override public void run() { Iterator<Integer> it = buffer.getDeepCopy().iterator(); while(it.hasNext()){ System.out.print(it.next() + " "); } System.out.println("print completed"); } }
f7fd983b1f52aa9b8374bb6daaf3b9b9a6983109
[ "Java" ]
4
Java
JamesAlexander1/JavaConcurrency
2587f19322e96032a64956eeaf2fcb32bec2c0a2
50e6e33a3e23d297f38209637a82553e46a80fc6
refs/heads/main
<file_sep>import React, {useState} from 'react'; const ApiComponent = () => { const [apiKey, setApiKey] = useState(""); const updateApi =(event) => { event.preventDefault(); setApiKey(event.target.value); } } export default ApiComponent; <file_sep>import React, {useState} from 'react'; import axios from 'axios'; import ApiComponent from './ApiKey'; import FilmComponent from './Film'; const FilmRequestComponent = () => { const [data, setData] = useState(""); const [apiKey, setApiKey] = useState(""); const [film, setFilm] = useState(""); const makeRequest =(event) => { axios.get(`http://www.omdbapi.com/?apikey=${apiKey}&t=${film}`) .then(response => { console.log(response.data); setData(response.data); }); } return( <> <div> <h1>Welcome to Film's Library</h1> <br/> <p>Please enter your Api key:</p> <input type="text" onChange={(event) => updateApi(event)}/> <br/> <p>Please enter the film name:</p> <input type="text" onChange={(event) => updateFilm(event)}/> <br/> <button onClick={(event) => makeRequest(event)}>Press to search for films</button> <br/> <br/> <br/> <h2>{data.Title}</h2> <br/> <h3>{data.Year}</h3> <h3>{data.Genre}</h3> </div> </> ); } export default FilmRequestComponent; <file_sep>import FilmRequestComponent from './components/react-project/FilmRequest'; import ApiComponent from './components/react-project/ApiKey'; import FilmComponent from './components/react-project/Film'; function App() { return( <> <FilmRequestComponent/> </> ); } export default App;
4e2b734718b3c10b91d294a9b8cae6cd9007856b
[ "JavaScript" ]
3
JavaScript
lisandrodv27/react-film-library
7a9ea441d15e3eb79e1cfcb9aceb3b141f94d542
c88446f9002819510ed9ceb99b4171d8063d06eb
refs/heads/main
<file_sep>import React, { Fragment, useState, useEffect } from 'react'; import axios from 'axios'; import Spinner from 'react-bootstrap/Spinner'; import Button from 'react-bootstrap/Button'; import InputGroup from 'react-bootstrap/InputGroup'; import Card from 'react-bootstrap/Card'; import ListGroup from 'react-bootstrap/ListGroup'; function Search() { const [data, setData] = useState([]); const [query, setQuery] = useState(''); const [param, setParam] = useState(''); const [url, setUrl] = useState( `${process.env.REACT_APP_BACKEND_URL}/v1/vehicles/search`, ); const [isLoading, setIsLoading] = useState(false); const [isError, setIsError] = useState(false); useEffect(() => { const fetchData = async () => { setIsError(false); setIsLoading(true); try { const result = await axios(url); setData(result.data); } catch (error) { setIsError(true); } setIsLoading(false); }; fetchData(); }, [url]); return ( <Fragment> <InputGroup className="mb-3 d-flex justify-content-center"> <input type="text" value={query} onChange={event => setQuery(event.target.value)} /> <select size="lg" value={param} onChange={event => setParam(event.target.value)}> <option value="">Select Option</option> <option value="model_name">Model Name</option> <option value="brand_name">Brand Name</option> <option value="year">Year greater than</option> <option value="mileage">Mileage lower than</option> <option value="price">Price lower than</option> </select> <Button variant="primary" type="button" onClick={() => setUrl(`${process.env.REACT_APP_BACKEND_URL}/v1/vehicles/search?${param}=${query}`) } > Search </Button> </InputGroup> {isError && <div>Something went wrong ...</div>} {isLoading ? ( <div> <Spinner animation="border" role="status"></Spinner> </div> ) : ( <Card> <ListGroup variant="flush"> {data.map(item => ( <ListGroup.Item key={item.id}> <div><strong>Model: </strong>{item.model_name}</div> <span><strong>Brand: </strong>{item.brand_name} </span> <span><strong>Year: </strong>{item.year} </span> <span><strong>Mileage: </strong>{item.mileage} mi </span> <span><strong>Price: </strong>{currencyFormat(item.price)} </span> </ListGroup.Item> ))} </ListGroup> </Card> )} </Fragment> ); } function currencyFormat(num) { return '$' + num.toFixed(2).replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') } export default Search;<file_sep>## Installation and Usage In this repository are the back-end and frontend which were created with the webpack=react flag that Rails offers 1. Clone the project to your local directory ``` git clone https://github.com/jstiven01/autocom-frontend.git ``` 2. Get in to the folder app ``` cd autocom-frontend ``` 3. You SHOULD run first the Backend server The Backend server will take the localhost:3000 and this command will open the app in localhost:3001 ``` yarn start ``` <file_sep>import './App.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import Search from './components/Search' function App() { return ( <div className="App"> <h1>Search Vehicles</h1> <Search /> </div> ); } export default App;
a2f7b7fca5844f225ae88121fee4d029f2fddceb
[ "JavaScript", "Markdown" ]
3
JavaScript
jstiven01/autocom-frontend
670e822a433c4dbe53be067e594d2aab4cdeb8cf
ad3f64d2d93a7843a1bcdd731a6d203650fe35d1
refs/heads/master
<file_sep>extern crate bytes; extern crate failure; #[macro_use] extern crate failure_derive; #[macro_use] extern crate futures; #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; extern crate hex; extern crate rand; extern crate ring; extern crate snow; extern crate rustls; extern crate tokio; extern crate tokio_core; extern crate webpki; extern crate webpki_roots; pub use client::Client; pub use server::Server; mod client; mod codec; mod conn_state; mod crypto; mod frame; mod nquic; pub mod http; mod packet; mod parameters; mod server; pub mod streams; pub mod handshake; mod types; #[derive(Debug, Fail)] pub enum QuicError { #[fail(display = "{}", _0)] AddrParse(#[cause] std::net::AddrParseError), #[fail(display = "needed slice of size {}, found {}", _0, _1)] AllocationError(usize, usize), #[fail(display = "application close ({}): '{}'", _0, _1)] ApplicationClose(u16, String), #[fail(display = "connection close ({}): '{}'", _0, _1)] ConnectionClose(u16, String), #[fail(display = "")] DecryptError, #[fail(display = "")] EncryptError, #[fail(display = "{}", _0)] General(String), #[fail(display = "{}", _0)] InvalidDnsName(String), #[fail(display = "{}", _0)] Io(#[cause] std::io::Error), #[fail(display = "{}", _0)] Tls(#[cause] rustls::TLSError), #[fail(display = "{}", _0)] DecodeError(String), #[fail(display = "")] Timeout, } impl From<std::io::Error> for QuicError { fn from(e: std::io::Error) -> QuicError { QuicError::Io(e) } } impl From<std::net::AddrParseError> for QuicError { fn from(e: std::net::AddrParseError) -> QuicError { QuicError::AddrParse(e) } } impl From<rustls::TLSError> for QuicError { fn from(e: rustls::TLSError) -> QuicError { QuicError::Tls(e) } } pub type QuicResult<O> = std::result::Result<O, QuicError>; pub const QUIC_VERSION: u32 = 0xff00_000b; <file_sep>use crypto::Secret; use parameters::{ClientTransportParameters, ServerTransportParameters, TransportParameters}; use types::Side; use super::{QuicError, QuicResult}; use codec::Codec; use std::str; use std::io::Cursor; use super::QUIC_VERSION; use hex; use ring::aead::AES_256_GCM; use ring::digest::SHA256; use snow; use snow::NoiseBuilder; use snow::params::NoiseParams; lazy_static! { static ref PARAMS: NoiseParams = "Noise_IK_25519_AESGCM_SHA256".parse().unwrap(); } const STATIC_DUMMY_SECRET : [u8; 32] = [ 0xe0, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 ]; pub struct ClientSession { static_key : [u8; 32], // client secret remote_key : [u8; 32], // server public session : Option<snow::Session>, // noise snow session params_remote : Option<ServerTransportParameters>, // authenticated remote transport parameters params_local : ClientTransportParameters, // transport parameters } pub struct ServerSession { static_key : [u8; 32], // server secret session : Option<snow::Session>, // noise snow session params_remote : Option<ClientTransportParameters>, // authenticated remote transport parameters params_local : ServerTransportParameters, // transport parameters auth_check : fn([u8; 32]) -> bool // application specific auth. check } pub trait Session { fn process_handshake_message(&mut self, &[u8]) -> QuicResult<HandshakeResult>; fn set_prologue(&mut self, prologue : &[u8]) -> QuicResult<()>; fn get_transport_parameters(&self) -> Option<TransportParameters>; } fn no_auth(pk : [u8; 32]) -> bool { println!("debug : client identity : {}", hex::encode(&pk)); true } pub fn client_session( remote_key : [u8; 32], static_key : Option<[u8; 32]>, params : ClientTransportParameters, ) -> ClientSession { ClientSession { static_key: static_key.unwrap_or(STATIC_DUMMY_SECRET), params_remote: None, params_local: params, remote_key, session: None } } pub fn server_session( static_key : [u8; 32], params : ServerTransportParameters, ) -> ServerSession { ServerSession { static_key: static_key, params_remote: None, params_local: params, session: None, auth_check: no_auth, } } impl Session for ClientSession { fn set_prologue(&mut self, _prologue : &[u8]) -> QuicResult<()> { Err(QuicError::General("setting prologue on client".to_owned())) } fn get_transport_parameters(&self) -> Option<TransportParameters> { match &self.params_remote { Some(p) => Some(p.parameters.clone()), None => None, } } fn process_handshake_message(&mut self, msg: &[u8]) -> QuicResult<HandshakeResult> { let session = self.session.as_mut().unwrap(); let mut payload = vec![0u8; 65535]; match session.read_message(msg, &mut payload) { Ok(n) => { // parse server transport parameters self.params_remote = Some({ let mut read = Cursor::new(&payload[..n]); ServerTransportParameters::decode(&mut read)? }); assert!(session.is_initiator()); assert!(session.is_handshake_finished()); // export key material let (k1, k2) = session.export().unwrap(); let secret = Secret::For1Rtt(&AES_256_GCM, &SHA256, k1.to_vec(), k2.to_vec()); println!("debug : params_remote = {:?}", &self.params_remote); println!("debug : exporting key material from Noise:"); println!("debug : i->r : {}", hex::encode(k1)); println!("debug : i<-r : {}", hex::encode(k2)); Ok((None, Some(secret))) }, Err(_) => Err(QuicError::General("failed to decrypt noise".to_owned())) } } } impl ClientSession { pub fn create_handshake_request(&mut self, prologue : &[u8]) -> QuicResult<Vec<u8>> { // sanity check if let Some(_) = self.session { panic!("Multiple calls to create_handshake_request"); } // build Noise session self.session = Some({ let builder = NoiseBuilder::new(PARAMS.clone()); builder .prologue(prologue) .local_private_key(&self.static_key) .remote_public_key(&self.remote_key) .build_initiator().unwrap() }); // serialize parameters let session = self.session.as_mut().unwrap(); let mut payload = Vec::new(); self.params_local.encode(&mut payload); let mut msg = vec![0u8; 65535]; let len = session.write_message(&payload, &mut msg).unwrap(); Ok(msg[..len].to_owned()) } } impl Session for ServerSession { fn set_prologue(&mut self, prologue : &[u8]) -> QuicResult<()> { match self.session { Some(_) => Err(QuicError::General("setting prologue after processing handshake request".to_owned())), None => { self.session = Some({ let builder = NoiseBuilder::new(PARAMS.clone()); builder .local_private_key(&self.static_key) .prologue(prologue) .build_responder().unwrap() }); Ok(()) } } } fn get_transport_parameters(&self) -> Option<TransportParameters> { match &self.params_remote { Some(p) => Some(p.parameters.clone()), None => None, } } fn process_handshake_message(&mut self, msg: &[u8]) -> QuicResult<HandshakeResult> { println!("debug : process handshake message"); let session = self.session.as_mut().unwrap(); let mut payload = vec![0u8; 65535]; match session.read_message(msg, &mut payload) { Ok(n) => { // parse client transport parameters let parameters = { let mut read = Cursor::new(&payload[..n]); ClientTransportParameters::decode(&mut read)? }; self.params_remote = Some(parameters.clone()); println!("debug : client parameters {:?}", &parameters); // validate initial_version (this is the only supported version) if parameters.initial_version != QUIC_VERSION { return Err( QuicError::General("failed to decrypt noise".to_owned()) ); }; // validate client identity let auth_ok = match session.get_remote_static() { None => false, Some(key) => { let mut pk = [0u8; 32]; pk[..].clone_from_slice(key); (self.auth_check)(pk) } }; if !auth_ok { return Err( QuicError::General("client idenity rejected".to_owned()) ); } // create handshake response let resp = { let mut payload = Vec::new(); let mut msg = vec![0u8; 65535]; self.params_local.encode(&mut payload); let len = session.write_message(&payload, &mut msg).unwrap(); assert!(session.is_handshake_finished()); msg[..len].to_owned() }; // export transport keys println!("debug : exporting key material from Noise:"); assert!(!session.is_initiator()); assert!(session.is_handshake_finished()); let (k1, k2) = session.export().unwrap(); let secret = Secret::For1Rtt( &AES_256_GCM, &SHA256, k1.to_vec(), k2.to_vec() ); println!("debug : i->r : {}", hex::encode(k1)); println!("debug : i<-r : {}", hex::encode(k2)); Ok((Some(resp), Some(secret))) }, Err(_) => Err(QuicError::General("failed to decrypt noise".to_owned())) } } } pub trait QuicSide { fn side(&self) -> Side; } impl QuicSide for ClientSession { fn side(&self) -> Side { Side::Client } } impl QuicSide for ServerSession { fn side(&self) -> Side { Side::Server } } type HandshakeResult = (Option<Vec<u8>>, Option<Secret>); fn to_vec<T: Codec>(val: &T) -> Vec<u8> { let mut bytes = Vec::new(); val.encode(&mut bytes); bytes } const ALPN_PROTOCOL: &str = "hq-11"; <file_sep>use bytes::{Buf, BufMut}; use codec::{BufLen, Codec, VarLen}; use {QuicError, QuicResult}; // On the wire: // len: VarLen // ptype: u8 // flags: u8 // payload: [u8] #[derive(Debug, PartialEq)] enum HttpFrame { Settings(SettingsFrame), } impl Codec for HttpFrame { fn encode<T: BufMut>(&self, buf: &mut T) { match self { HttpFrame::Settings(f) => { f.len().encode(buf); buf.put_u8(0x4); f.encode(buf); } } } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let len = VarLen::decode(buf)?.0 as usize; match buf.get_u8() { 0x4 => Ok(HttpFrame::Settings(SettingsFrame::decode( &mut buf.take(1 + len), )?)), v => Err(QuicError::DecodeError(format!( "unsupported HTTP frame type {}", v ))), } } } #[derive(Debug, PartialEq)] struct SettingsFrame(Settings); impl Codec for SettingsFrame { fn encode<T: BufMut>(&self, buf: &mut T) { buf.put_u8(0); buf.put_u16_be(0x1); let encoded = VarLen(u64::from(self.0.header_table_size)); let encoded_len = encoded.buf_len(); debug_assert!(encoded_len < 64); VarLen(encoded_len as u64).encode(buf); encoded.encode(buf); buf.put_u16_be(0x6); let encoded = VarLen(u64::from(self.0.max_header_list_size)); let encoded_len = encoded.buf_len(); debug_assert!(encoded_len < 64); VarLen(encoded_len as u64).encode(buf); encoded.encode(buf); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<SettingsFrame> { if buf.get_u8() != 0 { return Err(QuicError::DecodeError("unsupported flags".into())); } let mut settings = Settings::default(); while buf.has_remaining() { let tag = buf.get_u16_be(); if tag != 0x1 && tag != 0x6 { return Err(QuicError::DecodeError("unsupported tag".into())); } VarLen::decode(buf)?; let val = VarLen::decode(buf)?; if tag == 0x1 { settings.header_table_size = val.0 as u32; } else if tag == 0x6 { settings.max_header_list_size = val.0 as u32; } } Ok(SettingsFrame(settings)) } } impl FrameHeader for SettingsFrame { fn len(&self) -> VarLen { VarLen( (6 + VarLen(u64::from(self.0.header_table_size)).buf_len() + VarLen(u64::from(self.0.max_header_list_size)).buf_len()) as u64, ) } fn flags(&self) -> u8 { 0 } fn ftype(&self) -> u8 { 0x4 } } impl<T> BufLen for T where T: FrameHeader, { fn buf_len(&self) -> usize { let len = self.len(); 2 + VarLen(len.0).buf_len() + (len.0 as usize) } } pub trait FrameHeader { fn len(&self) -> VarLen; fn flags(&self) -> u8; fn ftype(&self) -> u8; fn encode_header<T: BufMut>(&self, buf: &mut T) { self.len().encode(buf); buf.put_u8(self.ftype()); buf.put_u8(self.flags()); } } #[derive(Debug, PartialEq)] pub struct Settings { header_table_size: u32, max_header_list_size: u32, } impl Default for Settings { fn default() -> Settings { Settings { header_table_size: 65536, max_header_list_size: 65536, } } } #[cfg(test)] mod tests { use codec::Codec; use std::io::Cursor; #[test] fn test_settings_frame() { let settings = super::Settings { header_table_size: 131072, max_header_list_size: 65536, }; let frame = super::HttpFrame::Settings(super::SettingsFrame(settings)); let mut buf = Vec::new(); frame.encode(&mut buf); assert_eq!( &buf, &[14, 4, 0, 0, 1, 4, 128, 2, 0, 0, 0, 6, 4, 128, 1, 0, 0] ); let mut read = Cursor::new(&buf); let decoded = super::HttpFrame::decode(&mut read).unwrap(); assert_eq!(decoded, frame); } } <file_sep>use futures::sync::mpsc::{self, Receiver, Sender}; use futures::{Async, AsyncSink, Future, Poll, Sink, Stream}; use super::{QuicError, QuicResult}; use conn_state::ConnectionState; use crypto::Secret; use packet::{LongType, PartialDecode}; use parameters::ServerTransportParameters; use handshake; use types::ConnectionId; use std::collections::{hash_map::Entry, HashMap}; use std::net::{SocketAddr, ToSocketAddrs}; use tokio::{self, net::UdpSocket}; pub struct Server { socket: UdpSocket, in_buf: Vec<u8>, connections: HashMap<ConnectionId, Sender<Vec<u8>>>, send_queue: PacketChannel, key: [u8; 32], } impl Server { pub fn new(ip: &str, port: u16, key: [u8; 32]) -> QuicResult<Self> { let addr = (ip, port) .to_socket_addrs()? .next() .ok_or_else(|| QuicError::General("no address found for host".into()))?; Ok(Server { socket: UdpSocket::bind(&addr)?, in_buf: vec![0u8; 65536], connections: HashMap::new(), send_queue: mpsc::channel(5), key, }) } fn received(&mut self, addr: SocketAddr, len: usize) -> QuicResult<()> { let connections = &mut self.connections; let packet = &mut self.in_buf[..len]; let (dst_cid, ptype) = { let partial = PartialDecode::new(packet)?; println!("debug : incoming packet: {:?} {:?}", addr, partial.header); (partial.dst_cid(), partial.header.ptype()) }; let cid = if ptype == Some(LongType::Initial) { let mut state = ConnectionState::new( handshake::server_session(self.key, ServerTransportParameters::default().clone()), Some(Secret::Handshake(dst_cid)), ); let cid = state.pick_unused_cid(|cid| connections.contains_key(&cid)); let (recv_tx, recv_rx) = mpsc::channel(5); tokio::spawn( Connection::new(addr, state, self.send_queue.0.clone(), recv_rx).map_err(|e| { error!("error spawning connection: {:?}", e); }), ); connections.insert(cid, recv_tx); cid } else { dst_cid }; match connections.entry(cid) { Entry::Occupied(mut inner) => { let mut sink = inner.get_mut(); forward_packet(sink, packet.to_vec())?; } Entry::Vacant(_) => println!("debug : connection ID {:?} unknown", cid), } Ok(()) } fn poll_next(&mut self) -> Option<(SocketAddr, Vec<u8>)> { match self.send_queue.1.poll() { Ok(Async::Ready(msg)) => msg, Ok(Async::NotReady) => None, Err(e) => { error!("error polling send queue: {:?}", e); None } } } } impl Future for Server { type Item = (); type Error = (); fn poll(&mut self) -> Poll<Self::Item, Self::Error> { let mut waiting; loop { waiting = true; match self.socket.poll_recv_from(&mut self.in_buf) { Ok(Async::Ready((len, addr))) => { waiting = false; if let Err(e) = self.received(addr, len) { error!("error while handling received packet: {:?}", e); } } Ok(Async::NotReady) => {} Err(e) => error!("Server RECV ERROR: {:?}", e), } if let Some((addr, msg)) = self.poll_next() { waiting = false; match self.socket.poll_send_to(&msg, &addr) { Ok(Async::Ready(_)) => {} Ok(Async::NotReady) => {} Err(e) => error!("Server poll_send_to ERROR {:?}", e), } } if waiting { break; } } Ok(Async::NotReady) } } fn forward_packet(sink: &mut Sender<Vec<u8>>, msg: Vec<u8>) -> QuicResult<()> { match sink.start_send(msg) { Ok(AsyncSink::Ready) => {} Ok(AsyncSink::NotReady(msg)) => error!("discarding message: {:?}", msg), Err(e) => { return Err(QuicError::General(format!( "error while starting channel send: {:?}", e ))); } } match sink.poll_complete() { Ok(Async::Ready(())) => {} Ok(Async::NotReady) => {} Err(e) => { return Err(QuicError::General(format!( "error while polling channel complete: {:?}", e ))); } } Ok(()) } struct Connection { addr: SocketAddr, state: ConnectionState<handshake::ServerSession>, send: Sender<(SocketAddr, Vec<u8>)>, recv: Receiver<Vec<u8>>, } impl Connection { fn new( addr: SocketAddr, state: ConnectionState<handshake::ServerSession>, send: Sender<(SocketAddr, Vec<u8>)>, recv: Receiver<Vec<u8>>, ) -> Self { Self { addr, state, send, recv, } } } impl Future for Connection { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { loop { let mut received = false; match self.recv.poll() { Ok(Async::Ready(Some(ref mut msg))) => { self.state.handle(msg).unwrap(); received = true; } Ok(Async::Ready(None)) => {} Ok(Async::NotReady) => {} Err(e) => error!("error from server: {:?}", e), } let mut sent = false; match self.state.queued() { Ok(Some(msg)) => match self.send.start_send((self.addr, msg.clone())) { Ok(AsyncSink::Ready) => { sent = true; } Ok(AsyncSink::NotReady(msg)) => { error!("start send not ready: {:?}", msg); } Err(e) => error!("error sending: {:?}", e), }, Ok(None) => {} Err(e) => error!("error from connection state: {:?}", e), } if sent { self.state.pop_queue(); } let flushed = false; match self.send.poll_complete() { Ok(Async::Ready(())) => {} Ok(Async::NotReady) => {} Err(e) => error!("error from flushing sender: {:?}", e), } if !(received || sent || flushed) { break; } } Ok(Async::NotReady) } } type PacketChannel = ( Sender<(SocketAddr, Vec<u8>)>, Receiver<(SocketAddr, Vec<u8>)>, ); <file_sep>use bytes::{Buf, BufMut}; use std::fmt; use std::io::Cursor; use ring::aead::{self, OpeningKey, SealingKey}; use ring::{digest, hkdf}; pub use ring::aead::AES_256_GCM; pub use ring::digest::SHA256; pub use ring::hmac::SigningKey; use super::{QuicError, QuicResult}; use types::{ConnectionId, Side}; pub enum Secret { Handshake(ConnectionId), For1Rtt( &'static aead::Algorithm, &'static digest::Algorithm, Vec<u8>, Vec<u8>, ), } impl Secret { pub fn tag_len(&self) -> usize { match self { Secret::Handshake(_) => AES_256_GCM.tag_len(), Secret::For1Rtt(aead_alg, _, _, _) => aead_alg.tag_len(), } } pub fn build_key(&self, side: Side) -> PacketKey { match self { Secret::Handshake(cid) => { let label = if side == Side::Client { b"client hs" } else { b"server hs" }; PacketKey::new( &AES_256_GCM, &SHA256, &expanded_handshake_secret(*cid, label), ) } Secret::For1Rtt(aead_alg, hash_alg, ref client_secret, ref server_secret) => { PacketKey::new( aead_alg, hash_alg, match side { Side::Client => client_secret, Side::Server => server_secret, }, ) } } } } impl fmt::Debug for Secret { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Secret::Handshake(cid) => write!(f, "Handshake({:?})", cid), Secret::For1Rtt(_, _, _, _) => write!(f, "For1Rtt(<secret>)"), } } } pub struct PacketKey { alg: &'static aead::Algorithm, data: Vec<u8>, split: usize, } impl PacketKey { pub fn new( aead_alg: &'static aead::Algorithm, hash_alg: &'static digest::Algorithm, secret: &[u8], ) -> Self { let mut res = Self { alg: aead_alg, data: vec![0; aead_alg.key_len() + aead_alg.nonce_len()], split: aead_alg.key_len(), }; let secret_key = SigningKey::new(hash_alg, secret); qhkdf_expand(&secret_key, b"key", &mut res.data[..res.split]); qhkdf_expand(&secret_key, b"iv", &mut res.data[res.split..]); res } pub fn algorithm(&self) -> &aead::Algorithm { self.alg } pub fn write_nonce(&self, number: u32, out: &mut [u8]) { debug_assert_eq!(out.len(), self.alg.nonce_len()); let out = { let mut write = Cursor::new(out); write.put_u32_be(0); write.put_u64_be(u64::from(number)); debug_assert_eq!(write.remaining(), 0); write.into_inner() }; let iv = &self.data[self.split..]; for i in 0..self.alg.nonce_len() { out[i] ^= iv[i]; } } pub fn encrypt( &self, number: u32, ad: &[u8], in_out: &mut [u8], out_suffix_capacity: usize, ) -> QuicResult<usize> { let key = SealingKey::new(self.alg, &self.data[..self.split]) .map_err(|_| QuicError::EncryptError)?; let mut nonce_buf = [0u8; aead::MAX_TAG_LEN]; let nonce = &mut nonce_buf[..self.alg.nonce_len()]; self.write_nonce(number, nonce); aead::seal_in_place(&key, &*nonce, ad, in_out, out_suffix_capacity) .map_err(|_| QuicError::EncryptError) } pub fn decrypt<'a>( &self, number: u32, ad: &[u8], input: &'a mut [u8], ) -> QuicResult<&'a mut [u8]> { let key = OpeningKey::new(self.alg, &self.data[..self.split]) .map_err(|_| QuicError::DecryptError)?; let mut nonce_buf = [0u8; aead::MAX_TAG_LEN]; let nonce = &mut nonce_buf[..self.alg.nonce_len()]; self.write_nonce(number, nonce); aead::open_in_place(&key, &*nonce, ad, 0, input).map_err(|_| QuicError::DecryptError) } } pub fn expanded_handshake_secret(conn_id: ConnectionId, label: &[u8]) -> Vec<u8> { let prk = handshake_secret(conn_id); let mut out = vec![0u8; SHA256.output_len]; qhkdf_expand(&prk, label, &mut out); out } pub fn qhkdf_expand(key: &SigningKey, label: &[u8], out: &mut [u8]) { let mut info = Vec::with_capacity(2 + 1 + 5 + out.len()); info.put_u16_be(out.len() as u16); info.put_u8(5 + (label.len() as u8)); info.extend_from_slice(b"QUIC "); info.extend_from_slice(&label); hkdf::expand(key, &info, out); } fn handshake_secret(conn_id: ConnectionId) -> SigningKey { let key = SigningKey::new(&SHA256, HANDSHAKE_SALT); let mut buf = Vec::with_capacity(8); buf.put_slice(&conn_id); hkdf::extract(&key, &buf) } const HANDSHAKE_SALT: &[u8; 20] = b"\x9c\x10\x8f\x98\x52\x0a\x5c\x5c\x32\x96\x8e\x95\x0e\x8a\x2c\x5f\xe0\x6d\x6c\x38"; #[cfg(test)] mod tests { use types::ConnectionId; #[test] fn test_handshake_client() { let hs_cid = ConnectionId { len: 8, bytes: [ 0x83, 0x94, 0xc8, 0xf0, 0x3e, 0x51, 0x57, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ], }; let client_handshake_secret = super::expanded_handshake_secret(hs_cid, b"client hs"); let expected = b"\x83\x55\xf2\x1a\x3d\x8f\x83\xec\xb3\xd0\xf9\x71\x08\xd3\xf9\x5e\ \x0f\x65\xb4\xd8\xae\x88\xa0\x61\x1e\xe4\x9d\xb0\xb5\x23\x59\x1d"; assert_eq!(&client_handshake_secret, expected); let input = super::PacketKey::new( &super::AES_256_GCM, &super::SHA256, &client_handshake_secret, ); assert_eq!( &input.data[..input.split], b"\x3a\xd0\x54\x2c\x4a\x85\x84\x74\x00\x63\x04\x9e\x3b\x3c\xaa\xb2" ); assert_eq!( &input.data[input.split..], b"\xd1\xfd\x26\x05\x42\x75\x3a\xba\x38\x58\x9b\xad" ); } } <file_sep>use bytes::BufMut; use futures::future::{self, Future}; use futures::sync::oneshot; use futures::task; use std::collections::{HashMap, VecDeque}; use std::iter; use std::sync::{Arc, Mutex}; use super::{QuicError, QuicResult}; use codec::{BufLen, Codec}; use frame::{Frame, StreamFrame, StreamIdBlockedFrame}; use types::Side; #[derive(Clone)] pub struct Streams { inner: Arc<Mutex<Inner>>, } impl Streams { pub fn new(side: Side) -> Self { let mut open = [ OpenStreams::new(), OpenStreams::new(), OpenStreams::new(), OpenStreams::new(), ]; open[0].next = Some(0); Self { inner: Arc::new(Mutex::new(Inner { side, task: None, streams: HashMap::new(), open, control: VecDeque::new(), send_queue: VecDeque::new(), })), } } pub fn set_task(&mut self, task: task::Task) { let mut me = self.inner.lock().unwrap(); me.task = Some(task); } pub fn poll_send<T: BufMut>(&mut self, payload: &mut T) { let mut me = self.inner.lock().unwrap(); while let Some(frame) = me.control.pop_front() { frame.encode(payload); } while let Some((id, start, mut end)) = me.send_queue.pop_front() { if payload.remaining_mut() < 16 { me.send_queue.push_front((id, start, end)); break; } let mut frame = StreamFrame { id, fin: false, offset: start as u64, len: Some((end - start) as u64), data: Vec::new(), }; let len = end - start; if len > payload.remaining_mut() { let pivot = start + payload.remaining_mut() - frame.buf_len(); me.send_queue.push_front((id, pivot, end)); end = pivot; frame.len = Some((end - start) as u64); } let mut stream = &me.streams[&id]; let offset = stream.send_offset; let (start, mut end) = (start - offset, end - offset); let slices = stream.queued.as_slices(); if start < slices.0.len() && end <= slices.0.len() { frame.data.extend(&slices.0[start..end]); } else if start < slices.0.len() { frame.data.extend(&slices.0[start..]); end -= slices.0.len(); frame.data.extend(&slices.1[..end]); } else { let (start, end) = (start - slices.0.len(), end - slices.0.len()); frame.data.extend(&slices.1[start..end]); } debug_assert_eq!(frame.len, Some((end - start) as u64)); let frame = Frame::Stream(frame); frame.encode(payload); } println!("debug : streams poll_send"); } pub fn get_stream(&self, id: u64) -> Option<StreamRef> { let me = self.inner.lock().unwrap(); if me.streams.contains_key(&id) { Some(StreamRef { inner: self.inner.clone(), id, }) } else { None } } pub fn init_send(&self, dir: Dir) -> QuicResult<StreamRef> { let mut me = self.inner.lock().unwrap(); let stype = (me.side.to_bit() + dir.to_bit()) as usize; let next = me.open[stype].next; if let Some(id) = next { me.open[stype].next = if id + 4 < me.open[stype].max { Some(id + 4) } else { None }; } next.map(|id| { me.streams.insert(id, Stream::new()); StreamRef { inner: self.inner.clone(), id, } }).ok_or_else(|| { QuicError::General(format!( "{:?} not allowed to send on stream {:?} [init send]", me.side, next )) }) } pub fn update_max_id(&mut self, id: u64) { let mut me = self.inner.lock().unwrap(); me.open[(id % 4) as usize].max = id; } pub fn received(&mut self, frame: &StreamFrame) -> QuicResult<()> { let mut me = self.inner.lock().unwrap(); let id = frame.id; if Dir::from_id(id) == Dir::Uni && Side::from_id(id) == me.side { return Err(QuicError::General(format!( "{:?} not allowed to receive on stream {:?} [direction]", me.side, id ))); } if !me.streams.contains_key(&id) { let stype = (id % 4) as usize; if let Some(id) = me.open[stype].next { me.open[stype].next = if id + 4 <= me.open[stype].max { Some(id + 4) } else { None }; } else { return Err(QuicError::General(format!( "{:?} not allowed to receive on stream {:?} [limited]", me.side, id ))); } } let stream = me.streams.entry(id).or_insert_with(Stream::new); let offset = frame.offset as usize; let expected = stream.recv_offset + stream.received.len(); if offset == expected { stream.received.extend(&frame.data); } else if offset > expected { stream .received .extend(iter::repeat(0).take(offset - expected)); stream.received.extend(&frame.data); } else { return Err(QuicError::General(format!( "unhandled receive: {:?} {:?} {:?}", frame.offset, frame.len, expected ))); } Ok(()) } pub fn request_stream(self, id: u64) -> Box<Future<Item = Streams, Error = QuicError>> { let consumer = { let mut me = self.inner.lock().unwrap(); let consumer = { let open = me.open.get_mut((id % 4) as usize).unwrap(); if id > open.max { let (p, c) = oneshot::channel::<u64>(); open.updates.push(p); Some(c) } else { None } }; if consumer.is_some() { me.control .push_back(Frame::StreamIdBlocked(StreamIdBlockedFrame(id))); if let Some(ref mut task) = me.task { task.notify(); } } consumer }; match consumer { Some(c) => Box::new( c.map(|_| self) .map_err(|_| QuicError::General("StreamIdBlocked future canceled".into())), ), None => Box::new(future::ok(self)), } } } pub struct StreamRef { inner: Arc<Mutex<Inner>>, pub id: u64, } impl StreamRef { pub fn send(&self, buf: &[u8]) -> QuicResult<()> { if buf.is_empty() { return Ok(()); } let mut me = self.inner.lock().unwrap(); if Dir::from_id(self.id) == Dir::Uni && Side::from_id(self.id) != me.side { return Err(QuicError::General(format!( "{:?} not allowed to send on stream {:?} [send]", me.side, self.id ))); } let (start, end) = { let stream = me.streams.get_mut(&self.id).unwrap(); let start = stream.send_offset + stream.queued.len(); stream.queued.extend(buf); (start, start + buf.len()) }; me.send_queue.push_back((self.id, start, end)); Ok(()) } pub fn received(&self) -> QuicResult<Vec<u8>> { let mut me = self.inner.lock().unwrap(); if Dir::from_id(self.id) == Dir::Uni && Side::from_id(self.id) == me.side { return Err(QuicError::General(format!( "{:?} not allowed to receive on stream {:?}", me.side, self.id ))); } let stream = me.streams.get_mut(&self.id).unwrap(); let vec = stream.received.drain(..).collect::<Vec<u8>>(); stream.recv_offset += vec.len(); Ok(vec) } } struct Inner { side: Side, task: Option<task::Task>, streams: HashMap<u64, Stream>, open: [OpenStreams; 4], control: VecDeque<Frame>, send_queue: VecDeque<(u64, usize, usize)>, } #[derive(Default)] struct Stream { send_offset: usize, recv_offset: usize, queued: VecDeque<u8>, received: VecDeque<u8>, } impl Stream { fn new() -> Self { Self { ..Default::default() } } } #[derive(Debug)] struct OpenStreams { next: Option<u64>, max: u64, updates: Vec<oneshot::Sender<u64>>, } impl OpenStreams { fn new() -> Self { Self { next: None, max: 0, updates: Vec::new(), } } } #[derive(Clone, Copy, Debug, PartialEq)] pub enum Dir { Bidi, Uni, } impl Dir { fn from_id(id: u64) -> Self { if id & 2 == 2 { Dir::Uni } else { Dir::Bidi } } fn to_bit(&self) -> u64 { match self { Dir::Bidi => 0, Dir::Uni => 2, } } } <file_sep># Ninn This is a work-in-progress implementation of the nQUIC draft, based on Quinn. <file_sep>use bytes::{Buf, BufMut}; use super::QuicResult; use codec::{BufLen, Codec, VarLen}; use types::{ConnectionId, GENERATED_CID_LENGTH}; use rand::{thread_rng, Rng}; use std::io::Cursor; pub struct PartialDecode<'a> { pub header: Header, pub header_len: usize, pub buf: &'a mut [u8], } impl<'a> PartialDecode<'a> { pub fn new(buf: &'a mut [u8]) -> QuicResult<Self> { let (header, header_len) = { let mut read = Cursor::new(&buf); let header = Header::decode(&mut read)?; (header, read.position() as usize) }; Ok(Self { header, header_len, buf, }) } pub fn dst_cid(&self) -> ConnectionId { self.header.dst_cid() } } #[derive(Debug, PartialEq)] pub enum Header { Long { ptype: LongType, version: u32, dst_cid: ConnectionId, src_cid: ConnectionId, len: u64, number: u32, }, Short { key_phase: bool, ptype: ShortType, dst_cid: ConnectionId, number: u32, }, Negotiation { dst_cid: ConnectionId, src_cid: ConnectionId, supported_versions: Vec<u32>, }, } impl Header { pub fn ptype(&self) -> Option<LongType> { match *self { Header::Long { ptype, .. } => Some(ptype), Header::Short { .. } => None, Header::Negotiation { .. } => None, } } fn dst_cid(&self) -> ConnectionId { match *self { Header::Long { dst_cid, .. } => dst_cid, Header::Short { dst_cid, .. } => dst_cid, Header::Negotiation { dst_cid, .. } => dst_cid, } } } impl BufLen for Header { fn buf_len(&self) -> usize { match self { Header::Long { dst_cid, src_cid, .. } => 12 + (dst_cid.len as usize + src_cid.len as usize), Header::Short { ptype, dst_cid, .. } => 1 + (dst_cid.len as usize) + ptype.buf_len(), Header::Negotiation { dst_cid, src_cid, supported_versions, } => 6 + (dst_cid.len as usize + src_cid.len as usize) + 4 * supported_versions.len(), } } } impl Codec for Header { fn encode<T: BufMut>(&self, buf: &mut T) { match *self { Header::Long { ptype, version, dst_cid, src_cid, len, number, } => { buf.put_u8(128 | ptype.to_byte()); buf.put_u32_be(version); buf.put_u8((dst_cid.cil() << 4) | src_cid.cil()); buf.put_slice(&dst_cid); buf.put_slice(&src_cid); debug_assert!(len < 16383); buf.put_u16_be((len | 16384) as u16); buf.put_u32_be(number); } Header::Short { key_phase, ptype, dst_cid, number, } => { let key_phase_bit = if key_phase { 0x40 } else { 0 }; buf.put_u8(key_phase_bit | 0x20 | 0x10 | ptype.to_byte()); buf.put_slice(&dst_cid); match ptype { ShortType::One => buf.put_u8(number as u8), ShortType::Two => buf.put_u16_be(number as u16), ShortType::Four => buf.put_u32_be(number as u32), }; } Header::Negotiation { dst_cid, src_cid, ref supported_versions, } => { buf.put_u8(thread_rng().gen::<u8>() | 128); buf.put_u32_be(0); buf.put_u8((dst_cid.cil() << 4) | src_cid.cil()); buf.put_slice(&dst_cid); buf.put_slice(&src_cid); for v in supported_versions { buf.put_u32_be(*v); } } } } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let first = buf.get_u8(); if first & 128 == 128 { let version = buf.get_u32_be(); let cils = buf.get_u8(); let (dst_cid, src_cid, used) = { let (mut dcil, mut scil) = ((cils >> 4) as usize, (cils & 15) as usize); if dcil > 0 { dcil += 3; } if scil > 0 { scil += 3; } let bytes = buf.bytes(); let dst_cid = ConnectionId::new(&bytes[..dcil]); let src_cid = ConnectionId::new(&bytes[dcil..dcil + scil]); (dst_cid, src_cid, dcil + scil) }; buf.advance(used); if version == 0 { let mut supported_versions = vec![]; while buf.has_remaining() { supported_versions.push(buf.get_u32_be()); } Ok(Header::Negotiation { dst_cid, src_cid, supported_versions, }) } else { Ok(Header::Long { ptype: LongType::from_byte(first ^ 128), version, dst_cid, src_cid, len: VarLen::decode(buf)?.0, number: buf.get_u32_be(), }) } } else { let key_phase = first & 0x40 == 0x40; let dst_cid = { let bytes = buf.bytes(); ConnectionId::new(&bytes[..GENERATED_CID_LENGTH as usize]) }; buf.advance(GENERATED_CID_LENGTH as usize); let ptype = ShortType::from_byte(first & 3); let number = match ptype { ShortType::One => u32::from(buf.get_u8()), ShortType::Two => u32::from(buf.get_u16_be()), ShortType::Four => buf.get_u32_be(), }; Ok(Header::Short { key_phase, ptype, dst_cid, number, }) } } } #[derive(Clone, Debug, PartialEq)] pub enum LongType { Initial = 0x7f, Retry = 0x7e, Handshake = 0x7d, Protected = 0x7c, } impl Copy for LongType {} impl LongType { pub fn to_byte(&self) -> u8 { use self::LongType::*; match self { Initial => 0x7f, Retry => 0x7e, Handshake => 0x7d, Protected => 0x7c, } } pub fn from_byte(v: u8) -> Self { use self::LongType::*; match v { 0x7f => Initial, 0x7e => Retry, 0x7d => Handshake, 0x7c => Protected, _ => panic!("invalid long packet type {}", v), } } } #[derive(Clone, Debug, PartialEq)] pub enum ShortType { One = 0x0, Two = 0x1, Four = 0x2, } impl Copy for ShortType {} impl BufLen for ShortType { fn buf_len(&self) -> usize { use self::ShortType::*; match self { One => 1, Two => 2, Four => 4, } } } impl ShortType { pub fn to_byte(&self) -> u8 { use self::ShortType::*; match self { One => 0, Two => 1, Four => 2, } } pub fn from_byte(v: u8) -> Self { use self::ShortType::*; match v { 0 => One, 1 => Two, 2 => Four, _ => panic!("invalid short packet type {}", v), } } } #[cfg(test)] mod tests { use hex; use codec::Codec; use types::ConnectionId; use std::io::Cursor; #[test] fn test_short_roundtrip() { let con : [u8; 8] = [ 0x38, 0xa7, 0xe6, 0x55, 0xbf, 0x62, 0xf5, 0xf7 ]; let header = super::Header::Short { key_phase: false, ptype: super::ShortType::Two, dst_cid: ConnectionId::new(&con), number: 3152957029, }; let mut bytes = Vec::with_capacity(64); header.encode(&mut bytes); println!("encoded : {}", hex::encode(&bytes)); let mut read = Cursor::new(bytes); let decoded = super::Header::decode(&mut read).unwrap(); assert_eq!(decoded, header); } } <file_sep>use futures::future::Future; use streams::Streams; use QuicError; pub fn start(streams: Streams) -> impl Future<Item = Streams, Error = QuicError> { println!("REQUEST STREAM 2"); streams.request_stream(2) } <file_sep>[package] name = "ninn" version = "0.1.0" authors = ["<NAME> <<EMAIL>>", "<NAME> <<EMAIL>>"] description = "Futures-based nQUIC implementation" keywords = ["quic", "tokio"] categories = ["network-programming"] repository = "https://github.com/rot256/ninn" license = "MIT/Apache-2.0" [dependencies] bytes = "0.4.7" failure = "0.1" failure_derive = "0.1" futures = "0.1" hex = "0.3.2" log = "0.4" tokio = "0.1" tokio-core = "*" rand = "=0.5.0-pre.2" ring = "0.13.0-alpha" webpki = "0.18.0-alpha" webpki-roots = "0.14" lazy_static = "*" [dependencies.rustls] git = "https://github.com/ctz/rustls" branch = "jbp-tls13-draft-28" features = ["quic"] [dependencies.snow] git = "https://github.com/rot256/snow" branch = "master" [dev-dependencies] env_logger = "0.5" untrusted = "0.6" hex = "*" <file_sep>use bytes::Buf; use rand::{thread_rng, Rng}; use std::collections::VecDeque; use std::io::Cursor; use std::mem; use hex; use super::{QuicError, QuicResult, QUIC_VERSION}; use codec::Codec; use crypto::Secret; use frame::{Ack, AckFrame, CloseFrame, Frame, PaddingFrame, PathFrame, CryptoFrame}; use packet::{Header, LongType, PartialDecode, ShortType}; use parameters::TransportParameters; use streams::Streams; use handshake; use types::{ConnectionId, Side, GENERATED_CID_LENGTH}; pub struct ConnectionState<T> { side: Side, state: State, local: PeerData, remote: PeerData, dst_pn: u32, src_pn: u32, secret: Secret, prev_secret: Option<Secret>, pub streams: Streams, queue: VecDeque<Vec<u8>>, control: VecDeque<Frame>, handshake: T, pmtu: usize, } fn recover_packet_number(current : u32, pn : u32, t : ShortType) -> u32 { let mask = match t { ShortType::One => 0xffff_ff00, ShortType::Two => 0xffff_0000, ShortType::Four => 0x0000_0000, }; let new = (current & mask) | pn; let off = (mask & 0xffff_ffff) + 1; return if new < current { new + off } else { new } } impl<T> ConnectionState<T> where T: handshake::Session + handshake::QuicSide, { pub fn new(handshake: T, secret: Option<Secret>) -> Self { let mut rng = thread_rng(); let dst_cid = rng.gen(); let side = handshake.side(); let secret = if side == Side::Client { debug_assert!(secret.is_none()); Secret::Handshake(dst_cid) } else if let Some(secret) = secret { secret } else { panic!("need secret for client conn_state"); }; let local = PeerData::new(rng.gen()); let (num_recv_bidi, num_recv_uni) = ( u64::from(local.params.max_streams_bidi), u64::from(local.params.max_stream_id_uni), ); let (max_recv_bidi, max_recv_uni) = if side == Side::Client { (1 + 4 * num_recv_bidi, 3 + 4 * num_recv_uni) } else { (4 * num_recv_bidi, 1 + 4 * num_recv_uni) }; let mut streams = Streams::new(side); streams.update_max_id(max_recv_bidi); streams.update_max_id(max_recv_uni); ConnectionState { handshake, side, state: State::Start, remote: PeerData::new(dst_cid), local, src_pn: rng.gen(), dst_pn: 0, secret, prev_secret: None, streams, queue: VecDeque::new(), control: VecDeque::new(), pmtu: IPV6_MIN_MTU, } } pub fn is_handshaking(&self) -> bool { match self.state { State::Connected => false, _ => true, } } pub fn queued(&mut self) -> QuicResult<Option<&Vec<u8>>> { self.queue_packet()?; Ok(self.queue.front()) } pub fn pop_queue(&mut self) { self.queue.pop_front(); } pub fn pick_unused_cid<F>(&mut self, is_used: F) -> ConnectionId where F: Fn(ConnectionId) -> bool, { while is_used(self.local.cid) { self.local.cid = thread_rng().gen(); } self.local.cid } pub(crate) fn set_secret(&mut self, secret: Secret) { let old = mem::replace(&mut self.secret, secret); self.prev_secret = Some(old); } #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] pub fn queue_packet(&mut self) -> QuicResult<()> { let (dst_cid, src_cid) = (self.remote.cid, self.local.cid); debug_assert_eq!(src_cid.len, GENERATED_CID_LENGTH); let number = self.src_pn; self.src_pn += 1; let (ptype, new_state) = match self.state { State::Connected => (None, self.state), State::Handshaking => (Some(LongType::Handshake), self.state), State::InitialSent => (Some(LongType::Handshake), State::Handshaking), State::Start => if self.side == Side::Client { (Some(LongType::Initial), State::InitialSent) } else { (Some(LongType::Handshake), State::Handshaking) } State::ConfirmHandshake => (Some(LongType::Handshake), State::ConfirmHandshake), }; let header_len = match ptype { Some(_) => (12 + (dst_cid.len + src_cid.len) as usize), None => (3 + dst_cid.len as usize), }; let secret = if let Some(LongType::Handshake) = ptype { if let Some(ref secret @ Secret::Handshake(_)) = self.prev_secret { secret } else { &self.secret } } else { &self.secret }; println!("debug : queue packet"); println!("debug : src_pn = {}", self.src_pn); println!("debug : type = {:?}", ptype); println!("debug : secret = {:?}", secret); let key = secret.build_key(self.side); let tag_len = key.algorithm().tag_len(); let mut buf = vec![0u8; self.pmtu]; let payload_len = { let mut write = Cursor::new(&mut buf[header_len..self.pmtu - tag_len]); while let Some(frame) = self.control.pop_front() { println!("debug : control frame"); println!("debug : {:?}", frame); frame.encode(&mut write); } self.streams.poll_send(&mut write); let mut payload_len = write.position() as usize; let initial_min_size = 1200 - header_len - tag_len; if ptype == Some(LongType::Initial) && payload_len < initial_min_size { Frame::Padding(PaddingFrame(initial_min_size - payload_len)).encode(&mut write); payload_len = initial_min_size; } payload_len }; if payload_len == 0 { return Ok(()); } let header = match ptype { Some(ltype) => Header::Long { ptype: ltype, version: QUIC_VERSION, dst_cid, src_cid, len: (payload_len + tag_len) as u64, number, }, None => Header::Short { key_phase: false, ptype: ShortType::Two, dst_cid, number, }, }; println!("{:?}", header); { let mut write = Cursor::new(&mut buf[..header_len]); header.encode(&mut write); } let out_len = { let (header_buf, mut payload) = buf.split_at_mut(header_len); let mut in_out = &mut payload[..payload_len + tag_len]; key.encrypt(number, &header_buf, in_out, tag_len)? }; buf.truncate(header_len + out_len); self.queue.push_back(buf); self.state = new_state; Ok(()) } pub(crate) fn handle(&mut self, buf: &mut [u8]) -> QuicResult<()> { println!("debug : handle packet:"); println!("debug : buf = {}", hex::encode(&buf)); let pdecode = PartialDecode::new(buf)?; self.handle_partial(pdecode) } pub(crate) fn handle_partial(&mut self, partial: PartialDecode) -> QuicResult<()> { let PartialDecode { header, header_len, buf, } = partial; let key = { let secret = &self.secret; println!("debug : key = {:?}", &secret); secret.build_key(self.side.other()) }; println!("debug : state = {:?}", &self.state); println!("debug : header = {:?}", header); let payload = match header { Header::Long { number, .. } | Header::Short { number, .. } => { let (header_buf, payload_buf) = buf.split_at_mut(header_len); let number = match header { Header::Short { ptype, .. } => recover_packet_number(self.dst_pn, number, ptype), _ => number, }; let decrypted = key.decrypt(number, &header_buf, payload_buf)?; self.dst_pn = number; // implicit confirmation match self.state { State::ConfirmHandshake => { println!("debug : connection confirmed"); self.state = State::Connected; } _ => (), } let mut read = Cursor::new(decrypted); let mut payload = Vec::new(); while read.has_remaining() { let frame = Frame::decode(&mut read)?; payload.push(frame); } payload } Header::Negotiation { .. } => vec![], }; self.handle_packet(header, payload) } #[cfg_attr(feature = "cargo-clippy", allow(needless_pass_by_value))] fn handle_packet(&mut self, header: Header, payload: Vec<Frame>) -> QuicResult<()> { let (dst_cid, number) = match header { Header::Long { dst_cid, src_cid, number, .. } => match self.state { State::Start | State::InitialSent => { self.remote.cid = src_cid; (dst_cid, number) } _ => (dst_cid, number), }, Header::Short { dst_cid, number, .. } => if let State::Connected = self.state { (dst_cid, number) } else { return Err(QuicError::General(format!( "{:?} received short header in {:?} state", self.side, self.state ))); }, Header::Negotiation { .. } => { return Err(QuicError::General( "negotiation packet not handled by connections".into(), )); } }; if self.state != State::Start && dst_cid != self.local.cid { return Err(QuicError::General(format!( "invalid destination CID {:?} received (expected {:?} in state {:?})", dst_cid, self.local.cid, self.state ))); } let mut prologue = false; let mut send_ack = false; for frame in &payload { println!("debug : decoded frame:"); println!("debug : {:?}", frame); println!("debug : {:?}", header.ptype()); match frame { Frame::Crypto(f) => { match header.ptype() { Some(LongType::Initial) => { if self.side == Side::Client { return Err(QuicError::General(format!( "client received initial message" ))); }; if prologue { self.handle_handshake_message(&f.payload)?; } else { println!("debug : set prologue"); self.handshake.set_prologue(&f.payload)?; prologue = true; }; } Some(LongType::Handshake) => self.handle_handshake_message(&f.payload)?, _ => (), }; } Frame::Stream(f) => { assert!(self.state == State::Connected); send_ack = true; self.streams.received(f)?; } Frame::PathChallenge(PathFrame(token)) => { send_ack = true; self.control .push_back(Frame::PathResponse(PathFrame(*token))); } Frame::ApplicationClose(CloseFrame { code, reason }) => { return Err(QuicError::ApplicationClose(*code, reason.clone())); } Frame::ConnectionClose(CloseFrame { code, reason }) => { return Err(QuicError::ConnectionClose(*code, reason.clone())); } Frame::PathResponse(_) | Frame::Ping | Frame::StreamIdBlocked(_) => { send_ack = true; } Frame::Ack(_) | Frame::Padding(_) => {} } } if send_ack { self.control.push_back(Frame::Ack(AckFrame { largest: number, ack_delay: 0, blocks: vec![Ack::Ack(0)], })); } Ok(()) } fn handle_handshake_message(&mut self, msg : &[u8]) -> QuicResult<()> { println!("debug : handle handshake message:"); println!("debug : length = {}", msg.len()); println!("debug : msg = {}", hex::encode(msg)); let (new_msg, new_secret) = self.handshake.process_handshake_message(msg)?; // process new key material if let Some(secret) = new_secret { /* TODO mem::replace(&mut self.remote.params, params); */ let (num_send_bidi, num_send_uni) = ( u64::from(self.remote.params.max_streams_bidi), u64::from(self.remote.params.max_stream_id_uni), ); let (max_send_bidi, max_send_uni) = if self.side == Side::Server { (1 + 4 * num_send_bidi, 3 + 4 * num_send_uni) } else { (4 * num_send_bidi, 1 + 4 * num_send_uni) }; self.streams.update_max_id(max_send_bidi); self.streams.update_max_id(max_send_uni); // update secret self.set_secret(secret); // update state match self.side { Side::Client => { self.state = State::Connected; self.control.push_back(Frame::Padding(PaddingFrame(1))); // TODO : less hacky }, Side::Server => { self.state = State::ConfirmHandshake; } }; } // send new message if let Some(msg) = new_msg { assert!(self.is_handshaking()); println!("debug : send handshake message"); println!("debug : msg = {} ", hex::encode(&msg)); self.control.push_back(Frame::Crypto(CryptoFrame { offset : 0, length : msg.len() as u64, payload : msg, })); } Ok(()) } } impl ConnectionState<handshake::ClientSession> { pub(crate) fn initial(&mut self, prologue : &[u8]) -> QuicResult<()> { println!("debug : create initial handshake packet"); let msg = self.handshake.create_handshake_request(prologue)?; // push prologue frame self.control.push_back(Frame::Crypto(CryptoFrame{ offset : 0, length : prologue.len() as u64, payload : prologue.to_owned(), })); // push crypto frame debug_assert!(msg.len() < (1 << 16)); self.control.push_back(Frame::Crypto(CryptoFrame{ offset : 0, length : msg.len() as u64, payload : msg, })); Ok(()) } } pub struct PeerData { pub cid: ConnectionId, pub params: TransportParameters, } impl PeerData { pub fn new(cid: ConnectionId) -> Self { PeerData { cid, params: TransportParameters::default(), } } } #[derive(Clone, Copy, Debug, PartialEq)] enum State { Start, InitialSent, Handshaking, ConfirmHandshake, Connected, } const IPV6_MIN_MTU: usize = 1232; <file_sep>use futures::{task, Async, Future, Poll}; use super::{QuicError, QuicResult}; use conn_state::ConnectionState; use parameters::ClientTransportParameters; use streams::Streams; use handshake; use std::net::{SocketAddr, ToSocketAddrs}; use std::time::Duration; use tokio::net::UdpSocket; use tokio::prelude::future::Select; use tokio_core::reactor; pub struct Client { conn_state: ConnectionState<handshake::ClientSession>, socket: UdpSocket, buf: Vec<u8>, } impl Client { pub fn connect(server: &str, port: u16, server_static: [u8; 32], client_static: Option<[u8; 32]>) -> QuicResult<ConnectFuture> { ConnectFuture::new( Self::new(server, port, server_static, client_static)? ) } pub(crate) fn new(server: &str, port: u16, server_static: [u8; 32], client_static: Option<[u8; 32]>) -> QuicResult<Client> { let handshake = handshake::client_session( server_static, client_static, ClientTransportParameters::default().clone()); Self::with_state(server, port, ConnectionState::new(handshake, None)) } pub(crate) fn with_state( server: &str, port: u16, conn_state: ConnectionState<handshake::ClientSession>, ) -> QuicResult<Client> { let addr = (server, port).to_socket_addrs()?.next().ok_or_else(|| { QuicError::General(format!("no address found for '{}:{}'", server, port)) })?; let local = match addr { SocketAddr::V4(_) => SocketAddr::from(([0, 0, 0, 0], 0)), SocketAddr::V6(_) => SocketAddr::from(([0, 0, 0, 0, 0, 0, 0, 0], 0)), }; let socket = UdpSocket::bind(&local)?; socket.connect(&addr)?; Ok(Self { conn_state, socket, buf: vec![0u8; 65536], }) } fn poll_send(&mut self) -> Poll<(), QuicError> { if let Some(buf) = self.conn_state.queued()? { let len = try_ready!(self.socket.poll_send(&buf)); debug_assert_eq!(len, buf.len()); } self.conn_state.pop_queue(); Ok(Async::Ready(())) } } impl Future for Client { type Item = (); type Error = QuicError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.conn_state.streams.set_task(task::current()); loop { match self.poll_send() { Ok(Async::Ready(())) | Ok(Async::NotReady) => {} e @ Err(_) => try_ready!(e), } let len = try_ready!(self.socket.poll_recv(&mut self.buf)); match self.conn_state.handle(&mut self.buf[..len]) { Ok(_) => (), Err(err) => { debug!("error, failed to handle message {:?}", err); () } } } } } #[must_use = "futures do nothing unless polled"] pub struct ConnectFuture { client : Option<Client>, timeout : reactor::Timeout, } impl ConnectFuture { fn new(mut client: Client) -> QuicResult<ConnectFuture> { let core = reactor::Core::new().unwrap(); let handle = core.handle(); Ok(ConnectFuture { client : Some(client), timeout : reactor::Timeout::new( Duration::from_millis(1000), &handle ).unwrap(), }) } } impl Future for ConnectFuture { type Item = (Client, Streams); type Error = QuicError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { // poll timeout match self.timeout.poll() { Err(_) => return Err(QuicError::Timeout), Ok(Async::Ready(_)) => return Err(QuicError::Timeout), _ => (), }; // poll for connection progression let done = if let Some(ref mut client) = self.client { match client.poll() { Err(e) => { return Err(e); } _ => !client.conn_state.is_handshaking(), } } else { panic!("invalid state for ConnectFuture"); }; if done { match self.client.take() { Some(client) => { let streams = client.conn_state.streams.clone(); Ok(Async::Ready((client, streams))) } _ => panic!("invalid future state"), } } else { Ok(Async::NotReady) } } } <file_sep>pub mod client; mod frame; <file_sep>use rand::{self, Rng}; use std::fmt; use std::ops::Deref; #[derive(Clone, Eq, Hash, PartialEq)] pub struct ConnectionId { pub len: u8, pub bytes: [u8; 18], } impl Copy for ConnectionId {} impl ConnectionId { pub fn new(bytes: &[u8]) -> Self { debug_assert!(bytes.is_empty() || (bytes.len() > 3 && bytes.len() < 19)); let mut res = Self { len: bytes.len() as u8, bytes: [0; 18], }; (&mut res.bytes[..bytes.len()]).clone_from_slice(bytes); res } pub fn cil(&self) -> u8 { if self.len > 0 { self.len - 3 } else { self.len } } } impl fmt::Debug for ConnectionId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "0x")?; for b in (&self.bytes[..self.len as usize]).iter() { write!(f, "{:02x}", b)?; } Ok(()) } } impl Deref for ConnectionId { type Target = [u8]; fn deref(&self) -> &[u8] { &self.bytes[..self.len as usize] } } impl rand::distributions::Distribution<ConnectionId> for rand::distributions::Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> ConnectionId { let mut res = ConnectionId { len: GENERATED_CID_LENGTH, bytes: [0; 18], }; rng.fill_bytes(&mut res.bytes[..res.len as usize]); res } } #[derive(Clone, Debug, PartialEq)] pub enum Side { Client, Server, } impl Side { pub fn other(&self) -> Side { match self { Side::Client => Side::Server, Side::Server => Side::Client, } } pub fn from_id(id: u64) -> Self { if id & 1 == 1 { Side::Server } else { Side::Client } } pub fn to_bit(&self) -> u64 { match self { Side::Client => 0, Side::Server => 1, } } } impl Copy for Side {} pub const GENERATED_CID_LENGTH: u8 = 8; <file_sep>use bytes::{Buf, BufMut}; use super::{QuicResult, QUIC_VERSION}; use codec::Codec; #[derive(Clone, Debug, PartialEq)] pub struct ClientTransportParameters { pub initial_version: u32, pub parameters: TransportParameters, } impl Default for ClientTransportParameters { fn default() -> Self { Self { initial_version: QUIC_VERSION, parameters: TransportParameters::default(), } } } impl Codec for ClientTransportParameters { fn encode<T: BufMut>(&self, buf: &mut T) { buf.put_u32_be(self.initial_version); self.parameters.encode(buf); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { Ok(ClientTransportParameters { initial_version: buf.get_u32_be(), parameters: TransportParameters::decode(buf)?, }) } } #[derive(Clone, Debug, PartialEq)] pub struct ServerTransportParameters { pub negotiated_version: u32, pub supported_versions: Vec<u32>, pub parameters: TransportParameters, } impl Default for ServerTransportParameters { fn default() -> Self { Self { negotiated_version: QUIC_VERSION, supported_versions: vec![QUIC_VERSION], parameters: TransportParameters::default(), } } } impl Codec for ServerTransportParameters { fn encode<T: BufMut>(&self, buf: &mut T) { buf.put_u32_be(self.negotiated_version); buf.put_u8((4 * self.supported_versions.len()) as u8); for v in &self.supported_versions { buf.put_u32_be(*v); } self.parameters.encode(buf); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { Ok(ServerTransportParameters { negotiated_version: buf.get_u32_be(), supported_versions: { let mut supported_versions = vec![]; let supported_bytes = buf.get_u8() as usize; let mut sub = buf.take(supported_bytes); while sub.has_remaining() { supported_versions.push(sub.get_u32_be()); } supported_versions }, parameters: TransportParameters::decode(buf)?, }) } } impl Codec for TransportParameters { fn encode<T: BufMut>(&self, buf: &mut T) { let mut tmp = vec![]; let mut val = vec![]; tmp.put_u16_be(0); val.put_u32_be(self.max_stream_data); tmp.put_u16_be(val.len() as u16); tmp.append(&mut val); val.truncate(0); tmp.put_u16_be(1); val.put_u32_be(self.max_data); tmp.put_u16_be(val.len() as u16); tmp.append(&mut val); val.truncate(0); tmp.put_u16_be(3); val.put_u16_be(self.idle_timeout); tmp.put_u16_be(val.len() as u16); tmp.append(&mut val); val.truncate(0); if self.max_streams_bidi > 0 { tmp.put_u16_be(2); val.put_u16_be(self.max_streams_bidi); tmp.put_u16_be(val.len() as u16); tmp.append(&mut val); val.truncate(0); } if self.max_packet_size != 65527 { tmp.put_u16_be(5); val.put_u16_be(self.max_packet_size); tmp.put_u16_be(val.len() as u16); tmp.append(&mut val); val.truncate(0); } if self.ack_delay_exponent != 3 { tmp.put_u16_be(7); val.put_u8(self.ack_delay_exponent); tmp.put_u16_be(val.len() as u16); tmp.append(&mut val); val.truncate(0); } if self.max_stream_id_uni > 0 { tmp.put_u16_be(8); val.put_u16_be(self.max_stream_id_uni); tmp.put_u16_be(val.len() as u16); tmp.append(&mut val); val.truncate(0); } if let Some(token) = self.stateless_reset_token { tmp.put_u16_be(6); tmp.put_u16_be(16); tmp.extend_from_slice(&token); } buf.put_u16_be(tmp.len() as u16); buf.put_slice(&tmp); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let mut params = TransportParameters::default(); let num = buf.get_u16_be(); let mut sub = buf.take(num as usize); while sub.has_remaining() { let tag = sub.get_u16_be(); let size = sub.get_u16_be(); match tag { 0 => { debug_assert_eq!(size, 4); params.max_stream_data = sub.get_u32_be(); } 1 => { debug_assert_eq!(size, 4); params.max_data = sub.get_u32_be(); } 2 => { debug_assert_eq!(size, 2); params.max_streams_bidi = sub.get_u16_be(); } 3 => { debug_assert_eq!(size, 2); params.idle_timeout = sub.get_u16_be(); } 5 => { debug_assert_eq!(size, 2); params.max_packet_size = sub.get_u16_be(); } 6 => { debug_assert_eq!(size, 16); let mut token = [0; 16]; sub.copy_to_slice(&mut token); params.stateless_reset_token = Some(token); } 7 => { debug_assert_eq!(size, 1); params.ack_delay_exponent = sub.get_u8(); } 8 => { debug_assert_eq!(size, 2); params.max_stream_id_uni = sub.get_u16_be(); } _ => { sub.advance(usize::from(size)); } } } Ok(params) } } #[derive(Clone, Debug, PartialEq)] pub struct TransportParameters { pub max_stream_data: u32, // 0x00 pub max_data: u32, // 0x01 pub max_streams_bidi: u16, // 0x02 pub idle_timeout: u16, // 0x03 pub max_packet_size: u16, // 0x05 pub stateless_reset_token: Option<[u8; 16]>, // 0x06 pub ack_delay_exponent: u8, // 0x07 pub max_stream_id_uni: u16, // 0x08 } impl Default for TransportParameters { fn default() -> Self { Self { max_stream_data: 131_072, max_data: 1_048_576, max_streams_bidi: 4, idle_timeout: 300, max_packet_size: 65_527, stateless_reset_token: None, ack_delay_exponent: 3, max_stream_id_uni: 20, } } } #[cfg(test)] mod tests { use super::TransportParameters; use super::{ClientTransportParameters, Codec, ServerTransportParameters}; use std::fmt::Debug; use std::io::Cursor; fn round_trip<T: Codec + PartialEq + Debug>(t: T) { let buf = { let mut ret = Vec::new(); t.encode(&mut ret); ret }; let mut read = Cursor::new(&buf); assert_eq!(t, T::decode(&mut read).unwrap()); } #[test] fn test_client_transport_parameters() { round_trip(ClientTransportParameters { initial_version: 1, parameters: TransportParameters { max_stream_data: 0, max_data: 1234, idle_timeout: 26, ..Default::default() }, }); } #[test] fn test_server_transport_parameters() { round_trip(ServerTransportParameters { negotiated_version: 1, supported_versions: vec![1, 2, 3], parameters: TransportParameters { stateless_reset_token: Some([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]), ..Default::default() }, }); } #[test] fn test_ignores_unknown_transport_parameter_ids() { #[cfg_attr(rustfmt, rustfmt_skip)] let bytes = [0u8, 130, 0, 0, 0, 4, 0, 0, 64, 0, 0, 1, 0, 4, 0, 0, 128, 0, 0, 2, 0, 2, 0, 1, 0, 8, 0, 2, 0, 1, 0, 3, 0, 2, 0, 10, 255, 0, 0, 2, 255, 0, 255, 1, 0, 2, 255, 1, 255, 2, 0, 2, 255, 2, 255, 3, 0, 2, 255, 3, 255, 4, 0, 2, 255, 4, 255, 5, 0, 2, 255, 5, 255, 6, 0, 2, 255, 6, 255, 7, 0, 2, 255, 7, 255, 8, 0, 2, 255, 8, 255, 9, 0, 2, 255, 9, 255, 10, 0, 2, 255, 10, 255, 11, 0, 2, 255, 11, 255, 12, 0, 2, 255, 12, 255, 13, 0, 2, 255, 13, 255, 14, 0, 2, 255, 14, 255, 15, 0, 2, 255, 15]; let tp = TransportParameters::decode(&mut Cursor::new(bytes.as_ref())).unwrap(); assert_eq!( tp, TransportParameters { max_stream_data: 16384, max_data: 32768, max_streams_bidi: 1, idle_timeout: 10, max_packet_size: 65527, stateless_reset_token: None, ack_delay_exponent: 3, max_stream_id_uni: 1, } ); } } <file_sep>use super::{QuicError, QuicResult}; use bytes::{Buf, BufMut}; pub struct VarLen(pub u64); impl BufLen for VarLen { fn buf_len(&self) -> usize { match self.0 { v if v <= 63 => 1, v if v <= 16_383 => 2, v if v <= 1_073_741_823 => 4, v if v <= 4_611_686_018_427_387_903 => 8, v => panic!("too large for variable-length encoding: {}", v), } } } impl Codec for VarLen { fn encode<T: BufMut>(&self, buf: &mut T) { match self.buf_len() { 1 => buf.put_u8(self.0 as u8), 2 => buf.put_u16_be(self.0 as u16 | 16384), 4 => buf.put_u32_be(self.0 as u32 | 2_147_483_648), 8 => buf.put_u64_be(self.0 | 13_835_058_055_282_163_712), _ => panic!("impossible variable-length encoding"), } } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let first = buf.get_u8(); let be_val = first & 0x3f; let val = match first >> 6 { 0 => u64::from(be_val), 1 => u64::from(be_val) << 8 | u64::from(buf.get_u8()), 2 => { u64::from(be_val) << 24 | u64::from(buf.get_u8()) << 16 | u64::from(buf.get_u16_be()) } 3 => { u64::from(be_val) << 56 | u64::from(buf.get_u8()) << 48 | u64::from(buf.get_u16_be()) << 32 | u64::from(buf.get_u32_be()) } v => { return Err(QuicError::DecodeError(format!( "impossible variable length encoding: {}", v ))) } }; Ok(VarLen(val)) } } pub trait BufLen { fn buf_len(&self) -> usize; } impl<T> BufLen for Option<T> where T: BufLen, { fn buf_len(&self) -> usize { match self { Some(v) => v.buf_len(), None => 0, } } } impl<T> BufLen for Vec<T> where T: BufLen, { fn buf_len(&self) -> usize { self.iter().map(|i| i.buf_len()).sum() } } pub trait Codec: Sized { // TODO q on add sized fn encode<T: BufMut>(&self, buf: &mut T); fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self>; } #[cfg(test)] mod tests { use super::{Codec, VarLen}; use std::io::Cursor; #[test] fn test_var_len_encoding_8() { let num = 151_288_809_941_952_652; let bytes = b"\xc2\x19\x7c\x5e\xff\x14\xe8\x8c"; let mut buf = Vec::new(); VarLen(num).encode(&mut buf); assert_eq!(bytes[..], *buf); let mut read = Cursor::new(bytes); assert_eq!(VarLen::decode(&mut read).expect("Invalid VarLen").0, num); } #[test] fn test_var_len_encoding_4() { let num = 494_878_333; let bytes = b"\x9d\x7f\x3e\x7d"; let mut buf = Vec::new(); VarLen(num).encode(&mut buf); assert_eq!(bytes[..], *buf); let mut read = Cursor::new(bytes); assert_eq!(VarLen::decode(&mut read).expect("Invalid VarLen").0, num); } #[test] fn test_var_len_encoding_2() { let num = 15_293; let bytes = b"\x7b\xbd"; let mut buf = Vec::new(); VarLen(num).encode(&mut buf); assert_eq!(bytes[..], *buf); let mut read = Cursor::new(bytes); assert_eq!(VarLen::decode(&mut read).expect("Invalid VarLen").0, num); } #[test] fn test_var_len_encoding_1_short() { let num = 37; let bytes = b"\x25"; let mut buf = Vec::new(); VarLen(num).encode(&mut buf); assert_eq!(bytes[..], *buf); let mut read = Cursor::new(bytes); assert_eq!(VarLen::decode(&mut read).expect("Invalid VarLen").0, num); } } <file_sep>use bytes::{Buf, BufMut}; use codec::{BufLen, Codec, VarLen}; use std::str; use super::{QuicError, QuicResult}; const CRYPTO_FRAME_ID : u8 = 0x18; // see draft-13 #[derive(Debug, PartialEq)] pub enum Frame { Ack(AckFrame), ApplicationClose(CloseFrame), ConnectionClose(CloseFrame), Padding(PaddingFrame), PathChallenge(PathFrame), PathResponse(PathFrame), Ping, Stream(StreamFrame), StreamIdBlocked(StreamIdBlockedFrame), Crypto(CryptoFrame), } impl BufLen for Frame { fn buf_len(&self) -> usize { match self { Frame::Ack(f) => f.buf_len(), Frame::Crypto(f) => 1 + f.buf_len(), Frame::ApplicationClose(f) => 1 + f.buf_len(), Frame::ConnectionClose(f) => 1 + f.buf_len(), Frame::Padding(f) => f.buf_len(), Frame::PathChallenge(f) => 1 + f.buf_len(), Frame::PathResponse(f) => 1 + f.buf_len(), Frame::Ping => 1, Frame::Stream(f) => f.buf_len(), Frame::StreamIdBlocked(f) => 1 + f.buf_len(), } } } impl Codec for Frame { fn encode<T: BufMut>(&self, buf: &mut T) { match self { Frame::Ack(f) => f.encode(buf), Frame::ApplicationClose(f) => { buf.put_u8(0x03); f.encode(buf) } Frame::ConnectionClose(f) => { buf.put_u8(0x02); f.encode(buf) } Frame::Padding(f) => f.encode(buf), Frame::PathChallenge(f) => { buf.put_u8(0x0e); f.encode(buf) } Frame::PathResponse(f) => { buf.put_u8(0x0f); f.encode(buf) } Frame::Ping => buf.put_u8(0x07), Frame::Stream(f) => f.encode(buf), Frame::StreamIdBlocked(f) => { buf.put_u8(0x0a); f.encode(buf) } Frame::Crypto(f) => { buf.put_u8(CRYPTO_FRAME_ID); f.encode(buf) } } } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { Ok(match buf.bytes()[0] { v if v >= 0x10 && v < 0x18 => Frame::Stream(StreamFrame::decode(buf)?), 0x02 => Frame::ConnectionClose({ buf.get_u8(); CloseFrame::decode(buf)? }), 0x03 => Frame::ApplicationClose({ buf.get_u8(); CloseFrame::decode(buf)? }), 0x07 => { buf.get_u8(); Frame::Ping } 0x0a => Frame::StreamIdBlocked({ buf.get_u8(); StreamIdBlockedFrame::decode(buf)? }), CRYPTO_FRAME_ID => Frame::Crypto({ buf.get_u8(); CryptoFrame::decode(buf)? }), 0x0d => Frame::Ack(AckFrame::decode(buf)?), 0x0e => Frame::PathChallenge({ buf.get_u8(); PathFrame::decode(buf)? }), 0x0f => Frame::PathResponse({ buf.get_u8(); PathFrame::decode(buf)? }), 0 => Frame::Padding(PaddingFrame::decode(buf)?), v => { return Err(QuicError::DecodeError(format!( "unimplemented decoding for frame type {}", v ))) } }) } } #[derive(Debug, PartialEq)] pub struct StreamFrame { pub id: u64, pub fin: bool, pub offset: u64, pub len: Option<u64>, pub data: Vec<u8>, } impl BufLen for StreamFrame { fn buf_len(&self) -> usize { 1 + VarLen(self.id).buf_len() + if self.offset > 0 { VarLen(self.offset).buf_len() } else { 0 } + self.len.map(VarLen).buf_len() + self.data.len() } } impl Codec for StreamFrame { fn encode<T: BufMut>(&self, buf: &mut T) { let has_offset = if self.offset > 0 { 0x04 } else { 0 }; let has_len = if self.len.is_some() { 0x02 } else { 0 }; let is_fin = if self.fin { 0x01 } else { 0 }; buf.put_u8(0x10 | has_offset | has_len | is_fin); VarLen(self.id).encode(buf); if self.offset > 0 { VarLen(self.offset).encode(buf); } if let Some(len) = self.len { VarLen(len).encode(buf); } buf.put_slice(&self.data); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let first = buf.get_u8(); let id = VarLen::decode(buf)?.0; let offset = if first & 0x04 > 0 { VarLen::decode(buf)?.0 } else { 0 }; let rem = buf.remaining() as u64; let (len, consume) = match first & 0x02 { 0 => (None, rem), _ => { let len = VarLen::decode(buf)?.0; if len > rem { return Err( QuicError::DecodeError("length too great".to_string()) ); } (Some(len), len) } }; let mut data = vec![0u8; consume as usize]; buf.copy_to_slice(&mut data); Ok(StreamFrame { id, fin: first & 0x01 > 0, offset, len, data, }) } } #[derive(Debug, PartialEq)] pub struct CryptoFrame { pub offset : u64, pub length : u64, pub payload : Vec<u8>, } impl BufLen for CryptoFrame { fn buf_len(&self) -> usize { 1 + VarLen(self.offset).buf_len() + VarLen(self.length).buf_len() + self.payload.len() } } impl Codec for CryptoFrame { /* Flags: * has_offset : The offset should always be zero, hence can be omitted entirely */ fn encode<T: BufMut>(&self, buf: &mut T) { buf.put_u8(CRYPTO_FRAME_ID); VarLen(self.offset).encode(buf); VarLen(self.length).encode(buf); buf.put_slice(&self.payload); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { if buf.get_u8() != CRYPTO_FRAME_ID { return Err(QuicError::DecodeError("invalid frame id".to_string())); } let offset = VarLen::decode(buf)?.0; let length = VarLen::decode(buf)?.0; if length > buf.remaining() as u64 { return Err(QuicError::DecodeError("length is too great".to_string())); } // copy payload into frame let mut payload = vec![0u8; length as usize]; buf.copy_to_slice(&mut payload); Ok(CryptoFrame {offset, length, payload}) } } #[derive(Debug, PartialEq)] pub struct AckFrame { pub largest: u32, pub ack_delay: u64, pub blocks: Vec<Ack>, } impl BufLen for AckFrame { fn buf_len(&self) -> usize { 1 + VarLen(u64::from(self.largest)).buf_len() + VarLen(self.ack_delay).buf_len() + VarLen((self.blocks.len() - 1) as u64).buf_len() + self.blocks .iter() .map(|v| VarLen(v.value()).buf_len()) .sum::<usize>() } } impl Codec for AckFrame { fn encode<T: BufMut>(&self, buf: &mut T) { buf.put_u8(0x0d); VarLen(u64::from(self.largest)).encode(buf); VarLen(self.ack_delay).encode(buf); VarLen((self.blocks.len() - 1) as u64).encode(buf); for ack in &self.blocks { VarLen(ack.value()).encode(buf); } } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let _ = buf.get_u8(); let largest = VarLen::decode(buf)?.0 as u32; let ack_delay = VarLen::decode(buf)?.0; let count = VarLen::decode(buf)?.0; debug_assert_eq!(count % 2, 0); let mut blocks = vec![]; for i in 0..count + 1 { blocks.push(if i % 2 == 0 { Ack::Ack(VarLen::decode(buf)?.0) } else { Ack::Gap(VarLen::decode(buf)?.0) }); } Ok(AckFrame { largest, ack_delay, blocks, }) } } #[derive(Debug, PartialEq)] pub enum Ack { Ack(u64), Gap(u64), } impl Ack { fn value(&self) -> u64 { match *self { Ack::Ack(v) => v, Ack::Gap(v) => v, } } } #[derive(Debug, PartialEq)] pub struct CloseFrame { pub(crate) code: u16, pub(crate) reason: String, } impl BufLen for CloseFrame { fn buf_len(&self) -> usize { 2 + VarLen(self.reason.len() as u64).buf_len() + self.reason.len() } } impl Codec for CloseFrame { fn encode<T: BufMut>(&self, buf: &mut T) { buf.put_u16_be(self.code); VarLen(self.reason.len() as u64).encode(buf); buf.put_slice(self.reason.as_bytes()); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let code = buf.get_u16_be(); let len = VarLen::decode(buf)?.0 as usize; let reason = { let bytes = buf.bytes(); str::from_utf8(&bytes[..len]).unwrap() }.to_string(); buf.advance(len); Ok(CloseFrame { code, reason }) } } #[derive(Debug, PartialEq)] pub struct PathFrame(pub [u8; 8]); impl BufLen for PathFrame { fn buf_len(&self) -> usize { 8 } } impl Codec for PathFrame { fn encode<T: BufMut>(&self, buf: &mut T) { buf.put_slice(&self.0); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let mut bytes = [0; 8]; buf.copy_to_slice(&mut bytes); Ok(PathFrame(bytes)) } } #[derive(Debug, PartialEq)] pub struct StreamIdBlockedFrame(pub u64); impl BufLen for StreamIdBlockedFrame { fn buf_len(&self) -> usize { VarLen(self.0).buf_len() } } impl Codec for StreamIdBlockedFrame { fn encode<T: BufMut>(&self, buf: &mut T) { VarLen(self.0).encode(buf) } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { Ok(StreamIdBlockedFrame(VarLen::decode(buf)?.0)) } } #[derive(Debug, PartialEq)] pub struct PaddingFrame(pub usize); impl BufLen for PaddingFrame { fn buf_len(&self) -> usize { self.0 } } impl Codec for PaddingFrame { fn encode<T: BufMut>(&self, buf: &mut T) { let padding = vec![0; self.0]; buf.put_slice(&padding); } fn decode<T: Buf>(buf: &mut T) -> QuicResult<Self> { let size = buf.bytes().iter().take_while(|b| **b == 0).count(); buf.advance(size); Ok(PaddingFrame(size)) } } #[cfg(test)] mod tests { use bytes::Buf; use codec::{BufLen, Codec}; use std::io::Cursor; #[test] fn test_padding_roundtrip() { let bytes = b"\x00\x00\x00\x00\x01"; let frame = { let mut read = Cursor::new(&bytes); let frame = super::Frame::decode(&mut read).unwrap(); assert_eq!(read.bytes(), b"\x01"); frame }; assert_eq!(frame, super::Frame::Padding(super::PaddingFrame(4))); let mut buf = vec![0u8; 16]; frame.encode(&mut buf); assert_eq!(&bytes[..4], &buf[..4]); } #[test] fn test_ack_roundtrip() { let obj = super::Frame::Ack(super::AckFrame { largest: 485971334, ack_delay: 0, blocks: vec![super::Ack::Ack(0)], }); let bytes = b"\x0d\x9c\xf7\x55\x86\x00\x00\x00"; assert_eq!(obj.buf_len(), bytes.len()); let mut buf = Vec::with_capacity(64); obj.encode(&mut buf); assert_eq!(&buf, bytes); let mut read = Cursor::new(bytes); let decoded = super::Frame::decode(&mut read).unwrap(); assert_eq!(decoded, obj); } #[test] fn test_crypto_round_trip() { let payload = b"\x0d\x9c\xf7\x55\x86\x00\x00\x00"; let obj = super::Frame::Crypto(super::CryptoFrame { len : payload.len() as u16, payload : payload.to_vec(), }); let bytes = b"\x0b\x00\x08\x0d\x9c\xf7\x55\x86\x00\x00\x00"; assert_eq!(obj.buf_len(), bytes.len()); let mut buf = Vec::with_capacity(64); obj.encode(&mut buf); println!("{:?}", buf); assert_eq!(buf.len(), obj.buf_len()); let mut read = Cursor::new(bytes); let decoded = super::Frame::decode(&mut read).unwrap(); assert_eq!(decoded, obj); } }
12fe34388aae883b77eec3f170a88897de258507
[ "Markdown", "Rust", "TOML" ]
17
Rust
rot256/ninn
d00d0059959e285675828f0aad2e006e99cf5abb
55145ddb73ffa14a7a42eb3587e93fb8e14acbfc
refs/heads/main
<repo_name>AdhirajDatar/Batman<file_sep>/BATMAN/sketch.js var Engine = Matter.Engine; var Bodies = Matter.Bodies; var World = Matter.World; var engine var world var umbrella1 var drop function preload(){ walk1 = loadImage("images/WalkingFrame/walking_1.png"); } function setup(){ engine = Engine.create(); world = engine.world; createCanvas(800,800); //umbrella1 = new Umbrella(300, 300); drop = new Drop (random(0,800), 0); } function draw(){ drop.display() drop.update() } <file_sep>/BATMAN/Drops.js class Drop { constructor(x,y){ var options={ friction:0.2 } this.r = 10 this.rain = Bodies.circle(x, y,10, options); World.add(world, this.rain); } update(){ if(this.rain.position.y > height){ Matter.Body.setPosition(this.rain, {x:random(0,800),y:0}) } } display(){ fill("white"); ellipseMode(RADIUS); ellipse(this.rain.position.x,this.rain.position.y,this.r,this.r); } }<file_sep>/BATMAN/Umbrella.js class Umbrella{ constructor(x,y){ var options={ isStatic:true } this.umbrellaImg = loadImage("images/Walking Frame/ walking_1.png") this.umbrellaBody = Bodies.circle(x, y,100, 100,options); this.h = 100; this.w = 100 World.add(world, this.umbrellaBody); } display(){ var pos = this.umbrellaBody.position image(this.umbrellaImg, pos.x, pos.y, this.w, this.h) } }
5dd9ca2acb31dc9bd6f8c8f1ab61f1ee27e759ee
[ "JavaScript" ]
3
JavaScript
AdhirajDatar/Batman
9ff6671f529a73ae5b96aa2cd8c3ee3eaf0b2bf2
1bf40d26f2f449c3d33fda7136e2c6385e3a84da
refs/heads/master
<repo_name>l2l-v2/vessel-enterprise-rb-service<file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/security/L2LUserGroupManagerImpl.java package com.l2l.enterprise.vessel.extension.activiti.security; import com.l2l.enterprise.vessel.security.SecurityUtils; import org.activiti.runtime.api.identity.UserGroupManager; import org.springframework.stereotype.Component; import java.util.List; @Component public class L2LUserGroupManagerImpl implements UserGroupManager { @Override public List<String> getUserGroups(String s) { return SecurityUtils.getUserGroups(s); } @Override public List<String> getUserRoles(String s) { return SecurityUtils.getUserRoles(s); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/agenda/TriggerAnnotationOutgoingOperation.java package com.l2l.enterprise.vessel.extension.activiti.agenda; import org.activiti.engine.impl.agenda.AbstractOperation; public class TriggerAnnotationOutgoingOperation extends AbstractOperation { @Override public void run() { } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/domain/AcquireProcessBusinessInformationMsg.java package com.l2l.enterprise.vessel.domain; import java.io.Serializable; import java.util.*; public class AcquireProcessBusinessInformationMsg extends MsgImpl implements Serializable { private Map<String,Object> processBusinessInformation = new HashMap<>(); private Map<String,Map<String,Object>> vidTopbi = new HashMap<>(); public Map<String, Object> getProcessBusinessInformation() { return processBusinessInformation; } public long getCurTime() { return curTime; } private long curTime; public void updatePBI(String key,Object value){ processBusinessInformation.put(key,value); } public void updatePBI(Map<String,Object> vMap){ processBusinessInformation.putAll(vMap); } public void setCurTime() { this.curTime = new Date().getTime(); } public AcquireProcessBusinessInformationMsg() { super(); setCurTime(); } public AcquireProcessBusinessInformationMsg(List<String> pids, String connectorType, String topic, String scenario,Map<String,Map<String,Object>> vidTopbi) { super(pids, connectorType, topic, scenario); this.processBusinessInformation = processBusinessInformation; this.vidTopbi = vidTopbi; setCurTime(); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/connector/channel/AnnotationIntegrationRequestSender.java package com.l2l.enterprise.vessel.extension.activiti.connector.channel; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationIntegrationRequestImpl; import org.activiti.cloud.services.events.configuration.RuntimeBundleProperties; import org.activiti.cloud.services.events.converter.RuntimeBundleInfoAppender; import org.activiti.runtime.api.event.impl.CloudIntegrationRequestedImpl; import org.activiti.runtime.api.model.IntegrationRequest; import org.springframework.cloud.stream.binding.BinderAwareChannelResolver; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; import org.springframework.transaction.event.TransactionPhase; import org.springframework.transaction.event.TransactionalEventListener; @Component public class AnnotationIntegrationRequestSender { protected static final String CONNECTOR_TYPE = "connectorType"; private final RuntimeBundleProperties runtimeBundleProperties; private final MessageChannel auditProducer; private final BinderAwareChannelResolver resolver; private final RuntimeBundleInfoAppender runtimeBundleInfoAppender; public AnnotationIntegrationRequestSender(RuntimeBundleProperties runtimeBundleProperties, MessageChannel auditProducer, BinderAwareChannelResolver resolver, RuntimeBundleInfoAppender runtimeBundleInfoAppender) { this.runtimeBundleProperties = runtimeBundleProperties; this.auditProducer = auditProducer; this.resolver = resolver; this.runtimeBundleInfoAppender = runtimeBundleInfoAppender; } @TransactionalEventListener( phase = TransactionPhase.AFTER_COMMIT ) public void sendIntegrationRequest(AnnotationIntegrationRequestImpl event) { if(event instanceof AnnotationIntegrationRequestImpl){ Message<AnnotationIntegrationRequestImpl> annotationIntegrationRequestMessage = MessageBuilder.withPayload(event).setHeader("connectorType", ((AnnotationIntegrationRequestImpl) event).getAnnotationIntergrationContext().getConnectorType()).build(); this.resolver.resolveDestination(((AnnotationIntegrationRequestImpl) event).getAnnotationIntergrationContext().getConnectorType()).send(annotationIntegrationRequestMessage); this.sendAuditEvent(event); }else { this.resolver.resolveDestination(event.getIntegrationContext().getConnectorType()).send(this.buildIntegrationRequestMessage(event)); this.sendAuditEvent(event); } } private void sendAuditEvent(IntegrationRequest integrationRequest) { if (this.runtimeBundleProperties.getEventsProperties().isIntegrationAuditEventsEnabled()) { CloudIntegrationRequestedImpl integrationRequested = new CloudIntegrationRequestedImpl(integrationRequest.getIntegrationContext()); this.runtimeBundleInfoAppender.appendRuntimeBundleInfoTo(integrationRequested); this.auditProducer.send(MessageBuilder.withPayload(integrationRequested).build()); } } private Message<IntegrationRequest> buildIntegrationRequestMessage(IntegrationRequest event) { return MessageBuilder.withPayload(event).setHeader("connectorType", event.getIntegrationContext().getConnectorType()).build(); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/web/rest/package-info.java /** * Spring MVC REST controllers. */ package com.l2l.enterprise.vessel.web.rest; <file_sep>/src/main/java/com/l2l/enterprise/vessel/domain/VesselShadow.java package com.l2l.enterprise.vessel.domain; import java.util.ArrayList; import java.util.List; public class VesselShadow { private String id; // vid private double longitude; private double latitude; private double velocity; private String timeStamp; private List<Destination> destinations; private String status; private String startTime; private int stepIndex; public String getId() { return id; } public void setId(String id) { this.id = id; } public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public double getVelocity() { return velocity; } public void setVelocity(double velocity) { this.velocity = velocity; } public String getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } public List<Destination> getDestinations() { return destinations; } public void setDestinations(List<Destination> destinations) { this.destinations = destinations; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getStartTime() { return startTime; } public void setStartTime(String startTime) { this.startTime = startTime; } public int getStepIndex() { return stepIndex; } public void setStepIndex(int stepIndex) { this.stepIndex = stepIndex; } public List<Destination> getRemainingDestinations(){ List<Destination> dlist = new ArrayList<Destination>(); for(int i = 0 ; i < destinations.size(); i++){ if(i >= stepIndex){ Destination d = destinations.get(i); // if(i == stepIndex) { // if ("Anchoring".equals(status) || "Docking".equals(status)) { // dlist.add(destinations.get(stepIndex)); // } // } dlist.add(d); } } return dlist; } public void updateState(double longitude , double latitude , double velocity , String timeStamp ){ this.longitude = longitude; this.latitude =latitude; this.velocity = velocity; this.timeStamp = timeStamp; } } <file_sep>/src/test/java/com/l2l/enterprise/vessel/domain/DestinationTest.java package com.l2l.enterprise.vessel.domain; import org.junit.Test; import static org.junit.Assert.*; public class DestinationTest { @Test public void getName() throws Exception { Destination d = new Destination("name","estiAnchorTime","estiArrivalTime","estiDepartureTime"); System.out.println(d.toString()); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/eventGateway/EventDispatcher.java package com.l2l.enterprise.vessel.eventGateway; import com.amazonaws.services.iot.client.AWSIotMessage; import com.amazonaws.services.iot.client.AWSIotQos; import com.amazonaws.services.iot.client.AWSIotTopic; import com.fasterxml.jackson.databind.ObjectMapper; import com.l2l.enterprise.vessel.extension.activiti.annotation.MsgAnnotation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.io.IOException; import java.util.List; import java.util.Map; @SuppressWarnings("all") public class EventDispatcher extends AWSIotTopic { private Logger logger = LoggerFactory.getLogger(this.getClass()); private static ObjectMapper objectMapper = new ObjectMapper(); private EventHandler eventHandler; private Map<String, List<MsgAnnotation>> msgAnnoationMap; public void setMsgAnnoationMap(Map<String, List<MsgAnnotation>> msgAnnoationMap) { this.msgAnnoationMap = msgAnnoationMap; } public EventDispatcher(String topic, AWSIotQos qos) { super(topic, qos); } public void setEventHandler(EventHandler eventHandler){ this.eventHandler = eventHandler; } @Autowired private MsgMatch msgMatch; @Override public void onMessage(AWSIotMessage message) { String receivedTopic = message.getTopic(); // if(this.msgAnnoationMap == null){ // setMsgAnnoationMap(msgMatch.initMsgAnnotationMap()); // } // if(this.msgAnnoationMap.containsKey(receivedTopic)){ // // } try { if(receivedTopic.equals("$aws/things/V413362260/shadow/update/accepted")){ updateShadowHandler(message); } if(receivedTopic.equals("IoT/V413362260/status")){ changeStatusHandler(message); } } catch (IOException e) { e.printStackTrace(); } } public void updateShadowHandler(AWSIotMessage message) throws IOException { //TODO:update vessel shadow and forward shadow to Monitor this.eventHandler.vesselShadowForwarding(message); } public void changeStatusHandler(AWSIotMessage message) throws IOException { //TODO: report the signal of reaching port to process engine this.eventHandler.changeStatus(message); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/eventGateway/THMsgHandler.java package com.l2l.enterprise.vessel.eventGateway; import com.l2l.enterprise.vessel.domain.Destination; import com.l2l.enterprise.vessel.domain.THMsg; import com.l2l.enterprise.vessel.extension.activiti.annotation.MsgAnnotation; import com.l2l.enterprise.vessel.extension.activiti.boot.L2LProcessEngineConfiguration; import com.sun.javafx.collections.MappingChange; import org.activiti.engine.RuntimeService; import org.activiti.engine.runtime.ProcessInstance; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.binding.BinderAwareChannelResolver; import org.springframework.stereotype.Component; import java.util.*; @Component public class THMsgHandler implements MsgEventHandler{ private static final Logger LOGGER = LoggerFactory.getLogger(THMsgHandler.class); private final MsgMatch msgMatch; private final BinderAwareChannelResolver binderAwareChannelResolver; private final VidPidRegistry vidPidRegistry; private final L2LProcessEngineConfiguration l2LProcessEngineConfiguration; public THMsgHandler(MsgMatch msgMatch, BinderAwareChannelResolver binderAwareChannelResolver, VidPidRegistry vidPidRegistry, L2LProcessEngineConfiguration l2LProcessEngineConfiguration) { this.msgMatch = msgMatch; this.binderAwareChannelResolver = binderAwareChannelResolver; this.vidPidRegistry = vidPidRegistry; this.l2LProcessEngineConfiguration = l2LProcessEngineConfiguration; } public void handle(THMsg thMsg){ if(thMsg.getScenario().equals("coldchain")){ scenarioHandlerForColdchain(thMsg); }//可能会有别的场景 } public void scenarioHandlerForColdchain(THMsg thMsg){ if(thMsg.getTopic().equals("temperatureAndHumidity")) { topicHandlerForTH(thMsg); } } @Autowired MsgAnnotationUtil msgAnnotationUtil; public void topicHandlerForTH(THMsg thMsg){ List<MsgAnnotation> mmp = msgAnnotationUtil.getMmp(thMsg.getTopic()); // testProcessRuntime.processInstances(null); RuntimeService runtimeService = l2LProcessEngineConfiguration.getRuntimeService(); for(MsgAnnotation msgAnnotation : mmp){ List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().processDefinitionId(msgAnnotation.getProcessDefinitionId()).list(); for(ProcessInstance processInstance :processInstances){ String vid = vidPidRegistry.findRegisteredVidBypId(processInstance.getId()); if(vid != null ){ for(Map.Entry<String, THMsg.TandH> entry : thMsg.getVidToTandH().entrySet()){ if(entry.getKey().equals(vid)){ float temperature = entry.getValue().getTemperature(); float humidity = entry.getValue().getHumidity(); float ptemperature = (float) runtimeService.getVariable(processInstance.getId(),"temperature"); float phumidity = (float) runtimeService.getVariable(processInstance.getId(),"humidity"); if(((temperature/ptemperature) < 0.5 || (temperature/ptemperature) > 2.0 ) && ((humidity/phumidity) <0.5 || (humidity/phumidity) > 2.0)){ LOGGER.info(vid + "bad temperature and humidity"); } } } } } } } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/domain/MsgImpl.java package com.l2l.enterprise.vessel.domain; import java.util.List; public class MsgImpl implements Msg { private List<String> pids; private String connectorType; private String topic; private String scenario; public MsgImpl(){} public MsgImpl(List<String> pids, String connectorType, String topic, String scenario) { this.pids = pids; this.connectorType = connectorType; this.topic = topic; this.scenario = scenario; } public List<String> getPids() { return pids; } public void setPids(List<String> pids) { this.pids = pids; } public void setConnectorType(String connectorType) { this.connectorType = connectorType; } public String getTopic() { return topic; } public void setTopic(String topic) { this.topic = topic; } public String getScenario() { return scenario; } public void setScenario(String scenario) { this.scenario = scenario; } @Override public String getConnectorType() { return null; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/domain/IoTSetting.java package com.l2l.enterprise.vessel.domain; public class IoTSetting { private String id; private String defaultTopic; private String customTopic; public IoTSetting(String id, String defaultTopic, String customTopic) { this.id = id; this.defaultTopic = defaultTopic; this.customTopic = customTopic; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDefaultTopic() { return defaultTopic; } public void setDefaultTopic(String defaultTopic) { this.defaultTopic = defaultTopic; } public String getCustomTopic() { return customTopic; } public void setCustomTopic(String customTopic) { this.customTopic = customTopic; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/agenda/L2LActivitiEngineAgendaFactory.java package com.l2l.enterprise.vessel.extension.activiti.agenda; import org.activiti.engine.ActivitiEngineAgenda; import org.activiti.engine.ActivitiEngineAgendaFactory; import org.activiti.engine.impl.interceptor.CommandContext; public class L2LActivitiEngineAgendaFactory implements ActivitiEngineAgendaFactory { public L2LActivitiEngineAgendaFactory() { } @Override public ActivitiEngineAgenda createAgenda(CommandContext commandContext) { return new L2LActivitiEngineAgenda(commandContext); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/annotation/DefaultServiceTaskConnector.java package com.l2l.enterprise.vessel.extension.activiti.annotation; import org.activiti.runtime.api.connector.Connector; import org.activiti.runtime.api.model.IntegrationContext; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; @Service("defaultServiceTaskConnector") public class DefaultServiceTaskConnector implements Connector { @Override public IntegrationContext execute(IntegrationContext integrationContext) { System.out.println("execute service task..."); return integrationContext; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/boot/AbstractProcessEngineConfiguration.java package com.l2l.enterprise.vessel.extension.activiti.boot; import org.activiti.engine.*; import org.activiti.engine.impl.persistence.entity.integration.IntegrationContextManager; import org.activiti.engine.integration.IntegrationContextService; import org.activiti.spring.ProcessEngineFactoryBean; import org.activiti.spring.SpringAsyncExecutor; import org.activiti.spring.SpringProcessEngineConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationEventPublisher; import org.springframework.core.io.Resource; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class AbstractProcessEngineConfiguration { private static final Logger logger = LoggerFactory.getLogger(org.activiti.spring.boot.AbstractProcessEngineConfiguration.class); public AbstractProcessEngineConfiguration() { } public ProcessEngineFactoryBean l2LProcessEngineBean(L2LProcessEngineConfiguration configuration) { ProcessEngineFactoryBean processEngineFactoryBean = new ProcessEngineFactoryBean(); processEngineFactoryBean.setProcessEngineConfiguration(configuration); return processEngineFactoryBean; } public L2LProcessEngineConfiguration processEngineConfigurationBean(ApplicationEventPublisher eventPublisher, Resource[] processDefinitions, DataSource dataSource, PlatformTransactionManager transactionManager, SpringAsyncExecutor springAsyncExecutor) throws IOException { L2LProcessEngineConfiguration engine = new L2LProcessEngineConfiguration(); engine.setEventPublisher(eventPublisher); if (processDefinitions != null && processDefinitions.length > 0) { engine.setDeploymentResources(processDefinitions); } engine.setDataSource(dataSource); engine.setTransactionManager(transactionManager); if (null != springAsyncExecutor) { engine.setAsyncExecutor(springAsyncExecutor); } return engine; } public List<Resource> discoverProcessDefinitionResources(ResourcePatternResolver applicationContext, String prefix, List<String> suffixes, boolean checkPDs) throws IOException { if (!checkPDs) { return new ArrayList(); } else { List<Resource> result = new ArrayList(); Iterator var6 = suffixes.iterator(); while(true) { Resource[] resources; do { do { if (!var6.hasNext()) { if (result.isEmpty()) { logger.info(String.format("No process definitions were found for autodeployment")); } return result; } String suffix = (String)var6.next(); String path = prefix + suffix; resources = applicationContext.getResources(path); } while(resources == null); } while(resources.length <= 0); Resource[] var10 = resources; int var11 = resources.length; for(int var12 = 0; var12 < var11; ++var12) { Resource resource = var10[var12]; result.add(resource); } } } } public RuntimeService runtimeServiceBean(ProcessEngine processEngine) { return processEngine.getRuntimeService(); } public RepositoryService repositoryServiceBean(ProcessEngine processEngine) { return processEngine.getRepositoryService(); } public TaskService taskServiceBean(ProcessEngine processEngine) { return processEngine.getTaskService(); } public HistoryService historyServiceBean(ProcessEngine processEngine) { return processEngine.getHistoryService(); } public ManagementService managementServiceBeanBean(ProcessEngine processEngine) { return processEngine.getManagementService(); } public IntegrationContextManager integrationContextManagerBean(ProcessEngine processEngine) { return processEngine.getProcessEngineConfiguration().getIntegrationContextManager(); } public IntegrationContextService integrationContextServiceBean(ProcessEngine processEngine) { return processEngine.getProcessEngineConfiguration().getIntegrationContextService(); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/form/FormDefinition.java package com.l2l.enterprise.vessel.extension.activiti.form; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @JsonInclude(JsonInclude.Include.NON_NULL) public class FormDefinition implements Serializable { private static final long serialVersionUID = 1L; protected List<FormField> fields = new ArrayList<FormField>(); public FormDefinition() { } public List<FormField> getFields() { return this.fields; } public void setFields(List<FormField> fields) { this.fields = fields; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/parser/L2LServiceTaskXMLConverter.java package com.l2l.enterprise.vessel.extension.activiti.parser; import org.activiti.bpmn.converter.ServiceTaskXMLConverter; import org.activiti.bpmn.converter.util.BpmnXMLUtil; import org.activiti.bpmn.model.*; import org.apache.commons.lang3.StringUtils; import javax.xml.stream.XMLStreamReader; import java.util.Arrays; import java.util.List; /** * Customize the ServiceTaskXMLConverter to parse extensive attributes , like "annotation". * @author bqzhu */ public class L2LServiceTaskXMLConverter extends ServiceTaskXMLConverter { protected static final List<ExtensionAttribute> defaultElementAttributes = Arrays.asList( new ExtensionAttribute("http://www.l2l.com" , "l2l:annotation") ); protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { ServiceTask serviceTask = new ServiceTask(); BpmnXMLUtil.addXMLLocation(serviceTask, xtr); if (StringUtils.isNotEmpty(xtr.getAttributeValue("http://activiti.org/bpmn", "class"))) { serviceTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_CLASS); serviceTask.setImplementation(xtr.getAttributeValue("http://activiti.org/bpmn", "class")); } else if (StringUtils.isNotEmpty(xtr.getAttributeValue("http://activiti.org/bpmn", "expression"))) { serviceTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_EXPRESSION); serviceTask.setImplementation(xtr.getAttributeValue("http://activiti.org/bpmn", "expression")); } else if (StringUtils.isNotEmpty(xtr.getAttributeValue("http://activiti.org/bpmn", "delegateExpression"))) { serviceTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_DELEGATEEXPRESSION); serviceTask.setImplementation(xtr.getAttributeValue("http://activiti.org/bpmn", "delegateExpression")); } else if ("##WebService".equals(xtr.getAttributeValue((String)null, "implementation"))) { serviceTask.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_WEBSERVICE); serviceTask.setOperationRef(this.parseOperationRef(xtr.getAttributeValue((String)null, "operationRef"), model)); } else { serviceTask.setImplementation(xtr.getAttributeValue((String)null, "implementation")); } serviceTask.setResultVariableName(xtr.getAttributeValue("http://activiti.org/bpmn", "resultVariableName")); if (StringUtils.isEmpty(serviceTask.getResultVariableName())) { serviceTask.setResultVariableName(xtr.getAttributeValue("http://activiti.org/bpmn", "resultVariable")); } serviceTask.setType(xtr.getAttributeValue("http://activiti.org/bpmn", "type")); serviceTask.setExtensionId(xtr.getAttributeValue("http://activiti.org/bpmn", "extensionId")); if (StringUtils.isNotEmpty(xtr.getAttributeValue("http://activiti.org/bpmn", "skipExpression"))) { serviceTask.setSkipExpression(xtr.getAttributeValue("http://activiti.org/bpmn", "skipExpression")); } BpmnXMLUtil.addCustomAttributes(xtr , serviceTask , defaultElementAttributes); this.parseChildElements(this.getXMLElementName(), serviceTask, model, xtr); return serviceTask; } protected String getXMLElementName() { return "serviceTask"; } // @Test // public void printType(){ // System.out.println("type : " + getBpmnElementType()); // } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/eventGateway/channel/THMsgChannel.java package com.l2l.enterprise.vessel.eventGateway.channel; import org.springframework.cloud.stream.annotation.Input; import org.springframework.messaging.SubscribableChannel; public interface THMsgChannel { String Temperature_and_humidity = "temperatureAndHumidity"; @Input("temperatureAndHumidity") SubscribableChannel temperatureAndHumidity(); } <file_sep>/src/main/java/com/l2l/enterprise/vessel/domain/Destination.java package com.l2l.enterprise.vessel.domain; public class Destination { private String name; private String estiAnchorTime; private String estiArrivalTime; private String estiDepartureTime; public Destination(String name, String estiAnchorTime, String estiArrivalTime, String estiDepartureTime) { this.name = name; this.estiAnchorTime = estiAnchorTime; this.estiArrivalTime = estiArrivalTime; this.estiDepartureTime = estiDepartureTime; } public Destination() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEstiAnchorTime() { return estiAnchorTime; } public void setEstiAnchorTime(String estiAnchorTime) { this.estiAnchorTime = estiAnchorTime; } public String getEstiArrivalTime() { return estiArrivalTime; } public void setEstiArrivalTime(String estiArrivalTime) { this.estiArrivalTime = estiArrivalTime; } public String getEstiDepartureTime() { return estiDepartureTime; } public void setEstiDepartureTime(String estiDepartureTime) { this.estiDepartureTime = estiDepartureTime; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/boot/ProcessEngineAutoConfiguration.java package com.l2l.enterprise.vessel.extension.activiti.boot; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationService; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationServiceImpl; import com.l2l.enterprise.vessel.extension.activiti.behavior.L2LActivityBehaviorFactory; import com.l2l.enterprise.vessel.extension.activiti.form.FormService; import com.l2l.enterprise.vessel.extension.activiti.form.FormServiceImpl; import com.l2l.enterprise.vessel.extension.activiti.parser.L2LProcessParseHandler; import com.l2l.enterprise.vessel.extension.activiti.parser.L2LServiceTaskParseHandler; import com.l2l.enterprise.vessel.extension.activiti.parser.L2LServiceTaskXMLConverter; import com.l2l.enterprise.vessel.extension.activiti.parser.L2LTimerDefinitionParseHandler; import org.activiti.bpmn.converter.BpmnXMLConverter; import org.activiti.engine.impl.ServiceImpl; import org.activiti.engine.parse.BpmnParseHandler; import org.activiti.runtime.api.identity.UserGroupManager; import org.activiti.spring.SpringAsyncExecutor; import org.activiti.spring.SpringProcessEngineConfiguration; import org.activiti.spring.boot.ActivitiProperties; import org.activiti.spring.boot.ProcessEngineConfigurationConfigurer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; import java.io.IOException; import java.util.ArrayList; import java.util.List; @Configuration @AutoConfigureAfter({DataSourceAutoConfiguration.class}) @EnableConfigurationProperties({ActivitiProperties.class}) public class ProcessEngineAutoConfiguration extends AbstractProcessEngineAutoConfiguration { @Qualifier("l2LUserGroupManagerImpl") @Autowired protected UserGroupManager userGroupManager; @Autowired private ResourcePatternResolver resourceLoader; @Autowired ApplicationEventPublisher eventPublisher; @Autowired( required = false ) private ProcessEngineConfigurationConfigurer processEngineConfigurationConfigurer; public ProcessEngineAutoConfiguration() { } // @Bean // public DeployedEventListener deployedEventListener(){ // return new DeployedEventListener(); // } @Bean @ConditionalOnMissingBean public L2LProcessEngineConfiguration l2LProcessEngineConfiguration(ApplicationEventPublisher eventPublisher, DataSource dataSource, PlatformTransactionManager transactionManager, SpringAsyncExecutor springAsyncExecutor) throws IOException { springAsyncExecutor.setDefaultTimerJobAcquireWaitTimeInMillis(5000); L2LProcessEngineConfiguration conf = super.baseL2LProcessEngineConfiguration(eventPublisher, dataSource, transactionManager, springAsyncExecutor, this.userGroupManager); // conf.setBpmnParseFactory(new BpmnParseFactory() { // @Override // public BpmnParse createBpmnParse(BpmnParser bpmnParser) { // return new BpmnParse(conf.getBpmnParser()); // } // }); // replace the default 'ServiceTaskXMLConverter' with custom one. BpmnXMLConverter.addConverter(new L2LServiceTaskXMLConverter()); // customize the default activity behavior factory L2LActivityBehaviorFactory l2LActivityBehaviorFactory = new L2LActivityBehaviorFactory(); conf.setActivityBehaviorFactory(l2LActivityBehaviorFactory); // customize the parse handlers. List<BpmnParseHandler> customDefaultBpmnParseHandlers = new ArrayList<BpmnParseHandler>(); customDefaultBpmnParseHandlers.add(new L2LServiceTaskParseHandler()); customDefaultBpmnParseHandlers.add(new L2LTimerDefinitionParseHandler()); customDefaultBpmnParseHandlers.add(new L2LProcessParseHandler()); conf.setCustomDefaultBpmnParseHandlers(customDefaultBpmnParseHandlers); // The asynchronous job executor is disabled by default and needs to be activated. // conf.setAsyncExecutorDefaultTimerJobAcquireWaitTime(5000); // conf.setAsyncExecutorActivate(true); return conf; } @Bean @ConditionalOnMissingBean public FormService formService(L2LProcessEngineConfiguration l2LProcessEngineConfiguration) { FormService formService = new FormServiceImpl(); if (formService instanceof ServiceImpl) { ((ServiceImpl)formService).setCommandExecutor(l2LProcessEngineConfiguration.getCommandExecutor()); } return formService; } @Bean @ConditionalOnMissingBean public AnnotationService annotationService(L2LProcessEngineConfiguration l2LProcessEngineConfiguration) { AnnotationService annotationService = new AnnotationServiceImpl(l2LProcessEngineConfiguration); if (annotationService instanceof ServiceImpl) { ((ServiceImpl)annotationService).setCommandExecutor(l2LProcessEngineConfiguration.getCommandExecutor()); } return annotationService; } } <file_sep>/settings.gradle rootProject.name = 'vessel' <file_sep>/src/main/java/com/l2l/enterprise/vessel/repository/package-info.java /** * Spring Data JPA repositories. */ package com.l2l.enterprise.vessel.repository; <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/form/FormServiceImpl.java package com.l2l.enterprise.vessel.extension.activiti.form; import org.activiti.bpmn.model.BpmnModel; import org.activiti.engine.impl.ServiceImpl; import org.activiti.engine.impl.cmd.GetBpmnModelCmd; import org.springframework.stereotype.Service; public class FormServiceImpl extends ServiceImpl implements FormService { public FormServiceImpl() { } @Override public FormDefinition getStartForm(String processDefinitionId) { return (FormDefinition)this.commandExecutor.execute(new GetStartFormCmd(processDefinitionId)); } @Override public FormDefinition getUserTaskForm(String processDefinitionId,String taskDefinitionKey){ return (FormDefinition)this.commandExecutor.execute(new GetTaskFormCmd(processDefinitionId,taskDefinitionKey)); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/annotation/AnnotationService.java package com.l2l.enterprise.vessel.extension.activiti.annotation; import com.l2l.enterprise.vessel.extension.activiti.boot.L2LProcessEngineConfiguration; import com.l2l.enterprise.vessel.extension.activiti.form.FormDefinition; import com.l2l.enterprise.vessel.extension.activiti.model.Annotation; import org.activiti.engine.impl.persistence.entity.integration.IntegrationContextEntity; import java.util.List; import java.util.Map; public interface AnnotationService { List<Annotation> getActivityAnnotations(String processDefinitionId , String targetElementId); // List<Annotation> getMsgAnnotations(String processDefinitionId); List<Annotation> getAllActivitiesAnnotations(String processDefinitionId); L2LProcessEngineConfiguration getL2LProcessEngineConfiguration(); List<MsgAnnotation> getAllMsgAnnotations(String processDefinitionId); void trigger(String var1,IntegrationContextEntity integrationContextEntity,AnnotationIntergrationContextImpl annotationIntergrationContext); void trigger(String var1,IntegrationContextEntity integrationContextEntity,AnnotationIntergrationContextImpl annotationIntergrationContext, Map<String, Object> var2); void trigger(String var1, IntegrationContextEntity integrationContextEntity, AnnotationIntergrationContextImpl annotationIntergrationContext,Map<String, Object> var2, Map<String, Object> var3); } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/agenda/L2LTakeOutgoingSequenceFlowsOperation.java package com.l2l.enterprise.vessel.extension.activiti.agenda; import com.l2l.enterprise.vessel.extension.activiti.annotation.DefaultAnnotationBehavior; import com.l2l.enterprise.vessel.extension.activiti.boot.L2LProcessEngineConfiguration; import com.l2l.enterprise.vessel.extension.activiti.model.Annotation; import com.l2l.enterprise.vessel.extension.activiti.parser.AnnotationConstants; import org.activiti.bpmn.model.Activity; import org.activiti.bpmn.model.FlowElement; import org.activiti.bpmn.model.FlowNode; import org.activiti.bpmn.model.SequenceFlow; import org.activiti.engine.impl.agenda.TakeOutgoingSequenceFlowsOperation; import org.activiti.engine.impl.delegate.ActivityBehavior; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.integration.IntegrationContextEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class L2LTakeOutgoingSequenceFlowsOperation extends TakeOutgoingSequenceFlowsOperation { private static Logger logger = LoggerFactory.getLogger(L2LContinueProcessOperation.class); private IntegrationContextEntity integrationContextEntity; public L2LTakeOutgoingSequenceFlowsOperation(CommandContext commandContext, ExecutionEntity executionEntity, boolean evaluateConditions) { super(commandContext, executionEntity, evaluateConditions); } public L2LTakeOutgoingSequenceFlowsOperation(CommandContext commandContext, ExecutionEntity executionEntity, boolean evaluateConditions,IntegrationContextEntity integrationContextEntity){ super(commandContext, executionEntity, evaluateConditions); this.integrationContextEntity = integrationContextEntity; } public void run() { FlowElement currentFlowElement = this.getCurrentFlowElement(this.execution); // IntegrationContextEntity integrationContextEntity = this.integrationContextService.findById(integrationResult.getIntegrationContext().getId()); Annotation tAn = acquirePostAnnotations(currentFlowElement , execution); if(tAn != null){ enterPostAnnotation(tAn); }else{ super.run(); } } protected Annotation acquirePostAnnotations(FlowElement flowNode , ExecutionEntity execution){ String pdId = execution.getProcessDefinitionId(); List<Annotation> postAns = new ArrayList<Annotation>(); if(this.commandContext.getProcessEngineConfiguration() instanceof L2LProcessEngineConfiguration){ postAns = ((L2LProcessEngineConfiguration) this.commandContext.getProcessEngineConfiguration()).getAnnotationManager().getAnnotations() .stream().filter( an -> { boolean selected = false; if(integrationContextEntity == null){ selected = ( AnnotationConstants.POST_PROCESSOR.equals(an.getPointcutType()) && an.getTargetElementId().equals(flowNode.getId()) && an.getProcessDefinitionId().equals(execution.getProcessDefinitionId())); }else { selected = (!this.integrationContextEntity.getFlowNodeId().equals(an.getTargetElementId())&& !this.integrationContextEntity.getProcessDefinitionId().equals(an.getProcessDefinitionId())&& !this.integrationContextEntity.getExecutionId().equals((this.execution.getId())) && AnnotationConstants.POST_PROCESSOR.equals(an.getPointcutType()) && an.getTargetElementId().equals(flowNode.getId()) && an.getProcessDefinitionId().equals(execution.getProcessDefinitionId())); } return selected; }).collect(Collectors.toList()); } if(postAns.size() > 0){ // Initially , supporting only one annotation of specified 'pointcut' type on the FlowElement. Indeed we can support more than one. //Here we take the first from the annotation queue on the current flowElement. Annotation tAn = postAns.get(0); return tAn; }else{ logger.debug("No pre-annotaions is attached to the FlowElement {}" , flowNode.getId()); } return null; } protected void enterPostAnnotation(Annotation currentAnnotation){ if(currentAnnotation.getDestination() != null){ if(this.commandContext.getProcessEngineConfiguration() instanceof L2LProcessEngineConfiguration){ ActivityBehavior annotationBehavior = (ActivityBehavior) ((L2LProcessEngineConfiguration) this.commandContext.getProcessEngineConfiguration()) .getAnnotationManager().getBehavior(); if(annotationBehavior instanceof DefaultAnnotationBehavior){ ((DefaultAnnotationBehavior) annotationBehavior).execute(this.execution,currentAnnotation); } } }else{ logger.debug("Now , Only third-party delivery is supported"); } } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/eventGateway/MsgEventHandler.java package com.l2l.enterprise.vessel.eventGateway; public interface MsgEventHandler { } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/form/FormField.java package com.l2l.enterprise.vessel.extension.activiti.form; import java.io.Serializable; public class FormField implements Serializable { private static final long serialVersionUID = 1L; protected String id; protected String name; protected String type; protected Object value; protected boolean required; protected boolean readOnly; public FormField() { } public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public Object getValue() { return this.value; } public void setValue(Object value) { this.value = value; } public boolean isRequired() { return this.required; } public void setRequired(boolean required) { this.required = required; } public boolean isReadOnly() { return this.readOnly; } public void setReadOnly(boolean readOnly) { this.readOnly = readOnly; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/domain/Msg.java package com.l2l.enterprise.vessel.domain; public interface Msg { String getConnectorType(); } <file_sep>/src/main/java/com/l2l/enterprise/vessel/web/rest/SenderTest.java package com.l2l.enterprise.vessel.web.rest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.Output; import org.springframework.cloud.stream.messaging.Sink; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.MessageChannel; @EnableBinding(value = {SenderTest.SinkSender.class}) public class SenderTest { @Autowired private SenderTest.SinkSender sinkSender; public void sinkSenderTester() { sinkSender.output().send(MessageBuilder.withPayload("produce a message to " + Sink.INPUT + " channel").build()); } public interface SinkSender { @Output(Sink.INPUT) MessageChannel output(); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/annotation/AnnotationServiceImpl.java package com.l2l.enterprise.vessel.extension.activiti.annotation; import com.l2l.enterprise.vessel.extension.activiti.boot.L2LProcessEngineConfiguration; import com.l2l.enterprise.vessel.extension.activiti.model.Annotation; import org.activiti.engine.impl.ServiceImpl; import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl; import org.activiti.engine.impl.cmd.TriggerCmd; import org.activiti.engine.impl.persistence.entity.integration.IntegrationContextEntity; import java.util.List; import java.util.Map; public class AnnotationServiceImpl extends ServiceImpl implements AnnotationService{ public AnnotationServiceImpl(ProcessEngineConfigurationImpl processEngineConfiguration) { super(processEngineConfiguration); } @Override public List<Annotation> getActivityAnnotations(String processDefinitionId, String targetElementId) { return this.commandExecutor.execute(new GetActivityAnnotationsCmd(processDefinitionId ,targetElementId)); } // @Override // public List<Annotation> getMsgAnnotations(String processDefinitionId) { // return this.commandExecutor.execute(new GetMsgAnnotationsCmd(processDefinitionId)); // } @Override public List<Annotation> getAllActivitiesAnnotations(String processDefinitionId) { return this.commandExecutor.execute(new GetAllActivitiesAnnotationsCmd(processDefinitionId)); } @Override public List<MsgAnnotation> getAllMsgAnnotations(String processDefinitionId){ return this.commandExecutor.execute((new GetMsgAnnotationsCmd(processDefinitionId))); } @Override public L2LProcessEngineConfiguration getL2LProcessEngineConfiguration(){ return (L2LProcessEngineConfiguration)this.processEngineConfiguration; } @Override public void trigger(String executionId,IntegrationContextEntity integrationContextEntity,AnnotationIntergrationContextImpl annotationIntergrationContext) { this.commandExecutor.execute(new AnnotationTrigglerCmd(executionId,integrationContextEntity ,annotationIntergrationContext,(Map)null)); } @Override public void trigger(String executionId, IntegrationContextEntity integrationContextEntity,AnnotationIntergrationContextImpl annotationIntergrationContext,Map<String, Object> processVariables) { this.commandExecutor.execute(new AnnotationTrigglerCmd(executionId, integrationContextEntity,annotationIntergrationContext,processVariables)); } @Override public void trigger(String executionId, IntegrationContextEntity integrationContextEntity,AnnotationIntergrationContextImpl annotationIntergrationContext,Map<String, Object> processVariables, Map<String, Object> transientVariables) { this.commandExecutor.execute(new AnnotationTrigglerCmd(executionId,integrationContextEntity,annotationIntergrationContext,processVariables,transientVariables)); } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/form/FormUtils.java package com.l2l.enterprise.vessel.extension.activiti.form; import org.activiti.bpmn.model.FormProperty; public class FormUtils { public static FormField toFormField(FormProperty formProperty){ FormField formField = new FormField(); formField.setId(formProperty.getId()); formField.setType(formProperty.getType()); formField.setName(formProperty.getName()); formField.setReadOnly(formProperty.isReadable()); formField.setRequired(formProperty.isRequired()); return formField; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/eventGateway/channel/DelayChannel.java package com.l2l.enterprise.vessel.eventGateway.channel; import afu.org.checkerframework.checker.units.qual.A; import com.l2l.enterprise.vessel.domain.DelayMsg; import com.l2l.enterprise.vessel.eventGateway.EventAssember; import com.l2l.enterprise.vessel.eventGateway.MsgEventHandler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.stereotype.Component; @Component @EnableBinding({DelayMsgChannel.class}) public class DelayChannel { // @Autowired // EventAssember eventAssember; // // @Autowired // MsgEventHandler eventHandler; // @StreamListener(value = "delaymsgConsumer") // public void comfirmDelayMsg(DelayMsg delayMsg){ //// eventAssember.handle("delaymsgConsumer" , delayMsg); // // eventHandler.comfirmDelayMsg(delayMsg); // } // @StreamListener(value = "delayDestinationUpdate") // public void delayDestinationUpdate(DelayMsg delayMsg){ //// eventAssember.handle("delaymsgConsumer" , delayMsg); // // eventHandler.delayDestinationUpdate(delayMsg); // } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/deploy/L2LDeploymentManager.java package com.l2l.enterprise.vessel.extension.activiti.deploy; import org.activiti.engine.impl.persistence.deploy.DeploymentManager; public class L2LDeploymentManager extends DeploymentManager { } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/utils/L2LProcessDefinitionUtil.java package com.l2l.enterprise.vessel.extension.activiti.utils; import com.l2l.enterprise.vessel.extension.activiti.boot.L2LProcessEngineConfiguration; import com.l2l.enterprise.vessel.extension.activiti.cache.L2LDeploymentCache; import org.activiti.bpmn.model.Process; import org.activiti.engine.ActivitiException; import org.activiti.engine.RepositoryService; import org.activiti.engine.RuntimeService; import org.activiti.engine.impl.DeploymentQueryImpl; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.persistence.deploy.DeploymentCache; import org.activiti.engine.impl.persistence.deploy.DeploymentManager; import org.activiti.engine.impl.persistence.deploy.ProcessDefinitionCacheEntry; import org.activiti.engine.impl.persistence.entity.DeploymentEntity; import org.activiti.engine.impl.util.Activiti5Util; import org.activiti.engine.impl.util.ProcessDefinitionUtil; import org.activiti.engine.repository.Deployment; import org.activiti.engine.repository.DeploymentQuery; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.repository.ProcessDefinitionQuery; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; public class L2LProcessDefinitionUtil { private static Logger log = LoggerFactory.getLogger(L2LProcessDefinitionUtil.class); public L2LProcessDefinitionUtil() { } public static List<Process> getProcessesOfAllVersions(L2LProcessEngineConfiguration l2LProcessEngineConfiguration) { List<Process> res = new ArrayList<Process>(); List<String> pids = getProcessDefinitionIdsOfAllVersions(l2LProcessEngineConfiguration); return res; } public static List<String> getProcessDefinitionIdsOfAllVersions(L2LProcessEngineConfiguration l2LProcessEngineConfiguration) { DeploymentManager deploymentManager = l2LProcessEngineConfiguration.getDeploymentManager(); DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache = deploymentManager.getProcessDefinitionCache(); List<String> res = new ArrayList<String>(); //if the new version of the bundled processDefinitions is deployed, get them from the `DeploymentManager`. if (processDefinitionCache instanceof L2LDeploymentCache) { Map<String, ProcessDefinitionCacheEntry> mp = ((L2LDeploymentCache<ProcessDefinitionCacheEntry>) processDefinitionCache).getCache(); List<String> newPids = mp.entrySet().stream().map(e -> e.getKey()).collect(Collectors.toList()); res.addAll(newPids); } //Get the old version of the deployed processDefinitions RepositoryService repositoryService = l2LProcessEngineConfiguration.getRepositoryService(); ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery(); List<String> oldPids = processDefinitionQuery.list().stream().map(ProcessDefinition::getId).collect(Collectors.toList()); res.addAll(oldPids); return res; } public static Process getProcess(String processDefinitionId , L2LProcessEngineConfiguration l2LProcessEngineConfiguration) { if (l2LProcessEngineConfiguration == null) { log.debug("l2LProcessEngineConfiguration is null"); return null; } else { DeploymentManager deploymentManager = l2LProcessEngineConfiguration.getDeploymentManager(); RepositoryService repositoryService = l2LProcessEngineConfiguration.getRepositoryService(); ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery(); ProcessDefinition processDefinitionEntity = processDefinitionQuery.processDefinitionId(processDefinitionId).singleResult(); if(processDefinitionEntity == null){ processDefinitionEntity = deploymentManager.findDeployedProcessDefinitionById(processDefinitionId); } DeploymentQuery deploymentQuery = repositoryService.createDeploymentQuery(); // DeploymentEntity deployment = (DeploymentEntity) deploymentQuery.deploymentId(processDefinitionEntity.getDeploymentId()).singleResult(); // if(deployment == null){ DeploymentEntity deployment = (DeploymentEntity)deploymentManager.getDeploymentEntityManager().findById(processDefinitionEntity.getDeploymentId()); // } deployment.setNew(false); deploymentManager.deploy(deployment, (Map)null); ProcessDefinitionCacheEntry cachedProcessDefinition = (ProcessDefinitionCacheEntry) deploymentManager.getProcessDefinitionCache().get(processDefinitionId); if (cachedProcessDefinition == null) { throw new ActivitiException("deployment '" + deployment.getId() + "' didn't put process definition '" + processDefinitionId + "' in the cache"); } return cachedProcessDefinition.getProcess(); } } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/eventGateway/VidPidRegisterService.java package com.l2l.enterprise.vessel.eventGateway; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationConnector; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationIntergrationContextImpl; import org.activiti.engine.RuntimeService; import org.activiti.engine.delegate.DelegateExecution; import org.activiti.engine.runtime.Execution; import org.activiti.engine.runtime.ProcessInstance; import org.activiti.runtime.api.connector.Connector; import org.activiti.runtime.api.model.IntegrationContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("vidPidRegisterService") public class VidPidRegisterService implements AnnotationConnector { private static Logger logger = LoggerFactory.getLogger(VidPidRegisterService.class); @Autowired VidPidRegistry vidPidRegistry; @Autowired RuntimeService runtimeService; @Override public AnnotationIntergrationContextImpl execute(AnnotationIntergrationContextImpl integrationContext,DelegateExecution execution) { String pid = integrationContext.getProcessInstanceId(); String vid = runtimeService.getVariable(execution.getId() , "vid").toString(); vidPidRegistry.p2vMap.put(pid,vid); vidPidRegistry.v2pMap.put(vid,pid); // integrationContext.getAnnotation().getInputVariables(); return integrationContext; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/annotation/AnnotationRequest.java package com.l2l.enterprise.vessel.extension.activiti.annotation; public interface AnnotationRequest { AnnotationIntergrationContextImpl getAnnotationIntergrationContext() ; } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/form/GetTaskFormCmd.java package com.l2l.enterprise.vessel.extension.activiti.form; import org.activiti.bpmn.model.FormProperty; import org.activiti.bpmn.model.Process; import org.activiti.bpmn.model.UserTask; import org.activiti.engine.ActivitiIllegalArgumentException; import org.activiti.engine.impl.interceptor.Command; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.util.ProcessDefinitionUtil; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class GetTaskFormCmd implements Command<FormDefinition>, Serializable { protected String processDefinitionId; protected String taskDefinitionKey; public GetTaskFormCmd(String processDefinitionId ,String taskDefinitionKey){ this.processDefinitionId = processDefinitionId; this.taskDefinitionKey = taskDefinitionKey; } @Override public FormDefinition execute(CommandContext commandContext) { if (this.processDefinitionId == null) { throw new ActivitiIllegalArgumentException("processDefinitionId is null"); } else { Process process = ProcessDefinitionUtil.getProcess(this.processDefinitionId); List<UserTask> userTasks= process.findFlowElementsOfType((UserTask.class) , false); FormDefinition formDefinition = new FormDefinition(); Boolean flag = false; if(userTasks.size() > 0){ for(UserTask userTask : userTasks){ if(userTask.getId().equals(taskDefinitionKey)){ List<FormProperty> formProperties = userTask.getFormProperties(); formProperties.forEach((formProperty)->{ FormField formField = FormUtils.toFormField(formProperty); formDefinition.getFields().add(formField); }); } } return formDefinition; }else{ throw new ActivitiIllegalArgumentException("UserTask is null"); } } } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/connector/channel/AnnotationIntergrationResultEventHandler.java package com.l2l.enterprise.vessel.extension.activiti.connector.channel; import com.l2l.enterprise.vessel.domain.DelayMsg; import com.l2l.enterprise.vessel.eventGateway.DelayMsgHandler; import com.l2l.enterprise.vessel.eventGateway.MsgEventHandler; import com.l2l.enterprise.vessel.eventGateway.channel.DelayMsgChannel; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationIntegrationResultImpl; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationIntergrationContextImpl; import com.l2l.enterprise.vessel.extension.activiti.annotation.AnnotationService; import org.activiti.cloud.services.events.configuration.RuntimeBundleProperties; import org.activiti.cloud.services.events.converter.RuntimeBundleInfoAppender; import org.activiti.engine.RuntimeService; import org.activiti.engine.impl.persistence.entity.integration.IntegrationContextEntity; import org.activiti.engine.integration.IntegrationContextService; import org.activiti.runtime.api.event.impl.CloudIntegrationResultReceivedImpl; import org.activiti.runtime.api.model.IntegrationResult; import org.activiti.services.connectors.channel.ServiceTaskIntegrationResultEventHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.StreamListener; import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Component; @Component @EnableBinding({AnnotationIntegrationChannels.class }) public class AnnotationIntergrationResultEventHandler { private static final Logger LOGGER = LoggerFactory.getLogger(ServiceTaskIntegrationResultEventHandler.class); private final RuntimeService runtimeService; private final IntegrationContextService integrationContextService; private final MessageChannel auditProducer; private final RuntimeBundleProperties runtimeBundleProperties; private final RuntimeBundleInfoAppender runtimeBundleInfoAppender; private final AnnotationService annotationService; private final MsgEventHandler msgEventHandler; private static org.slf4j.Logger log = LoggerFactory.getLogger(AnnotationIntergrationResultEventHandler.class); public AnnotationIntergrationResultEventHandler(RuntimeService runtimeService, IntegrationContextService integrationContextService, MessageChannel auditProducer, RuntimeBundleProperties runtimeBundleProperties, RuntimeBundleInfoAppender runtimeBundleInfoAppender, AnnotationService annotationService, DelayMsgHandler delayMsgHandler) { this.runtimeService = runtimeService; this.integrationContextService = integrationContextService; this.auditProducer = auditProducer; this.runtimeBundleProperties = runtimeBundleProperties; this.runtimeBundleInfoAppender = runtimeBundleInfoAppender; this.annotationService = annotationService; this.msgEventHandler = delayMsgHandler; } @StreamListener("AnnotationIntegrationResultsConsumer") public void AnnoatationResultReceive(AnnotationIntegrationResultImpl integrationResult) { IntegrationContextEntity integrationContextEntity = this.integrationContextService.findById(integrationResult.getIntegrationContext().getId()); AnnotationIntergrationContextImpl annotationIntergrationContext= null; if(integrationResult.getAnnotationIntegrationRequest().getAnnotationIntergrationContext() instanceof AnnotationIntergrationContextImpl){ annotationIntergrationContext = (AnnotationIntergrationContextImpl) integrationResult.getAnnotationIntegrationRequest().getAnnotationIntergrationContext() ; } if (integrationContextEntity != null) { this.integrationContextService.deleteIntegrationContext(integrationContextEntity); if(integrationResult.getAnnotationIntegrationRequest().getAnnotationIntergrationContext().getAnnotation().getImplementationType().equals("msgType")){ if (this.runtimeService.createExecutionQuery().executionId(integrationContextEntity.getExecutionId()).list().size() > 0) { //获取commandcontext 必须要采用cmd模式 这里是否口语添加流程变量的修改代码 感觉可以 this.runtimeService.setVariables(integrationContextEntity.getExecutionId(), integrationResult.getAnnotationIntegrationRequest().getAnnotationIntergrationContext().getAnnotation().getExecutionvars()); } else { String message = "No task is in this RB is waiting for integration result with execution id `" + integrationContextEntity.getExecutionId() + ", flow node id `" + integrationResult.getIntegrationContext().getActivityElementId() + "`. The integration result for the integration context `" + integrationResult.getIntegrationContext().getId() + "` will be ignored."; LOGGER.debug(message); } }else if(this.runtimeService.createExecutionQuery().executionId(integrationContextEntity.getExecutionId()).list().size() > 0) { //获取commandcontext 必须要采用cmd模式 这里是否口语添加流程变量的修改代码 感觉可以 this.runtimeService.setVariables(integrationContextEntity.getExecutionId(), integrationResult.getAnnotationIntegrationRequest().getAnnotationIntergrationContext().getAnnotation().getExecutionvars()); this.annotationService.trigger(integrationContextEntity.getExecutionId(), integrationContextEntity,annotationIntergrationContext); } else { String message = "No task is in this RB is waiting for integration result with execution id `" + integrationContextEntity.getExecutionId() + ", flow node id `" + integrationResult.getIntegrationContext().getActivityElementId() + "`. The integration result for the integration context `" + integrationResult.getIntegrationContext().getId() + "` will be ignored."; LOGGER.debug(message); } log.info(integrationResult.toString()); this.sendAuditMessage(integrationResult); } } private void sendAuditMessage(IntegrationResult integrationResult) { if (this.runtimeBundleProperties.getEventsProperties().isIntegrationAuditEventsEnabled()) { CloudIntegrationResultReceivedImpl integrationResultReceived = new CloudIntegrationResultReceivedImpl(integrationResult.getIntegrationContext()); this.runtimeBundleInfoAppender.appendRuntimeBundleInfoTo(integrationResultReceived); Message<CloudIntegrationResultReceivedImpl> message = MessageBuilder.withPayload(integrationResultReceived).build(); this.auditProducer.send(message); } } // @StreamListener("delayDestinationUpdate") // public void delayDestinationUpdate(DelayMsg delayMsg){ // msgEventHandler.delayDestinationUpdate(delayMsg); // } // @StreamListener("AnnotationIntegrationResultsConsumer") // public void comfirmDelayMsg(DelayMsg delayMsg){ // msgEventHandler.comfirmDelayMsg(delayMsg); // } // @StreamListener(DelayMsgChannel.DELAY_MSG) // public void comfirmDelayMsg(DelayMsg delayMsg){ // LOGGER.info("get"); //// msgEventHandler.comfirmDelayMsg(delayMsg); // } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/domain/THMsg.java package com.l2l.enterprise.vessel.domain; import java.io.Serializable; import java.util.HashMap; import java.util.List; import java.util.Map; public class THMsg extends MsgImpl implements Serializable { private Map<String,TandH> vidToTandH = new HashMap<>();//vid 对应湿度和温度 // @Override // public String getConnectorType() { // return null; // } public class TandH { private float temperature; private float humidity; public TandH(float temperature, float humidity) { this.temperature = temperature; this.humidity = humidity; } public float getTemperature() { return temperature; } public void setTemperature(float temperature) { this.temperature = temperature; } public float getHumidity() { return humidity; } public void setHumidity(float humidity) { this.humidity = humidity; } } public THMsg() { super(); } public THMsg(List<String> pids, String connectorType, String topic, String scenario,Map<String,TandH> vidToTandH) { super(pids, connectorType, topic, scenario); this.vidToTandH = vidToTandH; } public Map<String, TandH> getVidToTandH() { return vidToTandH; } public void setVidToTandH(Map<String, TandH> vidToTandH) { this.vidToTandH = vidToTandH; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/listener/SampleEvent.java package com.l2l.enterprise.vessel.extension.activiti.listener; import org.springframework.context.ApplicationEvent; public class SampleEvent extends ApplicationEvent { private String name; public SampleEvent(String name, Object source) { super(source); this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/config/package-info.java /** * Spring Framework configuration files. */ package com.l2l.enterprise.vessel.config; <file_sep>/src/main/java/com/l2l/enterprise/vessel/eventGateway/VidPidRegistry.java package com.l2l.enterprise.vessel.eventGateway; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.Collections; import java.util.HashMap; import java.util.Map; @Service public class VidPidRegistry { private static final Logger log = LoggerFactory.getLogger(VidPidRegistry.class); Map<String , String> v2pMap; Map<String , String> p2vMap; public VidPidRegistry() { this.p2vMap = Collections.synchronizedMap(new HashMap()); this.v2pMap = Collections.synchronizedMap(new HashMap()); } public String findRegisteredVidBypId(String pid){ return p2vMap.get(pid); } public String findRegisteredpidByvId(String vid){ return v2pMap.get(vid); } public Map<String, String> getV2pMap() { return v2pMap; } public void setV2pMap(Map<String, String> v2pMap) { this.v2pMap = v2pMap; } public Map<String, String> getP2vMap() { return p2vMap; } public void setP2vMap(Map<String, String> p2vMap) { this.p2vMap = p2vMap; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/web/rest/h2Jdbc.java package com.l2l.enterprise.vessel.web.rest; import org.springframework.stereotype.Component; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @Component public class h2Jdbc { private static final String JDBC_URL = "jdbc:h2:file:./build/h2db/db/vessel"; //连接数据库时使用的用户名 private static final String USER = "vessel"; //连接数据库时使用的密码 private static final String PASSWORD = ""; //连接H2数据库时使用的驱动类,org.h2.Driver这个类是由H2数据库自己提供的,在H2数据库的jar包中可以找到 private static final String DRIVER_CLASS="org.h2.Driver"; public HashMap<String, List<String>> querytask() throws Exception { // 加载H2数据库驱动 Class.forName(DRIVER_CLASS); // 根据连接URL,用户名,密码获取数据库连接 Connection conn = DriverManager.getConnection(JDBC_URL, USER, PASSWORD); Statement stmt = conn.createStatement(); // //如果存在USER_INFO表就先删除USER_INFO表 // stmt.execute("DROP TABLE IF EXISTS USER_INFO"); // //创建USER_INFO表 // stmt.execute("CREATE TABLE USER_INFO(id VARCHAR(36) PRIMARY KEY,name VARCHAR(100),sex VARCHAR(4))"); // //新增 // stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID()+ "','大日如来','男')"); // stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID()+ "','青龙','男')"); // stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID()+ "','白虎','男')"); // stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID()+ "','朱雀','女')"); // stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID()+ "','玄武','男')"); // stmt.executeUpdate("INSERT INTO USER_INFO VALUES('" + UUID.randomUUID()+ "','苍狼','男')"); // //删除 // stmt.executeUpdate("DELETE FROM USER_INFO WHERE name='大日如来'"); // //修改 // stmt.executeUpdate("UPDATE USER_INFO SET name='孤傲苍狼' WHERE name='苍狼'"); //查询 ResultSet rs = stmt.executeQuery("SELECT * FROM ACT_RU_TASK "); //遍历结果集 HashMap<String,List<String>> taskMap = new HashMap<>(); while (rs.next()) { List<String> pid_tname = new ArrayList<>(); pid_tname.add(rs.getString("PROC_INST_ID_")); pid_tname.add(rs.getString("NAME_")); taskMap.put(rs.getString("ID_"),pid_tname); // String s = rs.getString("ID_") + "," + rs.getString("PROC_INST_ID_")+ "," + rs.getString("NAME_"); // System.out.println(rs.getString("ID_") + "," + rs.getString("PROC_INST_ID_")+ "," + rs.getString("NAME_")); } return taskMap; //释放资源 // stmt.close(); // //关闭连接 // conn.close(); } public List<String> finTaskIf(String pid) throws Exception { HashMap<String, List<String>> taskMap = this.querytask(); String taskId = ""; String taskName = ""; for(String key : taskMap.keySet()){ if(taskMap.get(key).get(0).equals(pid)){ taskId = key; taskName = taskMap.get(key).get(1); break; } } List<String> ans = new ArrayList<>(); ans.add(taskId); ans.add(taskName); return ans; } } <file_sep>/src/main/java/com/l2l/enterprise/vessel/extension/activiti/behavior/L2LBoundaryTimerEventActivityBehavior.java package com.l2l.enterprise.vessel.extension.activiti.behavior; import org.activiti.bpmn.model.*; import org.activiti.engine.ActivitiException; import org.activiti.engine.impl.bpmn.behavior.BoundaryTimerEventActivityBehavior; import org.activiti.engine.impl.cmd.CompleteTaskCmd; import org.activiti.engine.impl.context.Context; import org.activiti.engine.impl.interceptor.CommandContext; import org.activiti.engine.impl.persistence.entity.ExecutionEntity; import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager; import org.activiti.engine.impl.persistence.entity.TaskEntity; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; public class L2LBoundaryTimerEventActivityBehavior extends BoundaryTimerEventActivityBehavior { private static final Logger logger = LoggerFactory.getLogger(L2LBoundaryTimerEventActivityBehavior.class); public L2LBoundaryTimerEventActivityBehavior(TimerEventDefinition timerEventDefinition, boolean interrupting) { super(timerEventDefinition, interrupting); } protected void executeInterruptingBehavior(ExecutionEntity executionEntity, CommandContext commandContext) { ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager(); ExecutionEntity attachedRefScopeExecution = (ExecutionEntity)executionEntityManager.findById(executionEntity.getParentId()); ExecutionEntity parentScopeExecution = null; ExecutionEntity currentlyExaminedExecution = (ExecutionEntity)executionEntityManager.findById(attachedRefScopeExecution.getParentId()); while(currentlyExaminedExecution != null && parentScopeExecution == null) { if (currentlyExaminedExecution.isScope()) { parentScopeExecution = currentlyExaminedExecution; } else { currentlyExaminedExecution = (ExecutionEntity)executionEntityManager.findById(currentlyExaminedExecution.getParentId()); } } if (parentScopeExecution == null) { throw new ActivitiException("Programmatic error: no parent scope execution found for boundary event"); } else { this.deleteChildExecutions(attachedRefScopeExecution, executionEntity, commandContext); executionEntity.setParent(parentScopeExecution); Context.getAgenda().planTakeOutgoingSequenceFlowsOperation(executionEntity, true); } } protected void executeNonInterruptingBehavior(ExecutionEntity executionEntity, CommandContext commandContext) { ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager(); ExecutionEntity parentExecutionEntity = (ExecutionEntity)executionEntityManager.findById(executionEntity.getParentId()); ExecutionEntity scopeExecution = null; ExecutionEntity currentlyExaminedExecution = (ExecutionEntity)executionEntityManager.findById(parentExecutionEntity.getParentId()); while(currentlyExaminedExecution != null && scopeExecution == null) { if (currentlyExaminedExecution.isScope()) { scopeExecution = currentlyExaminedExecution; } else { currentlyExaminedExecution = (ExecutionEntity)executionEntityManager.findById(currentlyExaminedExecution.getParentId()); } } if (scopeExecution == null) { throw new ActivitiException("Programmatic error: no parent scope execution found for boundary event"); } else { FlowElement currentFlowElement = executionEntity.getCurrentFlowElement(); if(hasOutgoingFlows(currentFlowElement)){ ExecutionEntity nonInterruptingExecution = executionEntityManager.createChildExecution(scopeExecution); nonInterruptingExecution.setCurrentFlowElement(currentFlowElement); Context.getAgenda().planTakeOutgoingSequenceFlowsOperation(nonInterruptingExecution, true); } else { // When the timed event arrives, comlete the task at the same time. List<TaskEntity> taskEntities = parentExecutionEntity.getTasks(); String taskId = taskEntities.get(0).getId(); Context.getProcessEngineConfiguration().getCommandExecutor().execute(new CompleteTaskCmd(taskId, null)); } } } /** * evaluate the whether the boundary event has outgoing flows. * @param flowElement * @return */ public boolean hasOutgoingFlows(FlowElement flowElement){ List<SequenceFlow> outgoingSequenceFlows = new ArrayList(); FlowNode flowNode = (FlowNode) flowElement; if(!(flowNode instanceof BoundaryEvent)){ logger.debug("current node is required BoundaryEvent"); return false; } outgoingSequenceFlows = flowNode.getOutgoingFlows(); return outgoingSequenceFlows.size() > 0; } }
48c0156374bdd1caf55024c984a32cf5994f0003
[ "Java", "Gradle" ]
43
Java
l2l-v2/vessel-enterprise-rb-service
9e304d810e65d73391e7065dfd05218fa44a4f2d
ce0da7b87e30060ba17c752f886602b0294260fc
refs/heads/master
<file_sep><?php /** * @package Adserver * @author <NAME> */ require_once('Repository.php'); class JsonDB implements Repository { var $path; public function __construct($storage) { $this->path = $storage['DATA_FOLDER']; } /** * Function to save to file * @param string $table * @param array $data * @return int */ public function insert($table, $data) { if (!file_exists($this->path . '/' . $table)) { file_put_contents($this->path . '/' . $table, null, FILE_APPEND); } $jsonData = $this->read($this->path . '/' . $table); $totalCount = count($jsonData) - 1; $data['id'] = $jsonData[$totalCount]['id'] + 1; $jsonData[] = $data; file_put_contents($this->path . '/' . $table, json_encode($jsonData)); return $data['id']; } /** * Function to delete from file * @param string $table * @param array $data * @return int */ public function delete($table, $data) { $jsonData = $this->read($this->path . '/' . $table); $id = 0; // get array index to delete $arr_index = array(); foreach ($jsonData as $key => $value) { if ($value['id'] == $data['id']) { $id = $key; unset($jsonData[$key]); } } // rebase array $jsonData = array_values($jsonData); // encode array to json and save to file file_put_contents($this->path . '/' . $table, json_encode($jsonData)); return $id; } /** * Function to update from file * @param string $table * @param array $data * @return int */ public function update($table, $data) { $jsonData = $this->read($this->path . '/' . $table); $id = 0; foreach ($jsonData as $key => $value) { if ($value['id'] == $data['id']) { $id = $key; $jsonData[$key] = $data; } } // encode array to json and save to file file_put_contents($this->path . '/' . $table, json_encode($jsonData)); return $id; } /** * Function to select all from file * @param string $table * @param array $data * @return int */ public function select($table) { $data = $this->read($this->path . '/' . $table); if (is_array($data)) { ksort($data); return $data; } else { return array(); } } /** * Function to bulkinsert from file * @param string $table * @param array $data * @return int */ public function multiinsert($table, $data) { $jsonData = $this->read($this->path . '/' . $table); $totalCount = count($jsonData) - 1; $newID = $jsonData[$totalCount]['id'] + 1; $dataArray = array(); foreach ($data as $column => $colvalues) { $data[$column]['id'] = $newID; $newID = $newID + 1; } $jsonData[] = $data; $appendData = str_replace(array('[', ']'), '', htmlspecialchars(json_encode($jsonData), ENT_NOQUOTES)); file_put_contents($this->path . '/' . $table, '[' . $appendData . ']'); return true; } private function read($path) { return json_decode(file_get_contents($path), true); } /** * funtion to select with filter * @param string $table * @param array $where * @return array */ public function find($table, $where, $select = array()) { $found = array(); print_r($where); $jsonData = $this->read($this->path . '/' . $table); foreach ($jsonData as $aKey => $aVal) { $coincidences = 0; foreach ($where as $pKey => $pVal) { if (array_key_exists($pKey, $aVal) && $aVal[$pKey] == $pVal) { $coincidences++; } } if ($coincidences == count($where)) { $found[$aKey] = $aVal; } } return $found; } } <file_sep><?php require_once('DBFactory.php'); require_once('MysqlDB.php'); require_once('JsonDB.php'); class DBFactory { /** * * @param string $DBType * @return DB */ static public function createDB($DBType,$storage){ switch ($DBType) { case 'mysql': $obj = new MysqlDB($storage); break; case 'json': $obj = new JsonDB($storage); break; default: $obj = new MysqlDB($storage); break; } return $obj; } } <file_sep><?php /** * @package Adserver * @author <NAME> */ require_once('Repository.php'); class MysqlDB implements Repository { var $path; public function __construct($storage) { $dsn = "mysql:host=" . $storage['DB_HOST'] . ";dbname=" . $storage['DB_NAME']; $opt = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $this->path = new PDO($dsn, $storage['DB_USER'], $storage['DB_PASS'], $opt); } /** * function to save data * @param string $table * @param array $data * @return int id */ public function insert($table, $data) { $result = array(); $columns = array(); $values = array(); foreach ($data as $column => $value) { $columns[] = $column; $values[] = $value; } $columns_imploded = implode(",", $columns); $values_imploded = "'" . implode("','", $values) . "'"; $query = "INSERT INTO $table ($columns_imploded) VALUES($values_imploded)"; $query = $this->path->prepare($query); $result = $query->execute(); return $this->path->lastInsertId(); } /** * funtion to insert multiple items * @param string $table * @param array $data * @return int */ public function multiinsert($table, $data) { $result = array(); $columns = array(); $values = array(); $queryString = ''; foreach ($data as $column => $colvalues) { $columns[] = array_keys($colvalues); $queryString .= '('; $queryString .= "'" . implode("','", array_values($colvalues)) . "'"; ; $queryString .= '),'; } $columns_imploded = implode(",", $columns[0]); $values_imploded = substr($queryString, 0, strlen($queryString) - 1); $query = "INSERT INTO $table ($columns_imploded) VALUES $values_imploded;"; $query = $this->path->prepare($query); $result = $query->execute(); return $result; } /** * funtion to delete * @param string $table * @param array $data * @return int */ public function delete($table, $data) { if (isset($data['id'])) { $result = ""; $where = 'id=' . $data['id']; $query = "DELETE FROM $table WHERE $where "; $query = $this->path->prepare($query); $result = $query->execute(); return $result; } } /** * funtion to update * @param string $table * @param array $data * @return int */ public function update($table, $data) { $result = array(); $new_values = array(); if (isset($data['id'])) { $where = 'id=' . $data['id']; unset($data['id']); foreach ($data as $column => $value) { $new_values[] = $column . " = " . "'" . $value . "'"; } $new_values_sql = join(",", $new_values); $query = "UPDATE $table SET $new_values_sql WHERE $where "; $query = $this->path->prepare($query); $result = $query->execute(); return $result; } } /** * funtion to select * @param string $table * @return array */ public function select($table) { $stmt = $this->path->prepare("SELECT * FROM $table"); $stmt->execute(); if ($stmt->rowCount() == 0) { $result = null; } else { $result = $stmt->fetchAll(); } return $result; } /** * funtion to select with filter * @param string $table * @param array $where * @return array */ public function find($table, $where, $select = array()) { $args = array(); foreach ($where as $key => $value) { $args[':' . $key] = $value; } $i = 0; foreach ($where as $key => $value) { if (!$i) $where_sql = "WHERE :{$key} = {$key}"; else $where_sql .= " AND {$key} = {$key}"; $i++; } $sql_select = ' * '; if (count($select)) $sql_select = implode(", ", $select); $query = "SELECT {$sql_select} FROM {$table} {$where_sql} "; return $this->db->query($query, $args); } } <file_sep><?php require_once(__DIR__ . '/../utils/CampaignUtil.php'); class Campaign { public static function getAllCampaigns() { return CampaignUtil::getAllCampaigns(); } public static function addNewCampaign($data) { return CampaignUtil::addNewCampaign($data); } public static function updateCampaign($data) { return CampaignUtil::updateCampaign($data); } public static function deleteCampaign($id) { return CampaignUtil::deleteCampaign($id); } }<file_sep><?php class concrete_optimization_1 extends base_optimization { /** * concrete_optimization_1 constructor. */ public function __construct() { parent::__construct(); $this->concrete_network_setting = array('runtime' => 'lastrun'); } public function getRow() { $this->row = $this->db->queryAll('SELECT * FROM campaigns WHERE active = 1'); } } <file_sep><?php require_once('Model.php'); class CampaignModel extends Model { var $table = 'ad_campaign'; function __construct() { parent::__construct(); } /* * Function returns all campaign */ public function getAllCampaigns() { return $this->connection->select($this->table); } /* * Function adds new campaign to database */ public function addNewCampaign($data) { try { return $this->connection->insert($this->table,$data); } catch(Exception $e) { throw $e; } } /* * Function adds new campaign to database */ public function updateCampaign($data) { try { return $this->connection->update($this->table,$data); } catch(Exception $e) { throw $e; } } /* * Function deletes campaign from the database */ public function deleteCampaign($id) { try { return $this->connection->delete($this->table,array('id'=>$id)); } catch(Exception $e) { throw $e; } } }<file_sep><?php /** * @package Adserver * @author <NAME> */ require_once(__DIR__ . '/../utils/BannerUtil.php'); class Banner { public static function getAllBanners() { return BannerUtil::getAllBanners(); } public static function getBannersByDimensions($data) { return BannerUtil::getBannersByDimensions($data); } public static function addNewBanner($data) { return BannerUtil::addNewBanner($data); } public static function addMultipleBanner($data) { return BannerUtil::addMultipleBanner($data); } public static function updateBanner($data) { return BannerUtil::updateBanner($data); } public static function deleteBanner($id) { return BannerUtil::deleteBanner($id); } } <file_sep><?php require __DIR__ . '/vendor/jacwright/restserver/source/Jacwright/RestServer/RestServer.php'; require __DIR__ . '/src/rest/BannerController.php'; require __DIR__ . '/src/rest/CampaignController.php'; $server = new \Jacwright\RestServer\RestServer('debug'); $server->addClass('BannerController'); $server->addClass('CampaignController'); $server->handle();<file_sep><?php /** * @package Adserver * @author <NAME> */ interface Repository { public function insert($table, $data); public function delete($table, $data); public function multiinsert($table, $data); public function update($table, $data); public function find($table, $where, $select = array()); public function select($table); } <file_sep><?php /** * @package Adserver * @author <NAME> */ require_once('Model.php'); class BannerModel extends Model { var $table = 'ad_banner'; function __construct() { parent::__construct(); } /* * Function returns all banner */ public function getAllBanners() { return $this->connection->select($this->table); } public function getBannersByDimensions($data) { try { return $this->connection->find($this->table,$data); } catch(Exception $e) { throw $e; } } /* * Function adds new banner to database */ public function addNewBanner($data) { try { return $this->connection->insert($this->table,$data); } catch(Exception $e) { throw $e; } } public function addMultipleBanner($data) { try { return $this->connection->multiinsert($this->table,$data); } catch(Exception $e) { throw $e; } } /* * Function adds new banner to database */ public function updateBanner($data) { try { return $this->connection->update($this->table,$data); } catch(Exception $e) { throw $e; } } /* * Function deletes banner from the database */ public function deleteBanner($id) { try { return $this->connection->delete($this->table,array('id'=>$id)); } catch(Exception $e) { throw $e; } } }<file_sep><?php require_once('DBFactory.php'); class Model { var $connection; function __construct() { try { $json = file_get_contents(__DIR__ . "/../dbserver.json"); $storage = json_decode($json, true); if($storage['DB_STORAGE']=='mysql'){ $this->connection = DBFactory::createDB('mysql',$storage); } else { $this->connection = DBFactory::createDB('json',$storage); } } catch(Exception $e) { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } <file_sep><?php /* * Base class for Controllers */ class AdsController { public function getDeleteData() { $_DELETE = array(); parse_str(file_get_contents("php://input"), $_DELETE); return $_DELETE; } public function getPutData() { $_PUT = array(); parse_str(file_get_contents("php://input"), $_PUT); return $_PUT; } }<file_sep><?php /** * @package Adserver * @author <NAME> */ use \Jacwright\RestServer\RestException; require_once 'AdsController.php'; require_once 'HttpStatusCodes.php'; require_once 'Banner.php'; require_once 'Campaign.php'; class BannerController extends AdsController { /** * Gets sll banners info * * @url GET /api/banner/all */ public function getBanners() { try { $result = Banner::getAllBanners(); return $result; } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } /** * Gets banners by dimensions info * * @url GET /api/banner/$width/$height */ public function getBannersByDimensions() { try { $result = Banner::getBannersByDimensions($_GET); return $result; } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } /** * Inserts a new banner into the database * * @url POST /api/banner * @url PUT /api/banner */ public function addNewBanner() { $_PUT = $this->getPutData(); $data = isset($_PUT) ? $_PUT : $_POST; if (!isset($data)) { throw new RestException(HttpStatusCodes::BAD_REQUEST, "Missing required params"); } try { if (isset($_POST) && isset($data['width']) && filter_var($data['width'], FILTER_VALIDATE_INT) && filter_var($data['height'], FILTER_VALIDATE_INT) && isset($data['height']) && isset($data['name']) && isset($data['content'])) { return Banner::addNewBanner($data); } else if (isset($_PUT) && filter_var($data['id'], FILTER_VALIDATE_INT)) { return Banner::updateBanner($data); } else { throw new RestException(HttpStatusCodes::BAD_REQUEST, "Not valid data."); } http_response_code(HttpStatusCodes::CREATED); } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } /** * Inserts a new banner into the database * * @url DELETE /api/banner */ public function deleteBanner() { $_DELETE = $this->getDeleteData(); if (isset($_DELETE['id'])) { $id = $_DELETE['id']; } else { throw new RestException(HttpStatusCodes::BAD_REQUEST, "Missing required params"); } try { Banner::deleteBanner($id); } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } /** * Inserts a new banner into the database * * @url POST /api/campaignbanners */ public function addCampaignBanners() { $data = $_POST; if (!isset($data)) { throw new RestException(HttpStatusCodes::BAD_REQUEST, "Missing required params"); } try { $bannerDara = json_decode($data, true); $id = Campaign::addNewCampaign(array('name' => $bannerDara['name'])); foreach ($bannerDara['banners'] as $key => $values) { $bannerDara['banners'][$key]['campaign_id'] = $id; } Banner::addMultipleBanner($bannerDara['banners']); return array("success" => "Campaign Banner, Updated " . $id); http_response_code(HttpStatusCodes::CREATED); } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } } <file_sep><?php abstract class base_optimization { public $concrete_network_setting; /** determines optimization type. has to be set in sub classes*/ protected $opt_type; /** array mit allen Kampagnen die nicht durch die Filter gefallen sind */ protected $data; /** current campaign that is being checked/optimized */ public $row;//@@todo its better to change protected /** * @var MDB2_Driver_Mysql */ public $db; //@@todo its better to change protected /** rpc Objects */ protected $campObj, $campOptimization, $campLandingpages, $contCost; /** When did the optimization take place */ public $optimization_runtime; /** Posttracking Settings */ protected $period = '0'; protected $group = 'banner'; protected $type = 'html'; protected $debugmode = false; /** * Activates or deactivates debug mode * * @param boolean $mode */ public function setDebugMode($mode) { $this->debugmode = $mode; } public function __construct() { $this->campLandingpages = adition_base::getInstance('campaignlandingpages'); $this->campObj = adition_base::getInstance('campaigns'); $this->campOptimization = adition_base::getInstance('campaignoptimizations'); $this->contCost = adition_base::getInstance('contentunitcosts'); } public function get_posttracking_report() { $this->getRow();//@@todo getRow should be called as abstract method $pages = $this->campLandingpages->getAll(array('campaign_id' => $this->row['campaign_id'])); $landingpageids = array(); foreach ($pages as $page) { $landingpageids[] = $page['landingpage_id']; } $today = date('Y-m-d'); $this->get_start_date_for_post_report(); $params['campaign_ids'] = array($this->row['campaign_id']); $params['landingpage_ids'] = $landingpageids; $params['group'] = $this->group; $params['type'] = $this->type; $params['conversion'] = false; $period = null; $report = new soapreport(); $rows = $report->getReport( 'urn:Adition/Tracking/PostReport2', $this->row['postreport_startdate'], $today, $params, $this->row['network_id'], $params, $period, 'bw' ); $selected_countingspots = $this->getCountingspots(); $sums = array(); $newdata['rows'] = array(); $newdata['totalsum'] = array(); if (is_array($rows['days']) && !empty($selected_countingspots)) { $index = 0; //@@todo this loop can be avoid if we use table joins foreach ($rows['days'] as $date => $date_values) { $index += 1; // LandingpageID foreach ($date_values as $landingpage_id => $landingpage_values) { $landingpage_data = adition_base:: getInstance('landingpages')->getOne($landingpage_id); foreach ($landingpage_values as $countingspot_key => $countingspot_value) { // Check whether it is a selective counting spot if (@in_array($countingspot_key, $selected_countingspots)) { $countingspot_data = adition_base:: getInstance('countingspots')->getOne($countingspot_key); foreach ($countingspot_value as $cu_key => $cu_value) { $cu_data = adition_base:: getInstance('contentunits')->getOne($cu_key); $website = adition_base:: getInstance('websites')->getOne($cu_data['website_id']); foreach ($cu_value as $banner_id => $banner_value) { $banner_data = adition_base:: getInstance('banners')->getAll( array('id' => $banner_id, 'with_server' => false) ); $banner_data = $banner_data[0]; $campaignbanners = adition_base:: getInstance('campaignbanners')->getCampaigns($banner_data['id']); $campaign_id = $campaignbanners[$banner_data['id']][0]; //$campaign_costs = adition_base::getInstance('campaigncosts')->getOne($campaign_id); $newrow = array( 'date' => $date, 'landingpage_name' => $landingpage_data['name'], 'trackingspot_name' => $countingspot_data['name'], 'contentunit_name' => $cu_data['name'], 'contentunit_id' => $cu_data['id'], 'website_name' => $website['name'], 'website_id' => 'ID_' . $website['id'], 'banner_name' => $banner_data['name'], 'banner_id' => 'ID_' . $banner_data['id'], 'campaign_id' => $campaign_id, 'campaign_costs' => ''/* $campaign_costs */, ); $newrow['visits_clicks'] = $this->convertNumber($banner_value['visits']['clicks']); $sums[$newrow[$key]]['visits_clicks'] += $newrow['visits_clicks']; $newrow['visits_views'] = $this->convertNumber($banner_value['visits']['views']); $sums[$newrow[$key]]['visits_views'] += $newrow['visits_views']; $newrow['unique_clicks'] = $this->convertNumber($banner_value['unique']['clicks']); $sums[$newrow[$key]]['unique_clicks'] += $newrow['unique_clicks']; $newrow['unique_views'] = $this->convertNumber($banner_value['unique']['views']); $sums[$newrow[$key]]['unique_views'] += $newrow['unique_views']; $newrow['data_clicks'] = $this->convertNumber($banner_value['data']['clicks']); $sums[$newrow[$key]]['data_clicks'] += $newrow['data_clicks']; $newrow['data_views'] = $this->convertNumber($banner_value['data']['views']); $sums[$newrow[$key]]['data_views'] += $newrow['data_views']; $newdata['rows'][] = $newrow; } } } } } } } foreach ($sums as $sum) { foreach ($sum as $key => $value) { $totalsum[$key] += $value; } } $this->row['cpl_by_contentunit'] = $newdata['rows']; $this->row['cpl'] = $totalsum['unique_clicks'] + $totalsum['unique_views']; } protected function convertNumber($a) { if (!isset($a) or $a == null) { $a = 0; } return $a; } protected function replaceCampaign() { try { $this->set_priority_if_not_in_network_range(); $this->row['datetime'] = true; if (!$this->debugmode) { if (isset($this->row['campaign_data']['priority_hacked'])) { $this->row['campaign_data']['weight'] = $this->row['campaign_data']['priority']; $this->row['campaign_data']['priority'] = $this->row['campaign_data']['priority_hacked']; unset($this->row['campaign_data']['priority_hacked']); } foreach (array('priority', 'weight') as $keyToBeCasted) { if (isset($this->row['campaign_data'][$keyToBeCasted])) { $this->row['campaign_data'][$keyToBeCasted] = (int)$this->row['campaign_data'][$keyToBeCasted]; } } $this->campObj->replaceObj($this->row['campaign_data']); // Because the database field `object` is too small, // only relevant data should be saved into the `campaignoptimizationhistory` table //@@todo Write a new class for log and pass the entire row $data = array( 'order_name' => $this->row['order_name'], 'lastrun' => $this->row['lastrun'], 'company_name' => $this->row['company_name'], 'concrete_cost' => $this->row['concrete_cost'], 'type' => $this->row['type'], 'costs' => $this->row['costs'], 'costtype' => $this->row['costtype'], 'ecpm' => $this->row['ecpm'], 'new_priority' => $this->row['new_priority'], 'old_priority' => $this->row['old_priority'], 'calc_priority' => $this->row['calc_priority'], 'campaign_data' => array( 'id' => $this->row['campaign_data']['id'], 'priority' => $this->row['campaign_data']['priority'], 'order_id' => $this->row['campaign_data']['order_id'], 'name' => $this->row['campaign_data']['name'], 'type' => $this->row['campaign_data']['type'], 'views_total' => $this->row['campaign_data']['views_total'], 'clicks_total' => $this->row['campaign_data']['clicks_total'] ), 'report' => array( 'views' => $this->row['report']['views'], 'clicks' => $this->row['report']['clicks'] ), 'options' => array( 'ecpm' => array( 'costSelect' => $this->row['options']['ecpm']['costSelect'] ) ), 'network_id' => $this->row['network_id'], 'datetime' => $this->row['datetime'], 'log_msg' => $this->row['log_msg'] ); $this->writeLog($data); $this->post_replace_data(); } } catch (Exception $e) { error_log($e->getMessage()); } } //@@todo log can be moved to a seprate class protected function writeLog($data) { $logMsg = !empty($data['log_msg']) ? serialize($data['log_msg']) : null; $lastrun = $data['datetime'] ? $this->optimization_runtime : null; # Fixme go to rpc module // @comment database layer should be keep seprately $query = sprintf( 'INSERT INTO campaignoptimizationhistory ( `order_id`, `network_id`, `campaign_id`, `messages`, `object`, `lastrun`) VALUES (%s, %s, %s, %s, %s, %s)', $this->db->quote($data['campaign_data']['order_id'], 'integer'), $this->db->quote($data['network_id'], 'integer'), $this->db->quote($data['campaign_data']['id'], 'integer'), $this->db->quote($logMsg, 'text'), $this->db->quote(serialize($data), 'text'), $this->db->quote($lastrun, 'timestamp') ); $result = $this->db->exec($query); rpcMiddlewareStorageException::throwForMdb2Error($result); } # overwritten me in subclass protected function set_priority_if_not_in_network_range() { ; } # overwrite me in subclass protected function post_replace_data() { ; } protected function get_start_date_for_post_report() { if ($this->concrete_network_setting['runtime'] == 'lastrun') { if (strtotime($this->row['lastrun']) <= time() - (adReportConst::getReportConfig()->getSoapReportMaxDays() * 24 * 3600)) { $this->row['postreport_startdate'] = date('Y-m-d', time() - (adReportConst::getReportConfig()->getSoapReportMaxDays() * 24 * 3600)); } else { $this->row['postreport_startdate'] = $this->row['lastrun']; } } if ($this->concrete_network_setting['runtime'] == 'campaign') { if (strtotime($this->row['runtimes'][sizeof($this->row['runtimes']) - 1]['startdate']) <= time() - (adReportConst::getReportConfig()->getSoapReportMaxDays() * 24 * 3600)) { $this->row['postreport_startdate'] = date('Y-m-d', time() - (adReportConst::getReportConfig()->getSoapReportMaxDays() * 24 * 3600)); } else { $this->row['postreport_startdate'] = $this->row['runtimes'][sizeof($this->row['runtimes']) - 1]['startdate']; } } } } ?> <file_sep><?php /** * @package Adserver * @author <NAME> */ require_once(__DIR__ . '/../model/BannerModel.php'); class BannerUtil { public static function getAllBanners() { $model = new BannerModel(); try { $rows = $model->getAllBanners(); return $rows; } catch (Exception $e) { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } public static function getBannersByDimensions($data) { $model = new BannerModel(); try { $rows = $model->getBannersByDimensions($data); return $rows; } catch (Exception $e) { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } public static function addNewBanner($data) { $model = new BannerModel(); try { return $model->addNewBanner($data); } catch (Exception $e) { if ($e->getCode() != 0) { throw $e; } else { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } public static function addMultipleBanner($data) { $model = new BannerModel(); try { return $model->addMultipleBanner($data); } catch (Exception $e) { if ($e->getCode() != 0) { throw $e; } else { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } public static function updateBanner($data) { $model = new BannerModel(); try { return $model->updateBanner($data); } catch (Exception $e) { if ($e->getCode() != 0) { throw $e; } else { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } public static function deleteBanner($id) { $model = new BannerModel(); try { return $model->deleteBanner($id); } catch (Exception $e) { if ($e->getCode() != 0) { throw $e; } else { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } } <file_sep><?php /** * @package Adserver * @author <NAME> */ use \Jacwright\RestServer\RestException; require_once 'AdsController.php'; require_once 'HttpStatusCodes.php'; require_once 'Campaign.php'; class CampaignController extends AdsController { /** * Gets all campaign info * * @url GET /api/campaign/all */ public function getCampaigns() { try { $result = Campaign::getAllCampaigns(); return $result; } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } /** * Inserts a new campaign into the database * * @url POST /api/campaign * @url PUT /api/campaign */ public function addNewCampaign() { $_PUT = $this->getPutData(); $data = isset($_PUT)?$_PUT:$_POST; if (!isset($data)) { throw new RestException(HttpStatusCodes::BAD_REQUEST, "Missing required params"); } try { if(isset($_PUT['id']) && filter_var($data['id'], FILTER_VALIDATE_INT)) { $id = Campaign::updateCampaign($_PUT); return array("success" => "Campaign Updated " . $id); }else if(isset($_POST['name'])){ $id = Campaign::addNewCampaign($data); return array("success" => "Campaign Added " . $id); }else{ throw new RestException(HttpStatusCodes::BAD_REQUEST, "Not valid data."); } } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } /** * delete campaign into the database * * @url DELETE /api/campaign */ public function deleteCampaign() { $_DELETE = $this->getDeleteData(); if (isset($_DELETE['id'])) { $id = $_DELETE['id']; } else { throw new RestException(HttpStatusCodes::BAD_REQUEST, "Missing required params"); } try{ Campaign::deleteCampaign($id); } catch (Exception $e) { throw new RestException($e->getCode(), $e->getMessage()); } } }<file_sep><?php /** * @package Adserver * @author <NAME> */ require_once(__DIR__ . '/../model/CampaignModel.php'); class CampaignUtil { public static function getAllCampaigns() { $model = new CampaignModel(); try { $rows = $model->getAllCampaigns(); return $rows; } catch (Exception $e) { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } public static function addNewCampaign($data) { $model = new CampaignModel(); try { return $model->addNewCampaign($data); } catch (Exception $e) { if ($e->getCode() != 0) { throw $e; } else { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } public static function updateCampaign($data) { $model = new CampaignModel(); try { return $model->updateCampaign($data); } catch (Exception $e) { if ($e->getCode() != 0) { throw $e; } else { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } public static function deleteCampaign($id) { $model = new CampaignModel(); try { return $model->deleteCampaign($id); } catch (Exception $e) { if ($e->getCode() != 0) { throw $e; } else { throw new Exception($e->getMessage(), HttpStatusCodes::INTERNAL_SERVER_ERROR); } } } }
a1c2b0c8a258acc47b687dc440f2814da794d3b4
[ "PHP" ]
17
PHP
snehaj/acr
9dc2f9af2375798670cd5baeb87b33c637b1d7a2
b749640563dc3ed562814c8f16af5cd98f45d601
refs/heads/master
<repo_name>18722480995/naizhan<file_sep>/lionfish_comshop/moduleA/components/img-box/img-box.js var app = getApp(); Component({ properties: { item: { type: Object } }, methods: { agree: function() { var e = this, a = this.data.item, t = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "recipe.fav_recipe_do", token: t, id: a.id }, dataType: "json", success: function(t) { 0 == t.data.code ? (wx.showToast({ title: "已喜欢~", icon: "none" }), a.fav_count = t.data.fav_count, a.has_fav = 1, e.setData({ item: a })) : 1 == t.data.code ? e.triggerEvent("needAuth") : 2 == t.data.code && (a.fav_count = t.data.fav_count, a.has_fav = 0, e.setData({ item: a }), wx.showToast({ title: "取消喜欢~", icon: "none" })) } }) }, goDetails: function(t) { var e = t.currentTarget.dataset.id || "", a = "/lionfish_comshop/moduleA/menu/details?id=" + e; 3 < getCurrentPages().length ? e && wx.redirectTo({ url: a }) : e && wx.navigateTo({ url: a }) } } });<file_sep>/lionfish_comshop/moduleA/video/detail.js var app = getApp(); Page({ data: { is_heng: 1, rushList: [], current: 0 }, onLoad: function(t) { var o = t.id || ""; o ? (this.getData(o), this.get_goods_details(o)) : wx.showModal({ title: "提示", content: "参数错误", showCancel: !1, success: function(t) { t.confirm && wx.redirectTo({ url: "/lionfish_comshop/pages/index/index" }) } }) }, onShow: function() {}, goDetails: function() { var t = this.data.goods.id || ""; t && wx.redirectTo({ url: "/lionfish_comshop/pages/goods/goodsDetail?id=" + t }) }, get_goods_details: function(t) { var e = this; if (!t) return wx.hideLoading(), wx.showModal({ title: "提示", content: "参数错误", showCancel: !1, confirmColor: "#F75451", success: function(t) { t.confirm && wx.redirectTo({ url: "/lionfish_comshop/pages/index/index" }) } }), !1; var o = wx.getStorageSync("token"), a = wx.getStorageSync("community").communityId || ""; app.util.request({ url: "entry/wxapp/index", data: { controller: "goods.get_goods_detail", token: o, id: t, community_id: a }, dataType: "json", success: function(t) { wx.hideLoading(); var o = t.data.data && t.data.data.goods || ""; o && 0 != o.length && "" != Object.keys(o) || wx.showModal({ title: "提示", content: "该商品不存在,回首页", showCancel: !1, confirmColor: "#F75451", success: function(t) { t.confirm && wx.switchTab({ url: "/lionfish_comshop/pages/index/index" }) } }), e.currentOptions = t.data.data.options, e.setData({ goods: o, options: t.data.data.options, order: { goods_id: t.data.data.goods.goods_id, pin_id: t.data.data.pin_id }, share_title: o.share_title, goods_image: t.data.data.goods_image }) } }) }, getData: function(a) { var t = wx.getStorageSync("token"), i = this, o = wx.getStorageSync("community"); app.util.request({ url: "entry/wxapp/index", data: { controller: "index.load_gps_goodslist", token: t, pageNum: 1, head_id: o.communityId, per_page: 1e4, is_video: 1 }, dataType: "json", success: function(t) { if (0 == t.data.code) { var o = t.data.list || [], e = o.findIndex(function(t) { return t.actId == a }); i.setData({ rushList: o, current: e }) } } }) }, changeSubject: function(t) { var o = this.data.rushList; if (t < 0 || o.length <= 1) wx.showToast({ title: "没有上一个视频了~", icon: "none", duration: 2e3 }); else { if (console.log(t), t > o.length - 1) return void wx.showToast({ title: "没有下一个视频了~", icon: "none", duration: 2e3 }); t = t || 0, this.setData({ current: t }), this.get_goods_details(o[t].actId) } }, pre: function() { this.changeSubject(1 * this.data.current - 1) }, next: function() { this.changeSubject(1 * this.data.current + 1) }, onShareAppMessage: function() { var t = wx.getStorageSync("community"), o = this.data.goods, e = (t.communityId, this.data.share_title), a = wx.getStorageSync("member_id"), i = "lionfish_comshop/moduleA/video/detail?id=" + o.id + "&share_id=" + a, n = this.data.goods.goods_share_image; return console.log("商品分享地址:", i), { title: e, path: i, imageUrl: n, success: function(t) {}, fail: function(t) {} } }, onShareTimeline: function () { var t = wx.getStorageSync("community"), o = this.data.goods, e = (t.communityId, this.data.share_title), a = wx.getStorageSync("member_id"), i = "id=" + o.id + "&share_id=" + a, n = this.data.goods.goods_share_image; return { title: e, query: i, imageUrl: n, } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/pages/test-functional-page/test-functional-page.js "use strict"; Component({ options: { styleIsolation: "page-apply-shared" } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/count-time/count-time.js "use strict"; var t = function(t) { if (isNaN(t)) return "-"; if (t <= 0) return "0"; var i = t, e = parseInt(i / 86400); i -= 86400 * e; var n = parseInt(i / 3600); i -= 3600 * n; var o = parseInt(i / 60); return i -= 60 * o, e > 0 ? e + "天" + n + "小时" : n > 0 ? n + "小时" + o + "分" : o > 0 ? o + "分" : i + "秒" }, i = null, e = 100; Component({ properties: { countdownTime: { type: Number }, countdownTimeContent: { type: String, value: "" }, isSubscribe: { type: Boolean }, name: { type: String, value: "" }, from: { type: String, value: "" } }, lifetimes: { attached: function() { "pusher" === this.data.from && (e = this.data.countdownTime, this.initCountdownTime()) }, detached: function() { "pusher" === this.data.from && clearTimeout(i) } }, observers: { countdownTime: function() { "pusher" === this.data.from && (e = this.data.countdownTime) < 864e4 && this.initCountdownTime() } }, data: { countdownTimeWording: "" }, methods: { initCountdownTime: function() { var n = this; if (clearTimeout(i), e > 0) { var o = 60; e <= 70 ? o = 1 : e <= 80 ? o = 5 : e > 86400 && (o = 1800), this.setData({ countdownTimeWording: t(e) }), i = setTimeout(function() { e -= o, n.initCountdownTime() }, 1e3 * o) } else { if (0 === this.data.countdownTime) return; this.setData({ countdownTime: 0 }) } }, clickSubscribe: function() { this.triggerEvent("customevent", { confirmSubscribe: !0, isSubscribe: this.data.isSubscribe }) }, clickInitateLive: function() { this.triggerEvent("InitateLive", {}) } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/pages/address-preview/address-preview.js "use strict"; var e = function(e) { return e && e.__esModule ? e : { default: e } }(require("../../utils/wxapi.js")), t = "denyAuthorizeLotteryAddress-" + (wx.getAccountInfoSync().miniProgram.appId || ""); Component({ options: { styleIsolation: "page-apply-shared" }, properties: { livePlayerOptions: String }, data: { address: "", district: "", phone: "", postcode: "", receive_name: "", showAddressPreview: !0 }, methods: { onLoad: function() { var e = JSON.parse(decodeURIComponent(this.data.livePlayerOptions)); this.setData({ weapp_name: e.weapp_name, address: e.address, district: e.district, phone: e.phone, postcode: e.postcode, receive_name: e.receive_name }) }, modifyLotteryAddress: function() { var o = this; e. default.chooseAddressForPlugin().then(function(e) { var t = { address: e && e.provinceName + " " + e.cityName + " " + e.countyName || "", district: e && e.detailInfo || "", phone: e && e.telNumber || "", postcode: e && e.postalCode || "", receive_name: e && e.userName || "" }; o.setData(t), o.getOpenerEventChannel().emit("acceptDataFromAddressPreviewPage", t) }). catch (function(a) { console.error("选择收货地址 fail", a); var n = wx.getStorageSync(t); a.errMsg && a.errMsg.includes("cancel") || (n ? wx.showModal({ content: "需要允许" + o.data.weapp_name + "小程序获取你的通信地址", confirmText: "前往设置", success: function(t) { t.confirm && e. default.openSettingForPlugin() } }) : wx.setStorageSync(t, !0)) }) } } });<file_sep>/lionfish_comshop/pages/order/shareOrderInfo.js var app = getApp(), status = require("../../utils/index.js"); Page({ data: { order: [], groupInfo: { group_name: "社区", owner_name: "团长" } }, onLoad: function(a) { var e = this; status.setGroupInfo().then(function(a) { e.setData({ groupInfo: a }) }); var o = a.order_id || 0; null != o && o || wx.redirectTo({ url: "/lionfish_comshop/pages/index/index" }), wx.showLoading(), this.getData(o) }, onShow: function() {}, getData: function(a) { var i = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "order.order_share_info", id: a, is_share: 1 }, dataType: "json", method: "POST", success: function(a) { if (wx.hideLoading(), 0 == a.data.code) { var e = a.data.data, o = e.order_info || ""; if (o) { var t = o.shipping_name, r = o.shipping_address; t = i.formatData(t, 2), r = i.formatData(r, 6), e.order_info.shipping_name = t, e.order_info.shipping_address = r } i.setData({ order: e }) } else app.util.message(a.data.msg || "请求出错", "", "error") } }) }, goGoodsDetails: function(a) { var e = a.currentTarget.dataset.id || 0, o = this.data.order.order_info.head_id || ""; wx.navigateTo({ url: "/lionfish_comshop/pages/goods/goodsDetail?id=" + e + "&community_id=" + o }) }, formatData: function(a, e) { return e = 3 < (a += "").length ? e : 1, a.length > e ? a.substr(0, a.length - e) + new Array(e + 1).join("*") : a } });<file_sep>/lionfish_comshop/moduleA/menu/subcate.js var app = getApp(); Page({ data: { subCate: [] }, onLoad: function(t) { this.getCate() }, getCate: function() { var e = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "recipe.get_recipe_categorylist" }, dataType: "json", success: function(t) { if (0 == t.data.code) { var a = t.data.data || []; e.setData({ subCate: a }) } } }) }, goList: function(t) { var a = t.currentTarget.dataset.id || "", e = t.currentTarget.dataset.name || ""; wx.navigateTo({ url: "/lionfish_comshop/moduleA/menu/list?gid=" + a + "&name=" + e }) } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/pages/report-room/report-room-detail.js "use strict"; var e = require("../../wxlive-components/logic/ui.js"); Component({ options: { styleIsolation: "page-apply-shared" }, properties: { livePlayerOptions: String }, data: { uiPagePaddingTop: 0, roomImg: "", roomTitle: "", roomTime: "", weappName: "", showSubmitReport: !1, reportItems: [{ name: "低俗色情", value: "value0", checked: !1 }, { name: "非法政治", value: "value1", checked: !1 }, { name: "出售假冒禁售商品", value: "value2", checked: !0 }, { name: "引导线下或其他平台交易", value: "value3", checked: !1 }, { name: "侵权盗播", value: "value4", checked: !1 }, { name: "长期空镜或换人直播", value: "value5", checked: !1 }, { name: "其它", value: "value6", checked: !1 }], uploadFileNum: 0 }, methods: { onLoad: function() { (0, e.setNavFontColor)("#f7f7f7"); var t = JSON.parse(decodeURIComponent(this.data.livePlayerOptions)); this.setData({ roomImg: t.roomImg, roomTitle: t.roomTitle, roomTime: t.roomTime, weappName: t.weappName, selectFile: this.selectFile.bind(this), uploadFile: this.uploadFile.bind(this) }), this.countTopPadding() }, onShow: function() { this.uiGetPagePaddingTop() }, countTopPadding: function() { var e = wx.getSystemInfoSync(); this.setData({ statusBarHeight: e.statusBarHeight }) }, uiGetPagePaddingTop: function() { this.setData({ uiPagePaddingTop: (0, e.getPaddingTop)() }) }, bindReportContentInput: function(e) { var t = e.detail.value; t ? this.setData({ showSubmitReport: !0, reportContent: t }) : this.setData({ showSubmitReport: !1 }) }, uploadError: function(e) { console.log("upload error", e.detail) }, uploadSuccess: function(e) { console.log("upload success", e.detail) }, selectFile: function(e) { console.log("files", e) }, uploadFile: function(e) { return console.log("upload files", e), new Promise(function(e, t) { setTimeout(function() { t("some error") }, 1e3) }) }, submitReport: function() { this.getOpenerEventChannel().emit("acceptDataFromReportRoomDetailPage", { reportContent: this.data.reportContent }), wx.navigateTo({ url: "../report-status/report-status?path=reportRoomPage" }) } } });<file_sep>/lionfish_comshop/moduleA/solitaire/groupIndex.js var _extends = Object.assign || function(t) { for (var a = 1; a < arguments.length; a++) { var e = arguments[a]; for (var o in e) Object.prototype.hasOwnProperty.call(e, o) && (t[o] = e[o]) } return t }, app = getApp(); Page({ data: { list: [], loadText: "加载中...", noData: 0, loadMore: !0, keyword: "" }, page: 1, onLoad: function(t) { this.getData() }, onShow: function() {}, getData: function() { var o = this; wx.showLoading(); var t = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_head_solitairelist", token: t, page: this.page, keyword: this.data.keyword }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var a = {}, e = t.data.data; e.length < 20 && (a.noMore = !0), e = o.data.list.concat(e), o.page++, o.setData(_extends({ list: e }, a)) } else { if (1 != t.data.code) return 2 == t.data.code ? void app.util.message("您还未登录", "switchTo:/lionfish_comshop/pages/index/index", "error") : void app.util.message(t.data.msg, "switchTo:/lionfish_comshop/pages/index/index", "error"); 1 == o.page && o.setData({ noData: 1 }), o.setData({ loadMore: !1, noMore: !1, loadText: "没有更多记录了~" }) } } }) }, goResult: function(t) { var a = t.detail.value || "", e = this; this.page = 1, this.setData({ list: [], loadText: "加载中...", noData: 0, loadMore: !0, keyword: a }, function() { e.getData() }) }, goDetails: function(t) { var a = t ? t.currentTarget.dataset.id : ""; if (a) { var e = "/lionfish_comshop/moduleA/solitaire/groupDetails?id=" + a; 3 < getCurrentPages().length ? wx.redirectTo({ url: e }) : wx.navigateTo({ url: e }) } }, onPullDownRefresh: function() {}, onReachBottom: function() { if (!this.data.loadMore) return !1; this.getData() } });<file_sep>/lionfish_comshop/pages/order/refund.js var app = getApp(); Page({ data: { xarray: ["点击选择退款理由", "商品有质量问题", "没有收到货", "商品少发漏发发错", "商品与描述不一致", "收到商品时有划痕或破损", "质疑假货", "其他"], index: 0, refund_type: 1, refund_imgs: [], complaint_mobile: "", refund_thumb_imgs: [], complaint_desc: "", order_id: 0, order_status_id: -1, complaint_name: "", ref_id: 0, complaint_money: 0, refund_money: 0, selArr: [] }, canRefund: !0, onLoad: function(e) { var t = e.id, a = e.order_goods_id, r = e.ref_id, n = this; this.setData({ order_id: t || 0, order_goods_id: a || 0, ref_id: r || 0 }, function() { n.getData() }) }, bindPickerChange: function(e) { this.setData({ index: e.detail.value }) }, choseImg: function() { var o = this; if (3 <= this.data.refund_imgs.length) return wx.showToast({ title: "最多三张图片", icon: "success", duration: 1e3 }), !1; wx.chooseImage({ count: 1, sizeType: ["original", "compressed"], sourceType: ["album", "camera"], success: function(e) { var t = e.tempFilePaths; wx.showLoading({ title: "上传中" }), wx.uploadFile({ url: app.util.url("entry/wxapp/index", { m: "lionfish_comshop", controller: "goods.doPageUpload" }), filePath: t[0], name: "upfile", formData: { name: t[0] }, header: { "content-type": "multipart/form-data" }, success: function(e) { wx.hideLoading(); var t = JSON.parse(e.data), a = t.image_thumb, r = t.image_o, n = o.data.refund_imgs, i = o.data.refund_thumb_imgs; n.push(r), i.push(a), o.setData({ refund_thumb_imgs: i, refund_imgs: n }) } }) } }) }, chose_type: function(e) { var t = e.currentTarget.dataset.rel; this.setData({ refund_type: t }) }, cancle_img: function(e) { var t = e.currentTarget.dataset.sr, a = 0, r = this.data.refund_imgs, n = this.data.refund_thumb_imgs, i = [], o = []; for (var s in n) n[s] == t ? (console.log("find"), a = s) : o.push(n[s]); for (var s in r) s != a && i.push(r[s]); this.setData({ refund_thumb_imgs: o, refund_imgs: i }), console.log(o.length), console.log(i.length) }, wenti_input: function(e) { var t = e.detail.value; this.setData({ complaint_desc: t }) }, mobile_input: function(e) { var t = e.detail.value; this.setData({ complaint_mobile: t }) }, name_input: function(e) { var t = e.detail.value; this.setData({ complaint_name: t }) }, refund_money_input: function(e) { var t = parseFloat(e.detail.value), a = this.data.refund_money, r = {}; a < t && (wx.showToast({ title: "最大退款金额为" + a, icon: "none", duration: 1e3 }), t = a, r.refund_money = a), r.complaint_money = t || 0, this.setData(r) }, sub_refund: function() { var t = this; if (t.canRefund) { var e = this.data, a = e.index, r = e.xarray, n = e.order_id, i = e.order_goods_id, o = e.refund_type, s = e.refund_imgs, d = e.complaint_desc, u = e.complaint_mobile, _ = e.total, c = e.complaint_name, l = e.complaint_money, f = e.ref_id, m = e.real_refund_quantity; if (l = parseFloat(l), m <= 0) return this.errorToast("请选择退款商品"), !1; if (0 == a) return this.errorToast("请选择问题类型"), !1; var p = r[a]; if (l <= 0) return this.errorToast("请填写正确退款金额"), !1; if (_ < l && (l = _), "" == d) return this.errorToast("请填写正确问题描述"), !1; if ("" == c) return this.errorToast("请填写正确联系人"), !1; if ("" == u) return this.errorToast("请填写正确手机号"), !1; if (!/^(((13[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(u)) return this.errorToast("请填写正确手机号"), !1; t.canRefund = !1; var h = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "afterorder.refund_sub", token: h, ref_id: f, order_id: n, order_goods_id: i, complaint_type: o, complaint_images: s, complaint_desc: d, complaint_mobile: u, complaint_reason: p, complaint_money: l, complaint_name: c, real_refund_quantity: m }, method: "POST", dataType: "json", success: function(e) { if (wx.hideLoading(), t.canRefund = !0, 3 == e.data.code) wx.showToast({ title: "未登录", icon: "loading", duration: 1e3 }); else { if (0 == e.data.code) return void wx.showToast({ title: e.data.msg, icon: "success", duration: 1e3 }); wx.showToast({ title: "申请成功", icon: "success", duration: 3e3, success: function(e) { wx.redirectTo({ url: "/lionfish_comshop/pages/order/order?id=" + t.data.order_id }) } }) } } }) } }, errorToast: function(e) { wx.showToast({ title: e, icon: "none", duration: 1e3 }) }, getData: function() { var e = wx.getStorageSync("token"), b = this, t = this.data, a = t.order_id, r = t.order_goods_id, n = t.ref_id; app.util.request({ url: "entry/wxapp/index", data: { controller: "afterorder.get_order_money", token: e, order_id: a, order_goods_id: r, ref_id: n }, dataType: "json", success: function(e) { if (1 == e.data.code) { var t = e.data, a = t.order_goods, r = t.order_status_id, n = t.refund_image, i = t.refund_info, o = t.shipping_name, s = t.shipping_tel, d = t.total, u = b.data.xarray, _ = i.ref_name, c = u.findIndex(function(e) { return e == _ }); c = c <= 0 ? 0 : c; var l = i.ref_description, f = i.ref_mobile, m = i.complaint_name, p = i.ref_money, h = a.quantity, g = a.has_refund_quantity, y = a.has_refund_money, v = new Array(parseInt(h)); g = parseInt(g); for (var x = 0; x < v.length; x++) v[x] = g <= x ? { isselect: !0, isrefund: !1 } : { isselect: !0, isrefund: !0 }; var w = (1 * d - 1 * y).toFixed(2), T = parseInt(h) - g; b.setData({ order_goods: a, order_status_id: r, refund_image: n, refund_info: i, shipping_name: o, shipping_tel: s, total: w, index: c || 0, complaint_desc: l || "", complaint_mobile: f || s, complaint_name: m || o, complaint_money: p || w, refund_money: p || w, selArr: v, real_refund_quantity: T }) } else e.data.code } }) }, goodsselect: function(e) { var t = e.target.dataset.idx, a = this.data, r = a.selArr, n = a.order_goods, i = a.total, o = { isselect: !r[t].isselect, isrefund: r[t].isrefund }; r[t] = o; var s = 0; r.forEach(function(e) { e.isselect && !e.isrefund && (s += 1) }); var d = n.price * s; i < d && (d = i), this.setData({ selArr: r, real_refund_quantity: s, complaint_money: d, refund_money: d }) } });<file_sep>/lionfish_comshop/moduleA/solitaire/groupDetails.js var _Page, _extends = Object.assign || function(t) { for (var e = 1; e < arguments.length; e++) { var o = arguments[e]; for (var a in o) Object.prototype.hasOwnProperty.call(o, a) && (t[a] = o[a]) } return t }; function _defineProperty(t, e, o) { return e in t ? Object.defineProperty(t, e, { value: o, enumerable: !0, configurable: !0, writable: !0 }) : t[e] = o, t } var app = getApp(); Page((_defineProperty(_Page = { data: { showGoodsModal: !1, showCommentModal: !1, pid: 0, showShareModal: !1, list: [], loadText: "加载中...", noData: 0, loadMore: !0, orderList: [], noOrderMore: !1, noOrderData: 0 }, imagePath: "", options: "", page: 1, orderPage: 1, onLoad: function(t) { (this.options = t).id || 0 || app.util.message("参数错误", "redirect:/lionfish_comshop/moduleA/solitaire/groupIndex", "error") }, initFn: function() { var t = this, e = this.options && this.options.id || 0; this.page = 1, this.setData({ list: [], loadText: "加载中...", noData: 0, loadMore: !0 }, function() { e && t.getData(e), t.getCommentList() }) }, onShow: function() { var t = this.options && this.options.id || 0; t && this.getData(t), this.getCommentList(), this.getOrderList() }, onHide: function() { this.setData({ clearTime: !0 }) }, getData: function(t) { var e = wx.getStorageSync("token"), p = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_solitaire_detail", id: t, token: e, is_head: 1 }, dataType: "json", success: function(t) { if (0 != t.data.code) return 2 == t.data.code ? void app.util.message("您还未登录", "switchTo:/lionfish_comshop/pages/index/index", "error") : void app.util.message(t.data.msg, "redirect:/lionfish_comshop/moduleA/solitaire/groupIndex", "error"); var e = t.data, o = e.head_data, a = e.soli_info, i = e.solitaire_target, n = e.solitaire_target_takemember, s = e.solitaire_target_takemoney, r = e.solitaire_target_type, d = 1 * s - 1 * a.soli_total_money, l = 1 * n - 1 * a.order_count; p.setData({ community: o || "", soli_info: a, solitaire_target: i, solitaire_target_takemember: n, solitaire_target_takemoney: s, solitaire_target_type: r, diffMoney: d, diffMember: l, clearTime: !1 }, function() { p.drawImg(o, a) }) } }) }, showImgPrev: function(t) { var e = t ? t.currentTarget.dataset.idx : "", o = this.data.soli_info.images_list || []; wx.previewImage({ current: o[e], urls: o }) }, handleGoodsModal: function() { this.setData({ showGoodsModal: !this.data.showGoodsModal }) }, handleCommentModal: function() { this.setData({ showCommentModal: !this.data.showCommentModal, pid: 0 }) }, subComment: function(t) { var e = this.data, l = e.soli_info, p = e.pid, c = l.id || "", h = t.detail.value.content || ""; if ("" != h) { var g = this, o = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.sub_solipost", soli_id: c, content: h, pid: p, token: o }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data, o = e.post_id, a = e.cur_time, i = wx.getStorageSync("userInfo"), n = g.data.list; if (0 != p) { var s = { id: o, pid: p, username: i.nickName, content: h }, r = n.findIndex(function(t) { return t.id == p }); - 1 !== r && n[r].reply.push(s) } else { var d = { id: o, soli_id: c, pid: p, username: i.nickName, avatar: i.avatarUrl, content: h, fav_count: 0, addtime: a, reply: [], is_agree: !1 }; n.unshift(d) } l.comment_total = 1 * l.comment_total + 1, g.setData({ soli_info: l, list: n, content: "", showCommentModal: !1, noData: 0 }), app.util.message(t.data.msg || "留言成功", "", "success") } else app.util.message(t.data.msg || "留言失败", "", "error") } }) } else wx.showToast({ title: "请输入内容", icon: "none" }) }, replyComment: function(t) { var e = t.currentTarget.dataset.id || ""; this.setData({ showCommentModal: !this.data.showCommentModal, pid: e }) }, deleteComment: function(t) { var n = this, o = t.currentTarget.dataset.id || "", s = t.currentTarget.dataset.idx || ""; o && wx.showModal({ title: "操作提示", content: "确认删除此留言?", confirmColor: "#ff5041", success: function(t) { if (t.confirm) { wx.showLoading({ title: "删除中..." }); var e = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.delete_comment", id: o, token: e }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = n.data, o = e.list, a = e.soli_info; o.splice(s, 1); var i = !1; 0 == o.length && (i = !0), a.comment_total = 1 * a.comment_total - 1, n.setData({ list: o, soli_info: a, noData: i }), wx.showToast({ title: t.data.msg || "删除成功", icon: "none" }) } else { if (2 == t.data.code) return void app.util.message("您还未登录", "switchTo:/lionfish_comshop/pages/index/index", "error"); app.util.message(t.data.msg || "删除失败", "", "error") } } }) } } }) }, favComment: function(t) { var a = this, e = this.data.soli_info.id || "", o = t ? t.currentTarget.dataset.post_id : "", i = t ? t.currentTarget.dataset.idx : 0, n = wx.getStorageSync("token"); o && app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.fav_soli_post", soli_id: e, post_id: o, token: n }, dataType: "json", success: function(t) { if (0 == t.data.code) if (1 == t.data.do) { var e = a.data.list; e[i].is_agree = !0, e[i].fav_count = 1 * e[i].fav_count + 1, a.setData({ list: e }) } else { var o = a.data.list; o[i].is_agree = !1, o[i].fav_count = 1 * o[i].fav_count - 1, a.setData({ list: o }) } else 1 == t.data.code ? a.setData({ needAuth: !0, showAuthModal: !0 }) : wx.showToast({ title: t.data.msg || "点赞失败", icon: "none" }) } }) }, endSolitaire: function(t) { var o = this, a = o.data.soli_info, i = a.id; i && wx.showModal({ title: "操作提示", content: "确认终止此接龙吗?", confirmColor: "#ff5041", success: function(t) { if (t.confirm) { wx.showLoading({ title: "提交中..." }); var e = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.end_solitaire", id: i, token: e }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) a.end = 1, o.setData({ soli_info: a }), wx.showToast({ title: t.data.msg || "接龙已终止", icon: "none" }); else { if (2 == t.data.code) return void app.util.message("您还未登录", "switchTo:/lionfish_comshop/pages/index/index", "error"); app.util.message(t.data.msg || "操作失败", "", "error") } } }) } } }) }, drawImg: function(t, e) { var o = e.images_list, a = e.qrcode_image, i = e.content.replace(/<\/?.+?>/g, ""), n = [], s = 300; o.length && (n.push({ type: "image", url: o[0], css: { width: "442px", height: "300px", top: "230px", left: "36px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "", shadow: "", mode: "scaleToFill" } }), s = 0), this.setData({ template: { width: "514px", height: 710 - s + "px", background: "#fff", views: [{ type: "image", url: t.avatar, css: { width: "46px", height: "46px", top: "25px", left: "36px", rotate: "0", borderRadius: "3px", borderWidth: "", borderColor: "#000000", shadow: "", mode: "scaleToFill" } }, { type: "text", text: t.head_name, css: { color: "#000000", background: "", width: "385px", height: "20.02px", top: "30px", left: "96px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "14px", fontWeight: "bold", maxLines: "1", lineHeight: "20.202000000000005px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: t.community_name, css: { color: "#999999", background: "", width: "385px", height: "17.16px", top: "52px", left: "96px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "12px", fontWeight: "normal", maxLines: "1", lineHeight: "17.316000000000003px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: i, css: { color: "#666666", background: "", width: "442px", height: "52.181999999999995px", top: "158px", left: "36px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "18px", fontWeight: "normal", maxLines: "2", lineHeight: "25.974000000000004px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: e.solitaire_name, css: { color: "#000000", background: "", width: "442px", height: "42.89999999999999px", top: "95px", left: "36px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "30px", fontWeight: "normal", maxLines: "1", lineHeight: "43.290000000000006px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: "一群人正在赶来接龙", css: { color: "#999999", background: "", width: "442px", height: "22.88px", top: 595 - s + "px", left: "204px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "16px", fontWeight: "normal", maxLines: "2", lineHeight: "23.088000000000005px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: "长按识别或扫码参与", css: { color: "#999999", background: "", width: "442px", height: "22.88px", top: 630 - s + "px", left: "204px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "16px", fontWeight: "normal", maxLines: "2", lineHeight: "23.088000000000005px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "image", url: a, css: { width: "120px", height: "120px", top: 560 - s + "px", left: "356px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", mode: "scaleToFill" } }].concat(n) } }) }, onImgOK: function(t) { this.imagePath = t.detail.path, this.setData({ image: this.imagePath }) }, saveImage: function() { var e = this; wx.saveImageToPhotosAlbum({ filePath: this.imagePath, success: function(t) { e.setData({ showShareModal: !1 }), wx.showToast({ title: "保存成功!" }) }, fail: function(t) { wx.showToast({ title: "保存失败,请重试!", icon: "none" }) } }) }, handleShareModal: function() { this.setData({ showShareModal: !this.data.showShareModal }) } }, "handleGoodsModal", function(t) { if (this.data.showGoodsModal) this.setData({ showGoodsModal: !1, goodsModalList: [] }); else { var e = t ? t.currentTarget.dataset.idx : "", o = this.data.orderList[e].goodslist || []; this.setData({ showGoodsModal: !0, goodsModalList: o }) } }), _defineProperty(_Page, "getCommentList", function() { var a = this, t = this.options && this.options.id || 0, e = wx.getStorageSync("token"); wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_comment_list", page: this.page, token: e, id: t }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = {}, o = t.data.data; o.length < 20 && (e.noMore = !0), o = a.data.list.concat(o), a.page++, a.setData(_extends({ list: o }, e)) } else 1 == t.data.code && (1 == a.page && a.setData({ noData: 1 }), a.setData({ loadMore: !1, noMore: !1, loadText: "没有更多记录了~" })) } }) }), _defineProperty(_Page, "onReachBottom", function() { if (!this.data.loadMore) return !1; this.getCommentList() }), _defineProperty(_Page, "getOrderList", function() { var n = this, t = this.options && this.options.id || 0; wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_soli_order_list", page: this.orderPage, id: t, size: 5 }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = {}, o = t.data.data; o.length < 5 && (e.noOrderMore = !0); var a = n.data.orderList.concat(o); n.orderPage++, n.setData(_extends({ orderList: a }, e)) } else if (1 == t.data.code) { var i = {}; 1 == n.orderPage && (i.noOrderData = 1), n.setData(_extends({ noOrderMore: !0 }, i)) } } }) }), _defineProperty(_Page, "getMoreOrder", function() { this.data.noOrderMore || this.getOrderList() }), _defineProperty(_Page, "onShareAppMessage", function() { var t = wx.getStorageSync("member_id") || "", e = this.data.soli_info || ""; return { title: e.solitaire_name || "", path: "lionfish_comshop/moduleA/solitaire/details?id=" + e.id + "&share_id=" + t, success: function(t) {}, fail: function(t) {} } }), _Page));<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/utils/wxapi.js "use strict"; function n() { return wx.getSystemInfoSync() || {} } module.exports = { showToast: function(n) { wx.showToast({ title: n, icon: "none", duration: 2e3 }) }, navigateBack: function() { wx.navigateBack({ delta: 1 }) }, getSystemInfoSync: n, checkWeChatVersion: function() { var o = n(), t = o.platform, e = o.version, i = void 0 === e ? "" : e; i = i.split("."), ("android" === t || "ios" === t) && +("" + i[0] + i[1] + i[2]) < 707 || "windows" === t && +("" + i[0] + i[1] + i[2]) < 271 ? wx.showModal({ title: "建议升级", content: "由于微信版本过低,只能观看直播", showCancel: !1, confirmText: "我知道了" }) : "android" !== t && "ios" !== t && "windows" !== t && wx.showModal({ title: "", content: "目前只有Android/iOS/Windows等平台支持观看直播,其他平台暂不支持", showCancel: !1, confirmText: "我知道了" }) }, pingDomain: function(n) { return new Promise(function(o, t) { var e = n.split("/"); e = e[2] ? e[0] + "//" + e[2] : "", wx.request({ url: e, success: function(n) { o(n) }, fail: function(n) { t(n) } }) }) }, authorize: function() { return new Promise(function(n, o) { wx.getNativeUserInfo && "function" == typeof wx.getNativeUserInfo ? wx.getNativeUserInfo({ success: function(o) { n(o) }, fail: function(n) { o(n) } }) : (wx.showModal({ title: "建议升级", content: "由于微信版本过低,无法打开授权弹框", showCancel: !1, confirmText: "我知道了" }), o({ errMsg: "not support" })) }) }, chooseAddressForPlugin: function() { return new Promise(function(n, o) { wx.chooseAddressForPlugin && "function" == typeof wx.chooseAddressForPlugin ? wx.chooseAddressForPlugin({ success: function(o) { n(o) }, fail: function(n) { o(n) } }) : (wx.showModal({ title: "建议升级", content: "由于微信版本过低,无法填写地址", showCancel: !1, confirmText: "我知道了" }), o({ errMsg: "not support" })) }) }, openSettingForPlugin: function() { return new Promise(function(n, o) { wx.openSettingForPlugin && "function" == typeof wx.openSettingForPlugin ? wx.openSettingForPlugin({ success: function(o) { n(o) }, fail: function(n) { o(n) } }) : (wx.showModal({ title: "建议升级", content: "由于微信版本过低,无法打开设置页", showCancel: !1, confirmText: "我知道了" }), o({ errMsg: "not support" })) }) }, reLaunch: function(n) { wx.reLaunch && "function" == typeof wx.reLaunch && wx.reLaunch({ url: n }) }, reportPerformance: function(n, o) { var t = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : []; wx.reportPerformance && "function" == typeof wx.reportPerformance && wx.reportPerformance(n, o, t) } };<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/pages/report-room/report-room.js "use strict"; var e = require("../../wxlive-components/logic/ui.js"); Component({ options: { styleIsolation: "page-apply-shared" }, properties: { livePlayerOptions: String }, data: { uiPagePaddingTop: 0, reportItems: [{ type: "低俗色情", value: "value0", checked: !1 }, { type: "非法政治", value: "value1", checked: !1 }, { type: "出售假冒禁售商品", value: "value2", checked: !1 }, { type: "引导线下或其他平台交易", value: "value3", checked: !1 }, { type: "侵权盗播", value: "value4", checked: !1 }, { type: "长期空镜或换人直播", value: "value5", checked: !1 }, { type: "其它", value: "value6", checked: !1 }] }, methods: { onLoad: function() { this.countTopPadding() }, onShow: function() { this.uiGetPagePaddingTop() }, countTopPadding: function() { var e = wx.getSystemInfoSync(); this.setData({ statusBarHeight: e.statusBarHeight }) }, uiGetPagePaddingTop: function() { this.setData({ uiPagePaddingTop: (0, e.getPaddingTop)() }) }, selectedReportReasonChange: function(e) { var t = "", a = e.detail.value; this.data.reportItems.forEach(function(e) { a === e.value && (t = e.type) }); var o = this.getOpenerEventChannel(); wx.navigateTo({ url: "report-room-detail?livePlayerOptions=" + encodeURIComponent(this.data.livePlayerOptions), events: { acceptDataFromReportRoomDetailPage: function(e) { o.emit("acceptDataFromReportRoomPage", { reportType: t, reportContent: e.reportContent }) } } }) } } });<file_sep>/lionfish_comshop/moduleA/solitaire/index.js var _extends = Object.assign || function(t) { for (var a = 1; a < arguments.length; a++) { var e = arguments[a]; for (var o in e) Object.prototype.hasOwnProperty.call(e, o) && (t[o] = e[o]) } return t }, app = getApp(), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ data: { list: [], loadText: "加载中...", noData: 0, loadMore: !0, groupInfo: { group_name: "社区", owner_name: "团长" } }, page: 1, onLoad: function(t) { var a = this; status.setGroupInfo().then(function(t) { a.setData({ groupInfo: t }) }); var e = t.share_id, o = t.community_id; this.options = t, "undefined" != e && 0 < e && wx.setStorageSync("share_id", e), this.compareCommunity(o), this.getData(o) }, initFn: function(t) { var a = this; this.page = 1, this.setData({ list: [], loadText: "加载中...", noData: 0, loadMore: !0 }, function() { a.getData(t) }) }, compareCommunity: function(i) { var s = this, r = wx.getStorageSync("community"), u = r.communityId || "", d = wx.getStorageSync("token"); i && util.getCommunityById(i).then(function(t) { var a = t.hide_community_change_btn, e = t.default_head_info; if (1 == t.open_danhead_model) { if (app.globalData.community = e, app.globalData.changedCommunity = !0, wx.setStorage({ key: "community", data: e }), d && util.addhistory(e), i != e.communityId) { var o = s.data.groupInfo; return void app.util.message("您只能访问自己" + o.group_name, "switchTo:/lionfish_comshop/pages/index/index", "error", "知道了") } } else if ("" != u && i) { if (console.log("currentCommunityId存在 比较社区"), u != i) { console.log("currentCommunityId存在 社区不同"); var n = s.data.groupInfo; if (1 == a) return console.log("禁止切换"), void app.util.message("您只能访问自己" + n.group_name, "switchTo:/lionfish_comshop/pages/index/index", "error", "知道了"); s.setData({ hide_community_change_btn: a, showChangeCommunity: !! t.data, changeCommunity: t.data, currentCommunity: r }) } } else d ? util.getCommunityInfo().then(function(t) { console.log("token存在 比较社区"), t.community_id && t.community_id != i && s.setData({ showChangeCommunity: !0, currentCommunity: t }) }). catch (function(t) { console.log("step4 新人"), "" != Object.keys(t) && util.addhistory(t, !0) }) : (console.log("token不存在 存社区"), app.globalData.community = t.data, app.globalData.changedCommunity = !0, wx.setStorage({ key: "community", data: t.data })) }) }, confrimChangeCommunity: function() { var t = this.data.changeCommunity, a = wx.getStorageSync("token"); app.globalData.community = t, app.globalData.changedCommunity = !0, wx.setStorage({ key: "community", data: t }), a && util.addhistory(t), this.initFn(t.communityId), this.setData({ showChangeCommunity: !1 }), console.log("用户点击确定") }, cancelChangeCommunity: function() { var t = this.data.currentCommunity.communityId || ""; t && this.initFn(t) }, onShow: function() { var a = this; util.check_login_new().then(function(t) { t ? (0, status.cartNum)("", !0).then(function(t) { a.setData({ cartNum: t.data }) }) : a.setData({ needAuth: !0 }) }) }, getData: function(t) { var s = this; (wx.showLoading(), t) || (t = wx.getStorageSync("community").communityId || ""); app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_head_index_solitairelist", head_id: t, page: this.page }, dataType: "json", success: function(t) { wx.stopPullDownRefresh(), wx.hideLoading(); var a = t.data.showTabbar; if (0 == t.data.code) { var e = {}, o = t.data.data, n = t.data.head_data; o.length < 20 && (e.noMore = !0), o = s.data.list.concat(o), s.page++, s.setData(_extends({ list: o }, e, { head_data: n, showTabbar: a })) } else if (1 == t.data.code) { var i = t.data.head_data || ""; 1 == s.page && s.setData({ noData: 1 }), s.setData({ loadMore: !1, noMore: !1, head_data: i, loadText: "没有更多记录了~", showTabbar: a }) } else if (2 != t.data.code) return 3 == t.data.code ? void app.util.message(t.data.msg, "/lionfish_comshop/pages/position/community", "error") : void app.util.message(t.data.msg, "", "error") } }) }, goDetails: function(t) { var a = t ? t.currentTarget.dataset.id : ""; if (a) { var e = "/lionfish_comshop/moduleA/solitaire/details?id=" + a; 3 < getCurrentPages().length ? wx.redirectTo({ url: e }) : wx.navigateTo({ url: e }) } }, showImgPrev: function(t) { var a = t ? t.currentTarget.dataset.idx : "", e = t ? t.currentTarget.dataset.sidx : "", o = this.data.list[e].images_list; wx.previewImage({ current: o[a], urls: o }) }, onPullDownRefresh: function() { var t = this; this.page = 1, this.setData({ list: [], loadText: "加载中...", noData: 0, loadMore: !0 }, function() { t.getData() }) }, onReachBottom: function() { if (!this.data.loadMore) return !1; this.getData() }, onShareAppMessage: function() { var t = wx.getStorageSync("community").communityId || ""; return { title: "", path: "lionfish_comshop/moduleA/solitaire/index?share_id=" + (wx.getStorageSync("member_id") || "") + "&community_id=" + t, success: function(t) {}, fail: function(t) {} } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/msg/msg.js "use strict"; var e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e) { return typeof e } : function(e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }; module.exports = function(t) { function n(e) { if (r[e]) return r[e].exports; var o = r[e] = { i: e, l: !1, exports: {} }; return t[e].call(o.exports, o, o.exports, n), o.l = !0, o.exports } var r = {}; return n.m = t, n.c = r, n.d = function(e, t, r) { n.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: r }) }, n.r = function(e) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e, "__esModule", { value: !0 }) }, n.t = function(t, r) { if (1 & r && (t = n(t)), 8 & r) return t; if (4 & r && "object" === (void 0 === t ? "undefined" : e(t)) && t && t.__esModule) return t; var o = Object.create(null); if (n.r(o), Object.defineProperty(o, "default", { enumerable: !0, value: t }), 2 & r && "string" != typeof t) for (var u in t) n.d(o, u, function(e) { return t[e] }.bind(null, u)); return o }, n.n = function(e) { var t = e && e.__esModule ? function() { return e. default } : function() { return e }; return n.d(t, "a", t), t }, n.o = function(e, t) { return Object.prototype.hasOwnProperty.call(e, t) }, n.p = "", n(n.s = 13) }({ 13: function(e, t, n) { Component({ options: { addGlobalClass: !0, multipleSlots: !0 }, properties: { title: { type: String, value: "" }, type: { type: String, value: "" }, icon: { type: String, value: "" }, desc: { type: String, value: "" }, extClass: { type: String, value: "" }, size: { type: Number, value: 64 } }, data: {} }) } });<file_sep>/lionfish_comshop/components/painter/lib/gradient.js ! function() { var t = { isGradient: function(t) { return !(!t || !t.startsWith("linear") && !t.startsWith("radial")) }, doGradient: function(t, a, r, n) { t.startsWith("linear") ? function(t, a, r, n) { for (var e = function(t, a, r) { var n = t.match(/([-]?\d{1,3})deg/), e = n && n[1] ? parseFloat(n[1]) : 0, i = void 0; switch (e) { case 0: i = [0, -r / 2, 0, r / 2]; break; case 90: i = [a / 2, 0, -a / 2, 0]; break; case -90: i = [-a / 2, 0, a / 2, 0]; break; case 180: i = [0, r / 2, 0, -r / 2]; break; case -180: i = [0, -r / 2, 0, r / 2]; break; default: var s = 0, l = 0; s = 0 < n[1] && n[1] < 90 ? a / 2 - (a / 2 * Math.tan((90 - n[1]) * Math.PI * 2 / 360) - r / 2) * Math.sin(2 * (90 - n[1]) * Math.PI * 2 / 360) / 2 : -180 < n[1] && n[1] < -90 ? -a / 2 + (a / 2 * Math.tan((90 - n[1]) * Math.PI * 2 / 360) - r / 2) * Math.sin(2 * (90 - n[1]) * Math.PI * 2 / 360) / 2 : 90 < n[1] && n[1] < 180 ? a / 2 + (-a / 2 * Math.tan((90 - n[1]) * Math.PI * 2 / 360) - r / 2) * Math.sin(2 * (90 - n[1]) * Math.PI * 2 / 360) / 2 : -a / 2 - (-a / 2 * Math.tan((90 - n[1]) * Math.PI * 2 / 360) - r / 2) * Math.sin(2 * (90 - n[1]) * Math.PI * 2 / 360) / 2, l = Math.tan((90 - n[1]) * Math.PI * 2 / 360) * s, i = [s, -l, -s, l] } return i }(r, t, a), i = n.createLinearGradient(e[0], e[1], e[2], e[3]), s = r.match(/linear-gradient\((.+)\)/)[1], l = h(s.substring(s.indexOf(",") + 1)), o = 0; o < l.colors.length; o++) i.addColorStop(l.percents[o], l.colors[o]); n.fillStyle = i }(a, r, t, n) : t.startsWith("radial") && function(t, a, r, n) { for (var e = h(r.match(/radial-gradient\((.+)\)/)[1]), i = n.createCircularGradient(0, 0, t < a ? a / 2 : t / 2), s = 0; s < e.colors.length; s++) i.addColorStop(e.percents[s], e.colors[s]); n.fillStyle = i }(a, r, t, n) } }; function h(t) { var a = t.substring(0, t.length - 1).split("%,"), r = [], n = [], e = !0, i = !1, s = void 0; try { for (var l, o = a[Symbol.iterator](); !(e = (l = o.next()).done); e = !0) { var h = l.value; r.push(h.substring(0, h.lastIndexOf(" ")).trim()), n.push(h.substring(h.lastIndexOf(" "), h.length) / 100) } } catch (t) { i = !0, s = t } finally { try { !e && o. return &&o. return () } finally { if (i) throw s } } return { colors: r, percents: n } } module.exports = { api: t } }();<file_sep>/lionfish_comshop/pages/user/protocol.js var util = require("../../utils/util.js"), status = require("../../utils/index.js"), app = getApp(); Page({ data: { list: [], noMore: !1 }, token: "", pageNum: 1, onLoad: function(t) { status.setNavBgColor(); var a = wx.getStorageSync("token"); this.token = a, this.get_list() }, get_list: function() { var s = this; wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "article.get_article_list", token: this.token, page: this.pageNum }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var a = s.data.list, e = t.data.data, i = {}; e.length < 30 && (i.noMore = !0), e = e.concat(a), i.list = e, s.pageNum++, s.setData(i) } else { var o = { noMore: !0 }; 1 == s.page && (o.noData = !0), s.setData(o) } } }) }, onReachBottom: function() { this.data.noMore || this.get_list() } });<file_sep>/lionfish_comshop/pages/groupCenter/apply.js var util = require("../../utils/util.js"), status = require("../../utils/index.js"), locat = require("../../utils/Location.js"), app = getApp(), clearTime = null; Page({ data: { pass: -2, canSubmit: !1, region: ["选择地址", "", ""], addr_detail: "", lon_lat: "", focus_mobile: !1, showCountDown: !0, timeStamp: 60, apply_complete: !1, wechat: "", needAuth: !1, member_info: { is_head: 0 }, groupInfo: { group_name: "社区", owner_name: "团长" } }, community_id: "", bindRegionChange: function(t) { this.setData({ region: t.detail.value.replace(/^\s*|\s*$/g, "") }) }, inputAddress: function(t) { this.setData({ addr_detail: t.detail.value.replace(/^\s*|\s*$/g, "") }) }, inputCommunity: function(t) { this.setData({ community_name: t.detail.value.replace(/^\s*|\s*$/g, "") }) }, inputMobile: function(t) { this.setData({ mobile_detail: t.detail.value.replace(/^\s*|\s*$/g, "") }) }, inputRealName: function(t) { this.setData({ head_name: t.detail.value.replace(/^\s*|\s*$/g, "") }) }, inputWechat: function(t) { this.setData({ wechat: t.detail.value.replace(/^\s*|\s*$/g, "") }) }, chose_location: function() { var d = this; wx.chooseLocation({ success: function(t) { var e = t.longitude + "," + t.latitude, a = t.address, n = d.data.region, i = "", o = a, s = new RegExp("(.*?省)(.*?市)(.*?区)", "g"), c = s.exec(o); null == c && null == (c = (s = new RegExp("(.*?省)(.*?市)(.*?市)", "g")).exec(o)) ? null != (c = (s = new RegExp("(.*?省)(.*?市)(.*县)", "g")).exec(o)) && (n[0] = c[1], n[1] = c[2], n[2] = c[3], i = a.replace(c[0], "")) : (n[0] = c[1], n[1] = c[2], n[2] = c[3], i = a.replace(c[0], "")); var u = i + t.name, r = u, l = ""; locat.getGpsLocation(t.latitude, t.longitude).then(function(t) { (l = t) && (n[0] = l.province, n[1] = l.city, n[2] = l.district, r = u || l.street), d.setData({ region: n, lon_lat: e, addr_detail: r }) }), "省" == n[0] && wx.showToast({ title: "请重新选择省市区", icon: "none" }) }, fail: function(t) { console.log("地址获取失败", t) } }) }, subscriptionNotice: function() { console.log("subscriptionNotice"); var o = this; return new Promise(function(t, e) { var i = o.data.need_subscript_template, a = Object.keys(i).map(function(t) { return i[t] }); wx.requestSubscribeMessage ? a.length && wx.requestSubscribeMessage({ tmplIds: a, success: function(e) { var a = 1, n = []; Object.keys(i).forEach(function(t) { "accept" == e[i[t]] ? n.push(t) : a = 0 }), n.length && o.addAccept(n), o.setData({ is_need_subscript: a }), t() }, fail: function() { e() } }) : e() }) }, addAccept: function(t) { var e = wx.getStorageSync("token"), a = t.join(","); app.util.request({ url: "entry/wxapp/user", data: { controller: "user.collect_subscriptmsg", token: e, type: a }, dataType: "json", method: "POST", success: function() {} }) }, submit: function() { if (this.authModal()) { var t = this, e = wx.getStorageSync("token"), a = this.data.region[0], n = this.data.region[1], i = this.data.region[2], o = this.data.addr_detail, s = this.data.community_name, c = this.data.mobile_detail, u = this.data.lon_lat, r = this.data.head_name, l = this.data.wechat; if ("" == r || void 0 === r) return wx.showToast({ title: "请填写姓名", icon: "none" }), !1; if ("" == c || !/^1(3|4|5|6|7|8|9)\d{9}$/.test(c)) return this.setData({ focus_mobile: !0 }), wx.showToast({ title: "手机号码有误", icon: "none" }), !1; if ("" == l || void 0 === l) return wx.showToast({ title: "请填写微信号", icon: "none" }), !1; if ("" == s || void 0 === s) return wx.showToast({ title: "请填写小区名称", icon: "none" }), !1; if ("省" == a && "市" == n && "区" == i) return wx.showToast({ title: "请选择地区", icon: "none" }), !1; if ("" == u || void 0 === u) return wx.showToast({ title: "请选择地图位置", icon: "none" }), !1; if ("" == o || void 0 === o) return wx.showToast({ title: "请填写详细地址", icon: "none" }), !1; var d = { province_name: a, city_name: n, area_name: i, lon_lat: u, addr_detail: o, community_name: s, mobile: c, head_name: r, wechat: l, controller: "community.sub_community_head", token: e, community_id: this.community_id }; 1 == this.data.is_need_subscript ? this.subscriptionNotice().then(function() { t.preSubmit(d) }). catch (function() { t.preSubmit(d) }) : t.preSubmit(d) } }, preSubmit: function(t) { var e = this; app.util.request({ url: "entry/wxapp/user", data: t, method: "post", dataType: "json", success: function(t) { 0 == t.data.code ? (wx.showToast({ title: "提交成功,等待审核", icon: "none", duration: 2e3 }), e.setData({ apply_complete: !0 })) : e.setData({ needAuth: !0 }) } }) }, onLoad: function(t) { var a = this; status.setNavBgColor(), status.setGroupInfo().then(function(t) { var e = t && t.owner_name || "团长"; a.setData({ groupInfo: t }), wx.setNavigationBarTitle({ title: e + "申请" }) }); var e = decodeURIComponent(t.scene); "undefined" != e && (this.community_id = e), this.getUserInfo(), this.checkSubscript() }, onShow: function() { var e = this; util.check_login_new().then(function(t) { t ? e.setData({ needAuth: !1 }) : e.setData({ needAuth: !0 }) }) }, authModal: function() { return !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, authSuccess: function() { var t = this; this.setData({ needAuth: !1 }, function() { t.getUserInfo() }) }, getUserInfo: function() { var a = this, t = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/user", data: { controller: "user.get_user_info", token: t }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data.data || { is_head: 0 }; 1 == e.is_head && app.util.message("您已通过审核", "/lionfish_comshop/pages/groupCenter/index", "error"), a.setData({ member_info: e }) } else a.setData({ needAuth: !0 }) } }) }, applyAgain: function() { var t = this.data.member_info; t.is_head = 0, this.setData({ member_info: t }) }, countDown: function() { var a = this; clearInterval(clearTime), clearTime = setInterval(function() { var t = a.data.timeStamp, e = a.data.showCountDown; 0 < t ? t-- : (e = !0, clearInterval(clearTime), t = 60), a.setData({ showCountDown: e, timeStamp: t }) }, 1e3) }, checkSubscript: function() { var i = this, t = wx.getStorageSync("token"); t && app.util.request({ url: "entry/wxapp/user", data: { controller: "community.check_head_subscriptapply", token: t }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data, a = e.is_need_subscript, n = e.need_subscript_template; i.setData({ is_need_subscript: a, need_subscript_template: n }) } } }) } });<file_sep>/lionfish_comshop/components/painter/lib/util.js var _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) { return typeof t } : function(t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }; function isValidUrl(t) { return /(ht|f)tp(s?):\/\/([^ \\/]*\.)+[^ \\/]*(:[0-9]+)?\/?/.test(t) } function equal(t, e) { if (t === e) return !0; if (t && e && "object" == (void 0 === t ? "undefined" : _typeof(t)) && "object" == (void 0 === e ? "undefined" : _typeof(e))) { var r, n, o, i = Array.isArray(t), f = Array.isArray(e); if (i && f) { if ((n = t.length) != e.length) return !1; for (r = n; 0 != r--;) if (!equal(t[r], e[r])) return !1; return !0 } if (i != f) return !1; var u = t instanceof Date, a = e instanceof Date; if (u != a) return !1; if (u && a) return t.getTime() == e.getTime(); var l = t instanceof RegExp, y = e instanceof RegExp; if (l != y) return !1; if (l && y) return t.toString() == e.toString(); var s = Object.keys(t); if ((n = s.length) !== Object.keys(e).length) return !1; for (r = n; 0 != r--;) if (!Object.prototype.hasOwnProperty.call(e, s[r])) return !1; for (r = n; 0 != r--;) if (!equal(t[o = s[r]], e[o])) return !1; return !0 } return t != t && e != e } module.exports = { isValidUrl: isValidUrl, equal: equal };<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/components/subscribe/subscribe.js "use strict"; function t(t) { return t && t.__esModule ? t : { default: t } } var e = t(require("../../wxlive-components/logic/api.js")), a = t(require("../../wxlive-components/logic/config.js")), i = t(require("../../wxlive-components/logic/request.js")), o = t(require("../../utils/wxapi.js")), s = null, n = !1; Component({ properties: { roomId: { type: Number } }, data: { showSubscribe: !0, roomStaticInfo: { end_time: "" } }, detached: function() { clearInterval(s) }, pageLifetimes: { show: function() { this.getRoomStaticInfo() }, hide: function() { clearInterval(s) } }, methods: { getRoomStaticInfo: function() { var t = this; i. default.getRoomStaticInfo({ room_id: t.data.roomId }).then(function(e) { t.data.roomStaticInfo = e, t.setData({ isSubscribe: !! +e.is_subscribe }), t.getLiveStatus() }). catch (function(e) { t.setData({ showSubscribe: !1 }) }) }, getLiveStatus: function() { var t = this; i. default.getLiveStatus({ room_id: t.data.roomId }).then(function(e) { var i = +e.live_status; e.timestamp > t.data.roomStaticInfo.end_time && i === a. default.LIVE_STATUS_CODE.LIVE_STATUS_NOT_START ? (t.setData({ showSubscribe: !1 }), clearInterval(s)) : (t.setData({ showSubscribe: i === a. default.LIVE_STATUS_CODE.LIVE_STATUS_NOT_START }), clearInterval(s), s = setInterval(function() { t.getLiveStatus() }, 6e4)) }). catch (function(e) { t.setData({ showSubscribe: !1 }), clearInterval(s), s = setInterval(function() { t.getLiveStatus() }, 6e4) }) }, clickSubscribe: function() { if (!n) { n = !0; var t = this, i = t.data.roomId, s = t.data.isSubscribe; if (s) { var u = { action: "unsubscribe", room_id: i, content: "", plugin_appid: a. default.PLUGIN_APPID, timestamp: Date.now() }; e. default.liveRoutePromise(u).then(function() { t.setData({ isSubscribe: !s }), n = !1, o. default.showToast("取消成功") }). catch (function() { n = !1, o. default.showToast("取消失败") }) } else { var c = { action: "subscribe", room_id: i, content: "", plugin_appid: a. default.PLUGIN_APPID, timestamp: Date.now() }; e. default.liveRoutePromise(c).then(function(e) { t.setData({ isSubscribe: !s }), n = !1, o. default.showToast("订阅成功") }). catch (function() { n = !1, o. default.showToast("订阅失败") }) } } } } });<file_sep>/lionfish_comshop/components/sku/index.js var _extends = Object.assign || function(t) { for (var a = 1; a < arguments.length; a++) { var e = arguments[a]; for (var i in e) Object.prototype.hasOwnProperty.call(e, i) && (t[i] = e[i]) } return t }, a = require("../../utils/public"), app = getApp(), util = require("../../utils/util.js"); Component({ properties: { visible: { type: Boolean, value: !1, observer: function(t) { t && this.setData({ value: 1, loading: !1 }) } }, cur_sku_arr: { type: Object, value: {} }, skuList: { type: Object, value: {} }, sku_val: { type: Number, value: 1 }, sku: { type: Array, value: [] }, goodsid: { type: Number, value: 0 }, type: { type: Number, value: 0 }, buyType: { type: String, value: "" }, soliId: { type: Number, value: 0 }, vipInfo: { type: Object, value: { is_open_vipcard_buy: 0, is_vip_card_member: 0, is_member_level_buy: 0 } } }, focusFlag: !1, data: { value: 1, loading: !1 }, methods: { close: function() { this.triggerEvent("cancel") }, selectSku: function(t) { var a = t.currentTarget.dataset.type.split("_"), e = this.data, i = e.sku, s = e.cur_sku_arr, o = e.skuList, u = e.sku_val, r = { name: a[3], id: a[2], index: a[0], idx: a[1] }; i.splice(a[0], 1, r); for (var n = "", d = 0; d < i.length; d++) d == i.length - 1 ? n += i[d].id : n = n + i[d].id + "_"; var l = {}; u > (s = Object.assign(s, o.sku_mu_list[n])).canBuyNum && (l.sku_val = s.canBuyNum, wx.showToast({ title: "最多只能购买" + s.canBuyNum + "件", icon: "none" })), this.setData(_extends({ cur_sku_arr: s, sku: i }, l)) }, setNum: function(t) { var a = t.currentTarget.dataset.type, e = 1, i = 1 * this.data.sku_val; "add" == a ? e = i + 1 : "decrease" == a && 1 < i && (e = i - 1); var s = this.data.sku, o = this.data.skuList; if (0 < s.length) for (var u = "", r = 0; r < s.length; r++) r == s.length - 1 ? u += s[r].id : u = u + s[r].id + "_"; 0 < o.length ? e > o.sku_mu_list[u].canBuyNum && (e -= 1) : e > this.data.cur_sku_arr.canBuyNum && (e -= 1); this.setData({ sku_val: e }) }, gocarfrom: function(t) { wx.showLoading(), a.collectFormIds(t.detail.formId), this.goOrder() }, goOrder: function() { var r = this, t = r.data; t.can_car && (t.can_car = !1); wx.getStorageSync("token"); var a = wx.getStorageSync("community").communityId, n = t.goodsid, e = t.sku_val, i = t.cur_sku_arr, s = ""; i && i.option_item_ids && (s = i.option_item_ids); var d = this.data.buyType ? this.data.buyType : "dan", o = this.data.soliId || "", u = { goods_id: n, community_id: a, quantity: e, sku_str: s, buy_type: d, pin_id: 0, is_just_addcar: 1, soli_id: o }; util.addCart(u).then(function(t) { if (1 == t.showVipModal) { var a = t.data.pop_vipmember_buyimage; wx.hideLoading(), r.triggerEvent("vipModal", { pop_vipmember_buyimage: a, showVipModal: !0, visible: !1 }) } else if (3 == t.data.code || 7 == t.data.code) wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }); else if ("integral" == d) if (6 == t.data.code) { var e = t.data.msg; wx.showToast({ title: e, icon: "none", duration: 2e3 }) } else wx.navigateTo({ url: "/lionfish_comshop/pages/order/placeOrder?type=integral" }); else if (4 == t.data.code) wx.showToast({ title: "您未登录", duration: 2e3, success: function() { r.setData({ needAuth: !0 }) } }); else if (6 == t.data.code) { var i = t.data.max_quantity || ""; 0 < i && r.setData({ sku_val: i }); e = t.data.msg; wx.showToast({ title: e, icon: "none", duration: 2e3 }) } else { if (r.close(), wx.hideLoading(), "soitaire" == d) { var s = t.data, o = s.goods_total_count, u = s.total; r.triggerEvent("changeCartNum", { goods_total_count: o, total: u, goods_id: n }) } else t.data.total && r.triggerEvent("changeCartNum", t.data.total); wx.showToast({ title: "已加入购物车", image: "../../images/addShopCart.png" }) } }) }, handleFocus: function() { this.focusFlag = !0 }, handleBlur: function(t) { var a = t.detail, e = parseInt(a.value); ("" == e || isNaN(e)) && this.setData({ sku_val: 1 }) }, changeNumber: function(t) { var a = this.data, e = a.cur_sku_arr, i = a.sku_val, s = 1 * e.stock, o = t.detail; if (this.focusFlag = !1, o) { var u = parseInt(o.value); s < (u = u < 1 ? 1 : u) ? (wx.showToast({ title: "最多只能购买" + s + "件", icon: "none" }), i = s) : i = u } this.setData({ sku_val: i }) } } });<file_sep>/app.js var util = require("we7/resource/js/util.js"), timeQueue = require("lionfish_comshop/utils/timeQueue"); require("lionfish_comshop/utils//mixins.js"), App({ onLaunch: function (t) { wx.hideTabBar(); var e = wx.getStorageSync("userInfo"); this.globalData.userInfo = e; var o = wx.getStorageSync("community"); this.globalData.hasDefaultCommunity = !!o, this.globalData.community = o, this.globalData.systemInfo = wx.getSystemInfoSync(); var a = this.globalData.systemInfo.model; this.globalData.isIpx = -1 < a.indexOf("iPhone X") || -1 < a.indexOf("unknown<iPhone"), this.globalData.timer = new timeQueue. default, this.getConfig() }, onShow: function (t) { this.getUpdate() }, onHide: function () {}, util: util, userInfo: { sessionid: null }, globalData: { systemInfo: {}, isIpx: !1, userInfo: {}, canGetGPS: !0, city: {}, community: {}, location: {}, hasDefaultCommunity: !0, historyCommunity: [], changedCommunity: !1, disUserInfo: {}, changeCity: "", timer: 0, formIds: [], community_id: "", placeholdeImg: "", cartNum: 0, cartNumStamp: 0, common_header_backgroundimage: "", appLoadStatus: 1, goodsListCarCount: [], typeCateId: 0, navBackUrl: "", isblack: 0 }, getUpdate: function () { if (wx.canIUse("getUpdateManager")) { var e = wx.getUpdateManager(); e.onCheckForUpdate(function (t) { t.hasUpdate && (e.onUpdateReady(function () { wx.showModal({ title: "更新提示", content: "新版本已经准备好,是否马上重启小程序?", success: function (t) { t.confirm && e.applyUpdate() } }) }), e.onUpdateFailed(function () { wx.showModal({ title: "已经有新版本了哟~", content: "新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~" }) })) }) } else wx.showModal({ title: "提示", content: "当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。" }) }, getConfig: function () { var t = wx.getStorageSync("token"); t && util.request({ url: "entry/wxapp/user", data: { controller: "index.get_firstload_msg", token: t, m: "lionfish_comshop" }, method: "post", dataType: "json", success: function (t) { if (0 == t.data.code) { var e = t.data, o = e.new_head_id, a = e.default_head_info; 0 < o && Object.keys(a).length && wx.setStorageSync("community", a) } } }) }, siteInfo: require("siteinfo.js") });<file_sep>/lionfish_comshop/components/parser/parser.js var document, _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) { return typeof t } : function(t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }, cache = getApp().parserCache = {}, config = require("./libs/config.js"), CssHandler = require("./libs/CssHandler.js"); try { document = require("./libs/document.js") } catch (t) {} var fs = wx.getFileSystemManager ? wx.getFileSystemManager() : null, parseHtml = require("./libs/MpHtmlParser.js"), showAnimation = wx.createAnimation({ timingFunction: "ease" }).opacity(1).step().export(); function hash(t) { for (var e = t.length, i = 5381; e--;) i += (i << 5) + t.charCodeAt(e); return i } Component({ properties: { html: { type: null, observer: function(t) { if (this._refresh) return this._refresh = !1; this.setContent(t, !0) } }, autosetTitle: { type: Boolean, value: !0 }, autopause: { type: Boolean, value: !0 }, domain: String, gestureZoom: Boolean, lazyLoad: Boolean, selectable: Boolean, tagStyle: Object, showWithAnimation: Boolean, useAnchor: Boolean, useCache: Boolean }, relations: { "../parser-group/parser-group": { type: "ancestor" } }, created: function() { this.imgList = [], this.imgList.setItem = function(t, e) { var i = this; if (e.includes("base64")) { var s = (this[t] = e).match(/data:image\/(\S+?);base64,(\S+)/); if (!s) return; var a = wx.env.USER_DATA_PATH + "/" + Date.now() + "." + s[1]; fs && fs.writeFile({ filePath: a, data: s[2], encoding: "base64", success: function() { return i[t] = a } }) } else if (this.includes(e)) { if ("http" != e.substring(0, 4)) return this[t] = e; for (var n = "", o = 0; o < e.length && (n += .5 < Math.random() ? e[o].toUpperCase() : e[o], "/" != e[o] || "/" == e[o - 1] || "/" == e[o + 1]); o++); n += e.substring(o + 1), this[t] = n } else this[t] = e }, this.imgList.each = function(t) { for (var e = 0; e < this.length; e++) { var i = t(this[e], e, this); i && this.setItem(e, i) } }, this._refresh = !1 }, detached: function() { this.imgList.each(function(t) { t && t.includes(wx.env.USER_DATA_PATH) && fs && fs.unlink({ filePath: t }) }) }, methods: { navigateTo: function(e) { var i = this; if (e.fail = e.fail || function() {}, !this.data.useAnchor) return e.fail({ errMsg: "Use-anchor attribute is disabled" }); this.createSelectorQuery().select("#root" + (e.id ? ">>>#" + e.id : "")).boundingClientRect().selectViewport().scrollOffset().exec(function(t) { if (!t[0]) return i.group ? i.group.navigateTo(i.i, e) : e.fail({ errMsg: "Label not found" }); wx.pageScrollTo({ scrollTop: t[1].scrollTop + t[0].top, success: e.success, fail: e.fail }) }) }, getText: function() { var n = ""; return function t(e) { if (e) for (var i, s = 0; i = e[s++];) if ("text" == i.type) n += i.text; else if ("br" == i.type) n += "\n"; else { var a = "p" == i.name || "div" == i.name || "tr" == i.name || "li" == i.name || "h" == i.name[0] && "0" < i.name[1] && i.name[1] < "7"; a && n && "\n" != n[n.length - 1] && (n += "\n"), t(i.children), a && "\n" != n[n.length - 1] ? n += "\n" : "td" != i.name && "th" != i.name || (n += "\t") } }(this.data.html), n.replace(/&nbsp;/g, " ") }, getVideoContext: function(t) { if (!t) return this.videoContexts; for (var e = this.videoContexts.length; e--;) if (this.videoContexts[e].id == t) return this.videoContexts[e]; return null }, setContent: function(t, e) { var i = this, s = { controls: {} }; if (this.data.showWithAnimation && (s.showAnimation = showAnimation), t) if ("string" == typeof t) { if (this.data.useCache) { var a = hash(t); cache[a] ? s.html = cache[a] : (s.html = parseHtml(t, this.data), cache[a] = s.html) } else s.html = parseHtml(t, this.data); this.triggerEvent("parse", s.html) } else if (t.constructor == Array) { if (t.length && "Parser" != t[0].PoweredBy) { var n = { _imgNum: 0, _videoNum: 0, _audioNum: 0, _domain: this.data.domain, _protocol: this.data.domain && this.data.domain.includes("://") ? this.data.domain.split("://")[0] : "http", _STACK: [], CssHandler: new CssHandler(this.data.tagStyle) }; ! function t(e) { for (var i, s = 0; i = e[s++];) if ("text" != i.type) { for (var a in i.attrs = i.attrs || {}, i.attrs) config.trustAttrs[a] ? "string" != typeof i.attrs[a] && (i.attrs[a] = i.attrs[a].toString()) : i.attrs[a] = void 0; config.LabelHandler(i, n), config.blockTags[i.name] ? i.name = "div" : config.trustTags[i.name] || (i.name = "span"), i.children && i.children.length ? (n._STACK.push(i), t(i.children), n._STACK.pop()) : i.children = void 0 } }(t), s.html = t } e || (s.html = t) } else { if ("object" != (void 0 === t ? "undefined" : _typeof(t)) || !t.nodes) return console.warn("错误的 html 类型:" + (void 0 === t ? "undefined" : _typeof(t))); s.html = t.nodes, console.warn("错误的 html 类型:object 类型已废弃,请直接将 html 设置为 object.nodes") } else { if (e) return; s.html = "" } this._refresh = !! s.html, this.setData(s), this.imgList.length = 0, this.videoContexts = [], document && (this.document = new document("html", s.html || t, this)); for (var o = this.selectAllComponents("#root,#root>>>._node"), r = function() { var t = o[h]; for (t._top = i, l = !! t._observer, c = t.data.nodes.length; u = t.data.nodes[--c];) u.c || ("img" == u.name ? (u.attrs.src && u.attrs.i && i.imgList.setItem(u.attrs.i, u.attrs.src), l || (l = !0, i.data.lazyLoad && t.createIntersectionObserver ? (wx.nextTick || setTimeout)(function() { t._observer = t.createIntersectionObserver(), t._observer.relativeToViewport({ top: 1e3, bottom: 1e3 }).observe("._img", function() { t.setData({ imgLoad: !0 }), t._observer.disconnect(), t._observer = void 0 }) }, 50) : t.setData({ imgLoad: !0 }))) : "video" == u.name ? ((m = wx.createVideoContext(u.attrs.id, t)).id = u.attrs.id, i.videoContexts.push(m)) : "audio" == u.name && u.attrs.autoplay ? wx.createAudioContext(u.attrs.id, t).play() : "title" == u.name && i.data.autosetTitle && "text" == u.children[0].type && u.children[0].text && wx.setNavigationBarTitle({ title: u.children[0].text })) }, h = o.length; h--;) { var l, c, u, m; r() }(wx.nextTick || setTimeout)(function() { i.createSelectorQuery().select("#root").boundingClientRect(function(t) { i.width = t.width, i.triggerEvent("ready", t) }).exec() }, 50) }, _tap: function(t) { if (this.data.gestureZoom && t.timeStamp - this.lastTime < 300) { if (this.zoomIn) this.animation.translateX(0).scale(1).step(), wx.pageScrollTo({ scrollTop: (t.detail.y - t.currentTarget.offsetTop + this.initY) / 2 - t.touches[0].clientY, duration: 400 }); else { var e = t.detail.x - t.currentTarget.offsetLeft; this.initY = t.detail.y - t.currentTarget.offsetTop, this.animation = wx.createAnimation({ transformOrigin: e + "px " + this.initY + "px 0", timingFunction: "ease-in-out" }), this.animation.scale(2).step(), this.translateMax = e / 2, this.translateMin = (e - this.width) / 2, this.translateX = 0 } this.zoomIn = !this.zoomIn, this.setData({ showAnimation: this.animation.export() }) } this.lastTime = t.timeStamp }, _touchstart: function(t) { 1 == t.touches.length && (this.initX = this.lastX = t.touches[0].pageX) }, _touchmove: function(t) { var e = t.touches[0].pageX - this.lastX; if (this.zoomIn && 1 == t.touches.length && 20 < Math.abs(e)) { if (this.lastX = t.touches[0].pageX, this.translateX <= this.translateMin && e < 0 || this.translateX >= this.translateMax && 0 < e) return; this.translateX += e * Math.abs(this.lastX - this.initX) * .05, this.translateX < this.translateMin && (this.translateX = this.translateMin), this.translateX > this.translateMax && (this.translateX = this.translateMax), this.animation.translateX(this.translateX).step(), this.setData({ showAnimation: this.animation.export() }) } } } });<file_sep>/lionfish_comshop/moduleA/seckill/lists.js var app = getApp(), util = require("../../utils/util.js"); Page({ data: { currentTab: 0, scekillTimeList: [], endTime: 1e4, list: [], clearTimer: !1 }, secTime: "", seckill_share_title: "", seckill_share_image: "", onLoad: function(e) { this.secTime = e.time || "" }, onShow: function() { var t = this; util.check_login_new().then(function(e) { t.setData({ needAuth: !e }) }), this.loadPage() }, onHide: function() { this.setData({ clearTimer: !1 }) }, loadPage: function() { this.getInfo() }, authSuccess: function() { var e = this; this.setData({ showEmpty: !1, needAuth: !1, showAuthModal: !1 }, function() { e.loadPage() }) }, authModal: function() { return !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, getInfo: function() { var m = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "scekill.get_scekill_info" }, dataType: "json", success: function(e) { if (0 == e.data.code) { var t = e.data.data, i = (t.seckill_is_open, t.scekill_time_arr), a = t.seckill_page_title, s = t.seckill_bg_color, l = t.seckill_share_title, n = t.seckill_share_image; wx.setNavigationBarTitle({ title: a || "限时秒杀" }); var o = (new Date).getHours(); console.log("当前时间:", o); var c = i || [], r = [], u = 0; if (c.length) { if (c.forEach(function(e, t) { var i = {}; e == o ? (i.state = 1, i.desc = "疯抢中", u = t) : e < o ? (i.state = 0, i.desc = "已开抢") : (i.state = 2, i.desc = "即将开抢"), i.timeStr = (e < 10 ? "0" + e : e) + ":00", i.seckillTime = e, r.push(i) }), "" != m.secTime) { var d = c.findIndex(function(e) { return e == m.secTime }); 0 < d && (u = d) } m.getSecKillGoods(c[u]) } var h = new Date((new Date).toLocaleDateString()).getTime() + 60 * (1 * c[u] + 1) * 60 * 1e3; console.log(m); m.seckill_share_title = l, m.seckill_share_image = n, m.setData({ scekillTimeList: r, seckill_bg_color: s, currentTab: u, endTime: h }) } } }) }, handleClick: function(e) { var t = this, i = e.currentTarget.dataset.index, a = this.data.scekillTimeList, s = new Date((new Date).toLocaleDateString()).getTime(), l = a[i], n = 0; 1 == l.state ? n = s + 60 * (1 * l.seckillTime + 1) * 60 * 1e3 : 2 == l.state && (n = s + 1 * l.seckillTime * 60 * 60 * 1e3 + 1), this.setData({ list: [], currentTab: i, endTime: n, clearTimer: !0 }, function() { t.getSecKillGoods(l.seckillTime) }) }, getSecKillGoods: function(e) { wx.showLoading(); var a = this, t = wx.getStorageSync("community"), i = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "index.load_gps_goodslist", token: i, pageNum: 1, head_id: t.communityId, seckill_time: e, is_seckill: 1, per_page: 1e4 }, dataType: "json", success: function(e) { if (wx.stopPullDownRefresh(), wx.hideLoading(), 0 == e.data.code) { var t = e.data.list || [], i = !1; 0 == (t = a.transTime(t)).length && (i = !0), a.setData({ list: t, clearTimer: !1, showEmpty: i }) } else a.setData({ clearTimer: !1, showEmpty: !0 }) } }) }, transTime: function(e) { return 0 === (1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : 0) && e.map(function(e) { e.end_time *= 1e3, e.actEnd = e.end_time <= (new Date).getTime() }), e }, endCurSeckill: function() { this.loadPage() }, onPullDownRefresh: function() { this.loadPage() }, onShareAppMessage: function() { var e = wx.getStorageSync("member_id"); return { title: this.seckill_share_title, path: "lionfish_comshop/moduleA/seckill/list?share_id=" + e, imageUrl: this.seckill_share_image, success: function() {}, fail: function() {} } } });<file_sep>/lionfish_comshop/moduleA/components/score-guess-like/index.js function _defineProperty(e, t, a) { return t in e ? Object.defineProperty(e, t, { value: a, enumerable: !0, configurable: !0, writable: !0 }) : e[t] = a, e } var util = require("../../../utils/util.js"); Component({ externalClasses: ["i-class"], properties: { item: { type: Object, value: {} } }, data: { disabled: !1 }, methods: { openSku: function() { this.setData({ disabled: !1 }); var e = this.data.item; void 0 === e.skuList.length ? this.triggerEvent("openSku", { actId: e.actId, skuList: e.skuList, promotionDTO: e.promotionDTO || "", allData: { spuName: e.spuName, skuImage: e.skuImage, actPrice: e.actPrice, canBuyNum: e.spuCanBuyNum, stock: e.spuCanBuyNum, marketPrice: e.marketPrice } }) : this.addCart({ value: 1, type: "plus" }) }, addCart: function(e) { wx.showLoading(); var t = wx.getStorageSync("community"), a = this.data.item.actId, i = t.communityId; if ("plus" == e.type) { var o = _defineProperty({ goods_id: a, community_id: i, quantity: 1, sku_str: "", buy_type: "dan", pin_id: 0, is_just_addcar: 1 }, "buy_type", "integral"); util.addCart(o).then(function(e) { if (wx.hideLoading(), 1 == e.showVipModal) { var t = e.data.pop_vipmember_buyimage; that.triggerEvent("vipModal", { pop_vipmember_buyimage: t, showVipModal: !0, visible: !1 }) } else if (3 == e.data.code || 7 == e.data.code) wx.showToast({ title: e.data.msg, icon: "none", duration: 2e3 }); else if (6 == e.data.code) { var a = e.data.msg; wx.showToast({ title: a, icon: "none", duration: 2e3 }) } else wx.navigateTo({ url: "/lionfish_comshop/pages/order/placeOrder?type=integral" }) }) } } } });<file_sep>/lionfish_comshop/mixin/scoreCartMixin.js var a = require("../utils/public"), app = getApp(), status = require("../utils/index.js"), util = require("../utils/util.js"); module.exports = { data: { visible: !1, stopClick: !1, updateCart: 0 }, vipModal: function(t) { this.setData(t.detail) }, authModal: function() { return (0 < arguments.length && void 0 !== arguments[0] && arguments[0]).detail && this.setData({ needAuth: !0 }), !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, openSku: function(t) { if (this.authModal()) { var a = this, e = t.detail, i = e.actId, s = e.skuList; a.setData({ addCar_goodsid: i }); var o = s.list || [], r = []; if (0 < o.length) { for (var d = 0; d < o.length; d++) { var u = o[d].option_value[0], n = { name: u.name, id: u.option_value_id, index: d, idx: 0 }; r.push(n) } for (var l = "", c = 0; c < r.length; c++) c == r.length - 1 ? l += r[c].id : l = l + r[c].id + "_"; var h = s.sku_mu_list[l]; a.setData({ sku: r, sku_val: 1, cur_sku_arr: h, skuList: e.skuList, visible: !0, showSku: !0 }) } else { var _ = e.skuList; a.setData({ sku: [], sku_val: 1, skuList: [], cur_sku_arr: _ }); var p = { detail: { formId: "" } }; p.detail.formId = "the formId is a mock one", a.gocarfrom(p) } } }, gocarfrom: function(t) { wx.showLoading(), a.collectFormIds(t.detail.formId), this.goOrder() }, goOrder: function() { var i = this, t = i.data; t.can_car && (t.can_car = !1); wx.getStorageSync("token"); var a = wx.getStorageSync("community").communityId, e = t.addCar_goodsid, s = t.sku_val, o = t.cur_sku_arr, r = ""; o && o.option_item_ids && (r = o.option_item_ids); var d = { goods_id: e, community_id: a, quantity: s, sku_str: r, buy_type: "integral", pin_id: 0, is_just_addcar: 1 }; util.addCart(d).then(function(t) { if (1 == t.showVipModal) { var a = t.data.pop_vipmember_buyimage; i.triggerEvent("vipModal", { pop_vipmember_buyimage: a, showVipModal: !0, visible: !1 }) } else if (3 == t.data.code || 7 == t.data.code) wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }); else if (4 == t.data.code) wx.showToast({ title: "您未登录", duration: 2e3, success: function() { i.setData({ needAuth: !0 }) } }); else if (6 == t.data.code) { var e = t.data.msg; wx.showToast({ title: e, icon: "none", duration: 2e3 }) } else { i.closeSku(), 3 < getCurrentPages().length ? wx.redirectTo({ url: "/lionfish_comshop/pages/order/placeOrder?type=integral" }) : wx.navigateTo({ url: "/lionfish_comshop/pages/order/placeOrder?type=integral" }) } }) }, closeSku: function() { this.setData({ visible: !1, stopClick: !1 }) } };<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/comments/comments.js "use strict"; Component({ properties: { from: { type: String, value: "" }, openid: { type: String, value: "" }, commentList: { type: Array, value: [] }, isScrollY: { type: Boolean, value: !0 }, commentScrollIntoView: { type: String, value: "" }, newNotifyCount: { type: Number }, hasStaticHeight: { type: Number, value: 0 } }, data: { showNewNotify: !1, showReportCommentList: [], fetchCommentList: [], avatarError: "https://mmbiz.qpic.cn/mmbiz/a5icZrUmbV8p5jb6RZ8aYfjfS2AVle8URwBt8QIu6XbGewB9wiaWYWkPwq4R7pfdsFibuLkic16UcxDSNYtB8HnC1Q/0" }, observers: { commentList: function(t) { this.setData({ fetchCommentList: t }) } }, methods: { handleAvatarError: function(t) { if (t.detail.errMsg) { var e = this.data.fetchCommentList; e[t.target.dataset.index].avatar = this.data.avatarError, this.setData({ fetchCommentList: e }) } }, scrollComment: function(t) { !this.data.showNewNotify && t.detail.scrollHeight - t.detail.scrollTop > 300 && (this.setData({ showNewNotify: !0 }), this.triggerEvent("customevent", { scrollComment: !0, isScrollCommentToBottom: !1 })) }, scrollCommentToBottom: function() { this.setData({ showNewNotify: !1 }), this.triggerEvent("customevent", { scrollComment: !0, isScrollCommentToBottom: !0 }) }, clickNewNotify: function() { this.setData({ showNewNotify: !1, commentScrollIntoView: "comment" + this.data.fetchCommentList.length }), this.triggerEvent("customevent", { scrollComment: !0, confirmNewNotify: !0 }) }, longPressComments: function(t) { var e = [], o = t.currentTarget.dataset.index; e[o] = 0 !== o, this.setData({ showReportCommentList: e }) }, reportComment: function(t) { this.setData({ showReportCommentList: [] }), "player" === this.data.from && this.triggerEvent("customevent", { confirmReportComment: !0, avatar: t.currentTarget.dataset.avatar, nickname: t.currentTarget.dataset.nickname, content: t.currentTarget.dataset.content }), "pusher" === this.data.from && this.triggerEvent("banuser", { openid: t.currentTarget.dataset.openid }) }, clickComments: function() { this.setData({ showReportCommentList: [] }) } } });<file_sep>/lionfish_comshop/moduleA/menu/index.js var _extends = Object.assign || function(t) { for (var e = 1; e < arguments.length; e++) { var a = arguments[e]; for (var i in a) Object.prototype.hasOwnProperty.call(a, i) && (t[i] = a[i]) } return t }, app = getApp(), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ data: { loadMore: !0, classification: { tabs: [], activeIndex: 0 }, tabTop: 0, showSubCate: !0 }, pageNum: 1, onLoad: function() { this.getInfo(), this._doRefreshMasonry() }, onReady: function() { var e = this, t = wx.createSelectorQuery(), a = Math.round(app.globalData.systemInfo.windowWidth / 750 * 100) || 0; setTimeout(function() { t.select("#tab").boundingClientRect(function(t) { e.setData({ tabTop: t.top - a }) }).exec() }, 1e3) }, onShow: function() { var a = this; util.check_login_new().then(function(t) { var e = !t; a.setData({ needAuth: e }), t && (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && a.setData({ cartNum: t.data }) }) }) }, onPageScroll: function(t) { if (t.scrollTop > this.data.tabTop) { if (this.data.tabFix) return; this.setData({ oneFixed: "Fixed" }) } else this.setData({ oneFixed: "" }) }, noLogin: function() { this.setData({ needAuth: !0, showAuthModal: !0 }) }, authSuccess: function() { var t = this; this.pageNum = 1, this.setData({ loadMore: !0, showEmpty: 0, needAuth: !1, showAuthModal: !1 }, function() { t._doRefreshMasonry() }) }, authModal: function() { return !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, classificationChange: function(t) { var e = this; this.pageNum = 1, this.setData({ loadMore: !0, showEmpty: 0, "classification.activeIndex": t.detail.e, classificationId: t.detail.a }, function() { e._doRefreshMasonry() }) }, onPullDownRefresh: function() { var t = this; this.pageNum = 1, this.setData({ loadMore: !0, showEmpty: 0 }, function() { t.getInfo(), t._doRefreshMasonry() }) }, onReachBottom: function() { this.data.loadMore && this._doAppendMasonry() }, _doRefreshMasonry: function() { var t = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : "", e = this; this.masonryListComponent = this.selectComponent("#masonry"), this.getData(t).then(function(t) { e.masonryListComponent.start(t).then(function() {}) }). catch (function() { e.masonryListComponent.start([]).then(function() {}) }) }, _doAppendMasonry: function() { var e = this; this.masonryListComponent = this.selectComponent("#masonry"), this.getData().then(function(t) { e.masonryListComponent.append(t).then(function() { console.log("refresh completed") }) }). catch (function() { console.log("没有更多了") }) }, getData: function() { var a = this, s = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : ""; return new Promise(function(i, o) { var n = a, t = wx.getStorageSync("token"), e = n.data.classificationId; wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "recipe.get_recipe_list", token: t, gid: e, pageNum: a.pageNum, keyword: s }, dataType: "json", success: function(t) { if (wx.stopPullDownRefresh(), 0 == t.data.code) { var e = t.data.data; n.pageNum++, i(e) } else { var a = { loadMore: !1 }; 1 == n.pageNum && (a.showEmpty = 1), n.setData(a), o("") } wx.hideLoading() } }) }) }, getInfo: function() { var h = this; wx.getStorageSync("token"); wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "recipe.get_index_info" }, dataType: "json", success: function(t) { if (t.data.code) { var e = t.data.code, a = e.adv_arr, i = e.cate_list, o = e.is_open_recipe, n = e.modify_recipe_name, s = e.modify_recipe_share_title, r = e.modify_vipcard_share_image; if (1 != o) return void app.util.message("未开启功能", "switchTo:/lionfish_comshop/pages/index/index", "error"); wx.setNavigationBarTitle({ title: n || "菜谱" }); var c = { classification: { activeIndex: 0 } }; 0 < i.length ? (i.unshift({ name: "全部", id: 0 }), c.isShowClassification = !0, c.classification.tabs = i) : c.isShowClassification = !1, h.setData(_extends({ adv_arr: a || [], modify_recipe_share_title: s, modify_vipcard_share_image: r, modify_recipe_name: n || "菜谱" }, c)) } wx.hideLoading() } }) }, goResult: function(t) { var e = this, a = t.detail.value.replace(/\s+/g, ""); a ? (this.pageNum = 1, this.setData({ loadMore: !0, showEmpty: 0 }, function() { e._doRefreshMasonry(a) })) : wx.showToast({ title: "请输入关键词", icon: "none" }) }, goBannerUrl: function(t) { var e = t.currentTarget.dataset.idx, a = this.data, i = a.adv_arr, o = a.needAuth; if (0 < i.length) { var n = i[e].link, s = i[e].linktype; if (util.checkRedirectTo(n, o)) return void this.authModal(); if (0 == s) n && wx.navigateTo({ url: "/lionfish_comshop/pages/web-view?url=" + encodeURIComponent(n) }); else if (1 == s) - 1 != n.indexOf("lionfish_comshop/pages/index/index") || -1 != n.indexOf("lionfish_comshop/pages/order/shopCart") || -1 != n.indexOf("lionfish_comshop/pages/user/me") || -1 != n.indexOf("lionfish_comshop/pages/type/index") ? n && wx.switchTab({ url: n }) : n && wx.navigateTo({ url: n }); else if (2 == s) { slider_list[e].appid && wx.navigateToMiniProgram({ appId: slider_list[e].appid, path: n, extraData: {}, envVersion: "release", success: function(t) {}, fail: function(t) { console.log(t) } }) } } }, goLink: function(t) { if (this.authModal()) { var e = t.currentTarget.dataset.link; 3 < getCurrentPages().length ? wx.redirectTo({ url: e }) : wx.navigateTo({ url: e }) } }, onShareAppMessage: function() { var t = wx.getStorageSync("member_id"), e = this.data; return { title: e.modify_recipe_share_title, path: "lionfish_comshop/moduleA/menu/index?share_id=" + t, imageUrl: e.modify_vipcard_share_image, success: function() {}, fail: function() {} } }, onShareTimeline: function () { var t = wx.getStorageSync("member_id"), e = this.data; return { title: e.modify_recipe_share_title, query: "share_id=" + t, imageUrl: e.modify_vipcard_share_image, } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/gallery/gallery.js "use strict"; var e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e) { return typeof e } : function(e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }; module.exports = function(t) { function r(e) { if (n[e]) return n[e].exports; var o = n[e] = { i: e, l: !1, exports: {} }; return t[e].call(o.exports, o, o.exports, r), o.l = !0, o.exports } var n = {}; return r.m = t, r.c = n, r.d = function(e, t, n) { r.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: n }) }, r.r = function(e) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e, "__esModule", { value: !0 }) }, r.t = function(t, n) { if (1 & n && (t = r(t)), 8 & n) return t; if (4 & n && "object" === (void 0 === t ? "undefined" : e(t)) && t && t.__esModule) return t; var o = Object.create(null); if (r.r(o), Object.defineProperty(o, "default", { enumerable: !0, value: t }), 2 & n && "string" != typeof t) for (var u in t) r.d(o, u, function(e) { return t[e] }.bind(null, u)); return o }, r.n = function(e) { var t = e && e.__esModule ? function() { return e. default } : function() { return e }; return r.d(t, "a", t), t }, r.o = function(e, t) { return Object.prototype.hasOwnProperty.call(e, t) }, r.p = "", r(r.s = 15) }({ 15: function(e, t, r) { Component({ options: { addGlobalClass: !0 }, properties: { imgUrls: { type: Array, value: [], observer: function(e, t, r) { this.setData({ currentImgs: e }) } }, delete: { type: Boolean, value: !0 }, show: { type: Boolean, value: !0 }, current: { type: Number, value: 0 }, hideOnClick: { type: Boolean, value: !0 }, extClass: { type: Boolean, value: "" } }, data: { currentImgs: [] }, ready: function() { var e = this.data; this.setData({ currentImgs: e.imgUrls }) }, methods: { change: function(e) { this.setData({ current: e.detail.current }), this.triggerEvent("change", { current: e.detail.current }, {}) }, deleteImg: function() { var e = this.data, t = e.currentImgs, r = t.splice(e.current, 1); this.triggerEvent("delete", { url: r[0], index: e.current }, {}), 0 !== t.length ? this.setData({ current: 0, currentImgs: t }) : this.hideGallery() }, hideGallery: function() { this.data.hideOnClick && (this.setData({ show: !1 }), this.triggerEvent("hide", {}, {})) } } }) } });<file_sep>/lionfish_comshop/components/vipModal/index.js Component({ properties: { visible: { type: Boolean, value: !1 }, imgUrl: { type: String, value: "" } }, methods: { goUrl: function() { wx.navigateTo({ url: "/lionfish_comshop/moduleA/vip/upgrade" }) }, closeModal: function() { this.setData({ visible: !1 }) } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/store-list/store-list.js "use strict"; Component({ properties: { from: { type: String, value: "" }, type: { type: String, value: "" }, showStoreList: { type: Boolean, value: !1 }, storeRankList: { type: Array, value: [] }, storeList: { type: Array, value: [] }, storeListStatus: { type: String, value: "" }, height: { type: Number, value: 0 } }, lifetimes: { ready: function() { this.setData({ fadeIn: !0 }) }, detached: function() { this.setData({ fadeIn: !1 }) } }, data: { fadeIn: !1, allStoreList: [] }, observers: { storeRankList: function(t) { this.setData({ allStoreList: t.concat(this.data.storeList) }) }, storeList: function(t) { this.setData({ allStoreList: this.data.storeRankList.concat(t) }) } }, methods: { clickViewGoods: function(t) { this.triggerEvent("customevent", { confirmViewGoods: !0, goods_id: t.currentTarget.dataset.id, showStoreList: !0 }) }, closeStore: function() { this.setData({ showStoreList: !1 }), this.triggerEvent("customevent", { showStoreList: !1 }) } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/checkbox-group/checkbox-group.js "use strict"; var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) { return typeof t } : function(t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }; module.exports = function(e) { function n(t) { if (a[t]) return a[t].exports; var r = a[t] = { i: t, l: !1, exports: {} }; return e[t].call(r.exports, r, r.exports, n), r.l = !0, r.exports } var a = {}; return n.m = e, n.c = a, n.d = function(t, e, a) { n.o(t, e) || Object.defineProperty(t, e, { enumerable: !0, get: a }) }, n.r = function(t) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: !0 }) }, n.t = function(e, a) { if (1 & a && (e = n(e)), 8 & a) return e; if (4 & a && "object" === (void 0 === e ? "undefined" : t(e)) && e && e.__esModule) return e; var r = Object.create(null); if (n.r(r), Object.defineProperty(r, "default", { enumerable: !0, value: e }), 2 & a && "string" != typeof e) for (var i in e) n.d(r, i, function(t) { return e[t] }.bind(null, i)); return r }, n.n = function(t) { var e = t && t.__esModule ? function() { return t. default } : function() { return t }; return n.d(e, "a", e), e }, n.o = function(t, e) { return Object.prototype.hasOwnProperty.call(t, e) }, n.p = "", n(n.s = 17) }({ 17: function(t, e, n) { Component({ properties: { multi: { type: Boolean, value: !0, observer: "_multiChange" }, extClass: { type: String, value: "" }, prop: { type: String, value: "" } }, data: { targetList: [], parentCell: null }, relations: { "../checkbox/checkbox": { type: "descendant", linked: function(t) { this.data.targetList.push(t), t.setMulti(this.data.multi), this.data.firstItem || (this.data.firstItem = t), t !== this.data.firstItem && t.setOuterClass("weui-cell_wxss") }, unlinked: function(t) { var e = -1; this.data.targetList.forEach(function(n, a) { n === t && (e = a) }), this.data.targetList.splice(e, 1), this.data.targetList || (this.data.firstItem = null) } }, "../form/form": { type: "ancestor" }, "../cells/cells": { type: "ancestor", linked: function(t) { this.data.parentCell || (this.data.parentCell = t) }, unlinked: function(t) { this.data.parentCell = null } } }, methods: { checkedChange: function(t, e) { if (console.log("checked change", t), this.data.multi) { var n = []; this.data.targetList.forEach(function(t) { t.data.checked && n.push(t.data.value) }), this.triggerEvent("change", { value: n }) } else { var a = ""; this.data.targetList.forEach(function(t) { t === e ? a = t.data.value : t.setData({ checked: !1 }) }), this.triggerEvent("change", { value: a }, {}) } }, _multiChange: function(t) { return this.data.targetList.forEach(function(e) { e.setMulti(t) }), this.data.parentCell && this.data.parentCell.setCellMulti(t), t } } }) } });<file_sep>/lionfish_comshop/pages/groupCenter/index.js var app = getApp(), status = require("../../utils/index.js"); Page({ data: { waitSendNum: 0, waitSignNum: 0, waitPickNum: 0, completeNum: 0, disUserId: "", communityName: "", communityId: "", distribution: "", estimate: "", lastMonth: "", isShow: !0, currentTab: 0, show_on_one: 0, dialogShow: 0, effectValidOrderNum: 0, groupInfo: { group_name: "社区", owner_name: "团长" } }, onLoad: function(t) { var o = this; status.setGroupInfo().then(function(t) { var e = t && t.owner_name || "团长"; wx.setNavigationBarTitle({ title: e + "中心" }), o.setData({ groupInfo: t }) }), this.loadPage() }, loadPage: function() { var e = this; status.loadStatus().then(function() { var t = app.globalData.appLoadStatus; 0 == t && wx.redirectTo({ url: "/lionfish_comshop/pages/user/me" }), e.setData({ appLoadStatus: t, community: app.globalData.community }) }), this.load_community_data() }, load_community_data: function() { var t = wx.getStorageSync("token"), c = this; app.util.request({ url: "entry/wxapp/user", data: { controller: "community.get_community_info", token: t }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data, o = e.commission_info; o.mix_total_money = o.mix_total_money.toFixed(2); var a = t.data, n = a.head_today_pay_money, i = a.today_add_head_member, r = a.today_after_sale_order_count, s = a.today_invite_head_member, u = a.is_open_solitaire; c.setData({ member_info: e.member_info, community_info: e.community_info, commission_info: o, total_order_count: e.total_order_count || 0, total_member_count: e.total_member_count || 0, today_order_count: e.today_order_count || 0, today_effect_order_count: e.today_effect_order_count || 0, today_pay_order_count: e.today_pay_order_count || 0, today_pre_total_money: e.today_pre_total_money || 0, waitSendNum: e.wait_send_count || 0, waitSignNum: e.wait_qianshou_count || 0, waitPickNum: e.wait_tihuo_count || 0, completeNum: e.has_success_count || 0, open_community_addhexiaomember: e.open_community_addhexiaomember, open_community_head_leve: e.open_community_head_leve, head_today_pay_money: n, today_add_head_member: i, today_after_sale_order_count: r, today_invite_head_member: s, is_open_solitaire: u }) } else wx.reLaunch({ url: "/lionfish_comshop/pages/user/me" }) } }) }, goScan: function() { wx.scanCode({ success: function(t) { console.log(t), "WX_CODE" == t.scanType && "" != t.path && wx.navigateTo({ url: "/" + t.path }) } }) }, onShow: function() { var t = this.data.show_on_one, e = wx.getStorageSync("commiss_diy_name") || "分销"; 0 < t && this.load_community_data(), this.setData({ show_on_one: 1, commiss_diy_name: e }) }, goOrder: function(t) { var e = t.currentTarget.dataset.status; wx.navigateTo({ url: "/lionfish_comshop/pages/groupCenter/groupList?tab=" + e }) }, goEdit: function() { wx.navigateTo({ url: "/lionfish_comshop/pages/groupCenter/setting?id=" + this.data.community_info.id }) }, switchNav: function(t) { if (this.data.currentTab === 1 * t.target.dataset.current) return !1; this.setData({ currentTab: 1 * t.target.dataset.current }) }, bindChange: function(t) { this.setData({ currentTab: 1 * t.detail.current }); for (var e = 0; e < 4; e++) this.data.currentTab === e && this.setData({ effectEstimate: this.data.effectList[e].estimate, effectSettle: this.data.effectList[e].settle, effectValidOrderNum: this.data.effectList[e].validOrderNum }) }, changeMycommunion: function() { var t = this.data.community_info.id; console.log(t); var e = wx.getStorageSync("token"), o = this; void 0 !== t && app.util.request({ url: "entry/wxapp/index", data: { controller: "index.addhistory_community", community_id: t, token: e }, dataType: "json", success: function(t) { console.log("s1"), o.getCommunityInfo().then(function() { console.log("s2"), app.globalData.changedCommunity = !0, wx.switchTab({ url: "/lionfish_comshop/pages/index/index" }) }) } }) }, getCommunityInfo: function() { return new Promise(function(o, t) { var e = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "index.load_history_community", token: e }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data.list; 0 < Object.keys(e).length || 0 != e.communityId ? (wx.setStorageSync("community", e), app.globalData.community = e, o(e)) : o("") } } }) }) } });<file_sep>/lionfish_comshop/pages/order/order.js var util = require("../../utils/util.js"), app = getApp(), status = require("../../utils/index.js"); function count_down(e, t) { var o = Math.floor(t / 1e3), a = o / 3600 / 24, r = Math.floor(a), n = o / 3600 - 24 * r, i = Math.floor(n), s = o / 60 - 1440 * r - 60 * i, d = Math.floor(s), c = o - 86400 * r - 3600 * i - 60 * d; e.setData({ endtime: { days: r, hours: fill_zero_prefix(i), minutes: fill_zero_prefix(d), seconds: fill_zero_prefix(c), show_detail: 1 } }), t <= 0 ? e.setData({ changeState: 1, endtime: { days: "00", hours: "00", minutes: "00", seconds: "00" } }) : setTimeout(function() { count_down(e, t -= 1e3) }, 1e3) } function fill_zero_prefix(e) { return e < 10 ? "0" + e : e } Page({ mixins: [require("../../mixin/compoentCartMixin.js")], data: { endtime: { days: "00", hours: "00", minutes: "00", seconds: "00" }, cancelOrderVisible: !1, orderSkuResps: [], tablebar: 4, navState: 0, theme_type: "", loadover: !1, pingtai_deal: 0, is_show: !1, order: {}, common_header_backgroundimage: "", isShowModal: !1, userInfo: {}, groupInfo: { group_name: "社区", owner_name: "团长", delivery_ziti_name: "到点自提", delivery_tuanzshipping_name: "团长配送", delivery_express_name: "快递配送" }, is_show_guess_like: 1, showRefundModal: !1 }, is_show_tip: "", timeOut: function() { console.log("计时完成") }, options: "", canCancel: !0, isFirst: 1, onLoad: function(e) { var u = this; u.options = e; var t = wx.getStorageSync("userInfo"); t && (t.shareNickName = 3 < t.nickName.length ? t.nickName.substr(0, 3) + "..." : t.nickName), status.setGroupInfo().then(function(e) { u.setData({ groupInfo: e }) }), util.check_login() ? this.setData({ needAuth: !1 }) : this.setData({ needAuth: !0 }), u.setData({ common_header_backgroundimage: app.globalData.common_header_backgroundimage, userInfo: t }); var o = wx.getStorageSync("token"); wx.hideShareMenu(), wx.showLoading(); var _ = e && e.is_show || 0, a = e && e.isfail || ""; null != (this.is_show_tip = _) && 1 == _ || wx.showLoading(), null != a && 1 == a && wx.showToast({ title: "支付失败", icon: "none" }), app.util.request({ url: "entry/wxapp/index", data: { controller: "order.order_info", token: o, id: e.id }, dataType: "json", method: "POST", success: function(e) { if (setTimeout(function() { wx.hideLoading() }, 1e3), 0 == e.data.code) { var t = e.data.data.order_info; if (null != _ && 1 == _ && "integral" == t.type) wx.showToast({ title: "兑换成功" }); else if (null != _ && 1 == _) if (1 == e.data.order_pay_after_share) { var o = e.data.data.share_img; u.setData({ share_img: o, isShowModal: !0 }) } else wx.showToast({ title: "支付成功" }); if (3 == t.order_status_id) { var a = 1e3 * (t.over_buy_time - t.cur_time); 0 < a ? count_down(u, a) : 1 == t.open_auto_delete && u.setData({ changeState: 1 }) } var r = e.data, n = r.pingtai_deal, i = r.order_refund, s = r.order_can_del_cancle, d = r.is_hidden_orderlist_phone, c = r.is_show_guess_like, l = r.user_service_switch; u.setData({ order: e.data.data, pingtai_deal: n, order_refund: i, order_can_del_cancle: s, loadover: !0, is_show: 1, hide_lding: !0, is_hidden_orderlist_phone: d || 0, is_show_guess_like: c || 0, user_service_switch: l || 1 }), u.hide_lding() } else 2 == e.data.code && u.setData({ needAuth: !0 }) } }) }, onShow: function() { console.log(this.isFirst, "onShow", this.options.id), 1 < this.isFirst && this.reload_data(), this.isFirst++ }, onHide: function() { console.log("order Hide") }, authSuccess: function() { this.onLoad(this.options) }, reload_data: function() { console.log("reload_data--", this.options.id); var a = this, e = wx.getStorageSync("token"), t = this.options.id || ""; t && app.util.request({ url: "entry/wxapp/index", data: { controller: "order.order_info", token: e, id: t }, dataType: "json", method: "POST", success: function(e) { var t = e.data.data.order_info; if (3 == t.order_status_id) { var o = 1e3 * (t.over_buy_time - t.cur_time); 0 < o ? count_down(a, o) : a.setData({ changeState: 1 }) } a.setData({ order: e.data.data, pingtai_deal: e.data.pingtai_deal, order_refund: e.data.order_refund, loadover: !0, is_show: 1, hide_lding: !0 }) } }) }, receivOrder: function(e) { var t = e.currentTarget.dataset.type || "", o = wx.getStorageSync("token"), a = this; wx.showModal({ title: "提示", content: "确认收到", confirmColor: "#F75451", success: function(e) { e.confirm && app.util.request({ url: "entry/wxapp/index", data: { controller: "order.receive_order", token: o, order_id: t }, dataType: "json", success: function(e) { 0 == e.data.code && (wx.showToast({ title: "收货成功", icon: "success", duration: 1e3 }), a.reload_data()) } }) } }) }, cancelSubmit: function(e) { var t = e.detail.formId, o = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/user", data: { controller: "user.get_member_form_id", token: o, from_id: t }, dataType: "json", success: function(e) {} }) }, payNowSubmit: function(e) { var t = e.detail.formId, o = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/user", data: { controller: "user.get_member_form_id", token: o, from_id: t }, dataType: "json", success: function(e) {} }) }, callDialog: function(e) { var t = e.currentTarget.dataset.type || "", o = wx.getStorageSync("token"); wx.showModal({ title: "取消支付", content: "好不容易挑出来,确定要取消吗?", confirmColor: "#F75451", success: function(e) { e.confirm && app.util.request({ url: "entry/wxapp/index", data: { controller: "order.cancel_order", token: o, order_id: t }, dataType: "json", success: function(e) { wx.showToast({ title: "取消成功", icon: "success", complete: function() { wx.redirectTo({ url: "/lionfish_comshop/pages/order/index" }) } }) } }) } }) }, applyForService: function(e) { var t = e.currentTarget.dataset.type || "", o = e.currentTarget.dataset.order_goods_id; wx.getStorageSync("token"); t && wx.redirectTo({ url: "/lionfish_comshop/pages/order/refund?id=" + t + "&order_goods_id=" + o }) }, payNow: function(e) { var t = e.currentTarget.dataset.type || "", o = wx.getStorageSync("token"); t && app.util.request({ url: "entry/wxapp/index", data: { controller: "car.wxpay", token: o, order_id: t }, dataType: "json", method: "POST", success: function(e) { 0 == e.data.code ? wx.requestPayment({ appId: e.data.appId, timeStamp: e.data.timeStamp, nonceStr: e.data.nonceStr, package: e.data.package, signType: e.data.signType, paySign: e.data.paySign, success: function(e) { wx.redirectTo({ url: "/lionfish_comshop/pages/order/order?id=" + t + "&is_show=1" }) }, fail: function(e) { console.log(e) } }) : 2 == e.data.code && wx.showToast({ title: e.data.msg, icon: "none" }) } }) }, hide_lding: function() { wx.hideLoading(), this.setData({ is_show: !0 }) }, call_mobile: function(e) { var t = e.currentTarget.dataset.mobile; wx.makePhoneCall({ phoneNumber: t }) }, goComment: function(e) { var t = e.currentTarget.dataset.type, o = e.currentTarget.dataset.order_goods_id, a = e.currentTarget.dataset.goods_id; 3 < getCurrentPages().length ? wx.redirectTo({ url: "/lionfish_comshop/pages/order/evaluate?id=" + t + "&goods_id=" + a + "&order_goods_id=" + o }) : wx.navigateTo({ url: "/lionfish_comshop/pages/order/evaluate?id=" + t + "&goods_id=" + a + "&order_goods_id=" + o }) }, gokefu: function(e) { var t = e.currentTarget.dataset.s_id; this.data.goods, this.data.seller_info; 3 < getCurrentPages().length ? wx.redirectTo({ url: "/pages/im/index?id=" + t }) : wx.navigateTo({ url: "/pages/im/index?id=" + t }) }, goRefund: function(e) { var t = e.currentTarget.dataset.id || 0; t && (3 < getCurrentPages().length ? wx.redirectTo({ url: "/lionfish_comshop/pages/order/refunddetail?id=" + t }) : wx.navigateTo({ url: "/lionfish_comshop/pages/order/refunddetail?id=" + t })) }, closeModal: function(e) { var t = {}; 1 == (e.currentTarget.dataset.type || 0) ? t.showRefundModal = !1 : t.isShowModal = !1, this.setData(t) }, cancelOrder: function(a) { var r = this; this.canCancel && wx.showModal({ title: "取消订单并退款", content: "取消订单后,款项将原路退回到您的支付账户;详情请查看退款进度。", confirmText: "取消订单", confirmColor: "#ff5344", cancelText: "再等等", cancelColor: "#666666", success: function(e) { if (e.confirm) { r.canCancel = !1; var t = a.currentTarget.dataset.type, o = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "order.del_cancle_order", token: o, order_id: t }, dataType: "json", method: "POST", success: function(e) { 0 == e.data.code ? wx.showModal({ title: "提示", content: "取消订单成功", showCancel: !1, confirmColor: "#ff5344", success: function(e) { e.confirm && wx.redirectTo({ url: "/lionfish_comshop/pages/order/index" }) } }) : (r.canCancel = !0, wx.showToast({ title: e.data.msg || "取消订单失败", icon: "none" })) } }), console.log("用户点击确定") } else e.cancel && (r.canCancel = !0, console.log("用户点击取消")) } }) }, showRefundInfo: function(e) { var t = e.currentTarget.dataset.idx; if (0 < e.currentTarget.dataset.hasrefund) { var o = this.data.order.order_goods_list[t]; this.setData({ showRefundModal: !0, refundGoodsInfo: o }) } }, onShareAppMessage: function(e) { var t = this.data.order.order_info.order_id || "", o = this.data.order.order_goods_list[0].goods_share_image, a = this.data.share_img; if (t && 1 == this.is_show_tip) return { title: "@" + this.data.order.order_info.ziti_name + this.data.groupInfo.owner_name + ",我是" + this.data.userInfo.shareNickName + ",刚在你这里下单啦!!!", path: "lionfish_comshop/pages/order/shareOrderInfo?order_id=" + t, imageUrl: a || o } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/navigation-bar/navigation-bar.js "use strict"; var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) { return typeof t } : function(t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }; module.exports = function(e) { function n(t) { if (o[t]) return o[t].exports; var i = o[t] = { i: t, l: !1, exports: {} }; return e[t].call(i.exports, i, i.exports, n), i.l = !0, i.exports } var o = {}; return n.m = e, n.c = o, n.d = function(t, e, o) { n.o(t, e) || Object.defineProperty(t, e, { enumerable: !0, get: o }) }, n.r = function(t) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: !0 }) }, n.t = function(e, o) { if (1 & o && (e = n(e)), 8 & o) return e; if (4 & o && "object" === (void 0 === e ? "undefined" : t(e)) && e && e.__esModule) return e; var i = Object.create(null); if (n.r(i), Object.defineProperty(i, "default", { enumerable: !0, value: e }), 2 & o && "string" != typeof e) for (var r in e) n.d(i, r, function(t) { return e[t] }.bind(null, r)); return i }, n.n = function(t) { var e = t && t.__esModule ? function() { return t. default } : function() { return t }; return n.d(e, "a", e), e }, n.o = function(t, e) { return Object.prototype.hasOwnProperty.call(t, e) }, n.p = "", n(n.s = 1) }([, function(t, e, n) { Component({ options: { multipleSlots: !0, addGlobalClass: !0 }, properties: { extClass: { type: String, value: "" }, title: { type: String, value: "" }, background: { type: String, value: "" }, color: { type: String, value: "" }, back: { type: Boolean, value: !0 }, loading: { type: Boolean, value: !1 }, animated: { type: Boolean, value: !0 }, show: { type: Boolean, value: !0, observer: "_showChange" }, delta: { type: Number, value: 1 } }, data: { displayStyle: "" }, attached: function() { var t = this, e = !! wx.getMenuButtonBoundingClientRect, n = wx.getMenuButtonBoundingClientRect ? wx.getMenuButtonBoundingClientRect() : null; wx.getSystemInfo({ success: function(o) { var i = !! (o.system.toLowerCase().search("ios") + 1); t.setData({ ios: i, statusBarHeight: o.statusBarHeight, innerWidth: e ? "width:" + n.left + "px" : "", innerPaddingRight: e ? "padding-right:" + (o.windowWidth - n.left) + "px" : "", leftWidth: e ? "width:" + (o.windowWidth - n.left) + "px" : "" }) } }) }, methods: { _showChange: function(t) { var e = ""; e = this.data.animated ? "opacity: " + (t ? "1" : "0") + ";-webkit-transition:opacity 0.5s;transition:opacity 0.5s;" : "display: " + (t ? "" : "none"), this.setData({ displayStyle: e }) }, back: function() { var t = this.data; wx.navigateBack({ delta: t.delta }), this.triggerEvent("back", { delta: t.delta }, {}) } } }) }]);<file_sep>/lionfish_comshop/pages/order/placeOrder.js var _extends = Object.assign || function(e) { for (var t = 1; t < arguments.length; t++) { var a = arguments[t]; for (var i in a) Object.prototype.hasOwnProperty.call(a, i) && (e[i] = a[i]) } return e }, app = getApp(), locat = require("../../utils/Location.js"), util = require("../../utils/util.js"), status = require("../../utils/index.js"), wcache = require("../../utils/wcache.js"); Page({ data: { payBtnLoading: !1, showConfirmModal: !1, receiverAddress: "", tuan_send_address: "", showGetPhone: !1, lou_meng_hao: "", pickUpAddress: "", disUserName: "", pickUpCommunityName: "", is_limit_distance_buy: 0, tabList: [{ id: 0, name: "到点自提", dispatching: "pickup", enabled: !1 }, { id: 1, name: "免费配送", dispatching: "tuanz_send", enabled: !1 }, { id: 2, name: "快递配送", dispatching: "express", enabled: !1 }], originTabList: [{ id: 0, name: "到点自提", dispatching: "pickup" }, { id: 1, name: "免费配送", dispatching: "tuanz_send" }, { id: 2, name: "快递配送", dispatching: "express" }], tabIdx: 0, region: ["选择地址", "", ""], tot_price: 0, needAuth: !1, reduce_money: 0, hide_quan: !0, tuan_region: ["选择地址", "", ""], groupInfo: { group_name: "社区", owner_name: "团长", placeorder_tuan_name: "配送费", placeorder_trans_name: "快递费" }, comment: "", is_yue_open: 0, can_yupay: 0, ck_yupay: 0, use_score: 0, commentArr: {} }, canPay: !0, canPreSub: !0, onLoad: function(e) { var F = this; status.setGroupInfo().then(function(e) { F.setData({ groupInfo: e }) }); var t = wx.getStorageSync("token"), a = wx.getStorageSync("community"), i = a.communityId; util.check_login() ? this.setData({ needAuth: !1 }) : (this.setData({ needAuth: !0 }), wx.hideTabBar()); var o = e.is_limit || 0; this.setData({ buy_type: e.type || "", soli_id: e.soli_id || "", pickUpAddress: a.fullAddress || "", pickUpCommunityName: a.communityName || "", disUserName: a.disUserName || "" }), wx.showLoading(); var s = wx.getStorageSync("latitude2"), n = wx.getStorageSync("longitude2"); function r() { app.util.request({ url: "entry/wxapp/user", data: { controller: "car.checkout", token: t, community_id: i, buy_type: e.type, soli_id: e.soli_id }, dataType: "json", method: "POST", success: function(e) { setTimeout(function() { wx.hideLoading() }, 1e3); var t = e.data, a = 0, i = 0, o = F.data.tabList, s = [], n = e.data, r = n.delivery_express_name, d = n.delivery_tuanzshipping_name, c = n.delivery_ziti_name, _ = n.delivery_diy_sort, u = n.delivery_type_express, l = n.delivery_type_tuanz, h = n.delivery_type_ziti, p = n.delivery_tuanz_money, m = n.is_vip_card_member, y = n.vipcard_save_money, g = n.level_save_money, f = n.is_open_vipcard_buy, v = n.is_member_level_buy, b = n.total_integral, x = n.is_need_subscript, w = n.need_subscript_template, S = n.is_hexiao, A = !1; if (1 == f ? 1 != m && 1 == v && (A = !0) : 1 == v && (A = !0), 1 == u && (o[2].enabled = !0, i++), 1 == l && (o[1].enabled = !0, i++), 1 == h && (o[0].enabled = !0, i++), _) { var k = _.split(","); k[2] && o[k[2]] && o[k[2]].enabled && (a = k[2]), k[1] && o[k[1]] && o[k[1]].enabled && (a = k[1]), k[0] && o[k[0]] && o[k[0]].enabled && (a = k[0]), k.forEach(function(e) { s.push(o[e]) }) } r && (o[2].name = r), d && (o[1].name = d), c && (o[0].name = c); 1 == a || 2 == a && t.trans_free_toal; var T = 0, D = 0, P = t.seller_goodss, z = (Object.keys(P).length, {}); for (var I in P) z[I] = ""; var L = ""; for (var O in P) for (var j in 1 == P[O].show_voucher && (P[O].chose_vouche.id && (T = P[O].chose_vouche.id), P[O].chose_vouche.store_id && (D = P[O].chose_vouche.store_id), "[object Object]" == Object.prototype.toString.call(P[O].chose_vouche) && (L = P[O].chose_vouche)), P[O].goodsnum = Object.keys(P[O].goods).length, P[O].goods) 0 < P[O].goods[j].header_disc && P[O].goods[j].header_disc < 100 && (P[O].goods[j].header_disc = (P[O].goods[j].header_disc / 10).toFixed(1)); var N = { is_hexiao: S, loadover: !0, commentArr: z, sel_chose_vouche: L, tabList: s, is_limit_distance_buy: t.is_limit_distance_buy || 0, tabIdx: a, tabLength: i, tuan_send_address: t.tuan_send_address, is_open_order_message: t.is_open_order_message, is_yue_open: t.is_yue_open, can_yupay: t.can_yupay, show_voucher: t.show_voucher, current_distance: t.current_distance || "", man_free_tuanzshipping: 1 * t.man_free_tuanzshipping || 0, man_free_shipping: 1 * t.man_free_shipping || 0, index_hide_headdetail_address: t.index_hide_headdetail_address || 0, open_score_buy_score: t.open_score_buy_score || 0, score: t.score || 0, score_for_money: t.score_for_money || 0, bue_use_score: t.bue_use_score || 0, is_man_delivery_tuanz_fare: t.is_man_delivery_tuanz_fare, fare_man_delivery_tuanz_fare_money: t.fare_man_delivery_tuanz_fare_money, is_man_shipping_fare: t.is_man_shipping_fare, fare_man_shipping_fare_money: t.fare_man_shipping_fare_money, is_vip_card_member: m, vipcard_save_money: y, level_save_money: g, is_open_vipcard_buy: f, is_member_level_buy: v, canLevelBuy: A, total_integral: b || "", is_need_subscript: x, need_subscript_template: w }, q = t.address, C = t.tuan_send_address_info, M = C.address || "选择位置"; "" != C.city_name && 3708 != C.city_id && "" != C.country_name && 3708 != C.country_id || (M = "选择位置"), N.tabAddress = [{ name: t.ziti_name || "", mobile: t.ziti_mobile || "" }, { name: C.name || "", mobile: C.telephone || "", receiverAddress: M, lou_meng_hao: C.lou_meng_hao || "", region: [C.province_name || "", C.city_name || "", C.country_name || ""] }, { name: q.name || "", mobile: q.telephone || "", receiverAddress: q.address || "", region: [q.province_name || "选择地址", q.city_name || "", q.country_name || ""] }], F.setData(_extends({}, N, { pick_up_time: e.data.pick_up_time, pick_up_type: e.data.pick_up_type, pick_up_weekday: e.data.pick_up_weekday, addressState: !0, is_integer: e.data.is_integer, is_ziti: e.data.is_ziti, pick_up_arr: e.data.pick_up_arr, seller_goodss: e.data.seller_goodss, seller_chose_id: T, seller_chose_store_id: D, goods: e.data.goods, buy_type: e.data.buy_type, yupay: e.data.can_yupay, is_yue_open: e.data.is_yue_open, yu_money: e.data.yu_money, total_free: e.data.total_free, trans_free_toal: e.data.trans_free_toal, delivery_tuanz_money: e.data.delivery_tuanz_money, reduce_money: e.data.reduce_money, is_open_fullreduction: e.data.is_open_fullreduction, cha_reduce_money: e.data.cha_reduce_money }), function() { F.calcPrice() }) } }) } 1 == o && s && n && console.log("---------is here ?-----------"), r() }, authSuccess: function() { this.onLoad() }, getReceiveMobile: function(e) { var t = e.detail; this.setData({ t_ziti_mobile: t, showGetPhone: !1 }) }, ck_wxpays: function() { this.setData({ ck_yupay: 0 }) }, ck_yupays: function() { this.setData({ ck_yupay: 1 }) }, scoreChange: function(e) { console.log("是否使用", e.detail.value); var t = this.data, a = 1 * t.score_for_money, i = 1 * t.tot_price, o = 1 * t.disAmount; console.log("score_for_money", a); console.log("tot_price", i); console.log("disAmount", o); e.detail.value ? (i = (i - a).toFixed(2), o += a) : (i = (i + a).toFixed(2), o -= a), this.setData({ use_score: e.detail.value ? 1 : 0, tot_price: i, disAmount: o.toFixed(2) }) }, needAuth: function() { this.setData({ needAuth: !0 }) }, close: function() { this.setData({ showGetPhone: !1 }) }, goOrderfrom: function() { var e = this.data, t = e.tabAddress, a = e.tabIdx, i = t[a].name, o = t[a].mobile, s = t[a].receiverAddress, n = t[a].region, r = t[a].receiverAddress, d = t[a].lou_meng_hao; if ("" == i) { this.setData({ focus_name: !0 }); var c = "请填写收货人"; return 0 == a && (c = "请填写提货人"), wx.showToast({ title: c, icon: "none" }), !1 } if ("" == o || !/^1(3|4|5|6|7|8|9)\d{9}$/.test(o)) return this.setData({ focus_mobile: !0 }), wx.showToast({ title: "手机号码有误", icon: "none" }), !1; if (2 == a && "选择地址" == n[0]) return wx.showToast({ title: "请选择所在地区", icon: "none" }), !1; if (2 == a && "" == s) return this.setData({ focus_addr: !0 }), wx.showToast({ title: "请填写详细地址", icon: "none" }), !1; if (1 == a) { if ("选择位置" == r || "" == r) return wx.showToast({ title: "请选择位置", icon: "none" }), !1; if ("" == d) return wx.showToast({ title: "输入楼号门牌", icon: "none" }), !1 } 2 == a ? this.preSubscript() : this.conformOrder() }, preSubscript: function() { var e = this; this.canPreSub && (this.canPreSub = !1, 1 == this.data.is_need_subscript ? this.subscriptionNotice().then(function() { e.prepay() }). catch (function() { e.prepay() }) : e.prepay()) }, prepay: function() { this.canPreSub = !0; var e = this.data, t = e.tabAddress, a = e.tabIdx; if (1 == e.is_limit_distance_buy && 1 == a) return wx.showModal({ title: "提示", content: "离团长太远了,暂不支持下单", showCancel: !1, confirmColor: "#F75451" }), !1; if (this.canPay) { this.setData({ payBtnLoading: !0 }), this.canPay = !1; var o = this, i = this.data, s = wx.getStorageSync("token"), n = this.data, r = n.seller_chose_id, d = n.seller_chose_store_id, c = n.ck_yupay, _ = n.tabList, u = r, l = ""; _.forEach(function(e) { e.id == a && (l = e.dispatching) }); var h = i.commentArr, p = []; for (var m in h) p.push(h[m]); var y = p.join("@EOF@"), g = t[a].receiverAddress || "", f = t[a].region || [], v = t[a].name, b = t[a].mobile, x = t[a].lou_meng_hao || "", w = []; if (0 < u) { var S = d + "_" + u; w.push(S) } var A = "", k = "", T = "", D = "", P = "", z = ""; 1 == a ? (A = g, D = (k = f)[0], P = k[1], z = k[2]) : 2 == a && (T = g, D = f[0], P = f[1], z = f[2]); var I = wx.getStorageSync("community").communityId, L = wx.getStorageSync("latitude2"), O = wx.getStorageSync("longitude2"), j = this.data, N = j.use_score, q = j.buy_type, C = j.soli_id; wx.showLoading(), app.util.request({ url: "entry/wxapp/user", data: { controller: "car.sub_order", token: s, pay_method: "wxpay", buy_type: q, pick_up_id: I, dispatching: l, ziti_name: v, quan_arr: w, comment: y, ziti_mobile: b, latitude: L, longitude: O, ck_yupay: c, tuan_send_address: A, lou_meng_hao: x, address_name: T, province_name: D, city_name: P, country_name: z, use_score: N, soli_id: C }, dataType: "json", method: "POST", success: function(t) { wx.hideLoading(); var e = t.data.has_yupay || 0, a = t.data.order_id, i = {}; console.log("支付日志:", t), 0 == t.data.code ? (o.changeIndexList(), 1 == e ? (o.canPay = !0, "dan" == q || "pindan" == q || "integral" == q || "soitaire" == q ? t.data.is_go_orderlist <= 1 ? wx.redirectTo({ url: "/lionfish_comshop/pages/order/order?id=" + a + "&is_show=1" }) : wx.redirectTo({ url: "/lionfish_comshop/pages/order/index?is_show=1" }) : wx.redirectTo({ url: "/lionfish_comshop/moduleA/pin/share?id=" + a })) : wx.requestPayment({ appId: t.data.appId, timeStamp: t.data.timeStamp, nonceStr: t.data.nonceStr, package: t.data.package, signType: t.data.signType, paySign: t.data.paySign, success: function(e) { o.canPay = !0, "dan" == q || "pindan" == q || "integral" == q || "soitaire" == q ? t.data.is_go_orderlist <= 1 ? wx.redirectTo({ url: "/lionfish_comshop/pages/order/order?id=" + a + "&is_show=1" }) : wx.redirectTo({ url: "/lionfish_comshop/pages/order/index?is_show=1" }) : wx.redirectTo({ url: "/lionfish_comshop/moduleA/pin/share?id=" + a }) }, fail: function(e) { t.data.is_go_orderlist <= 1 ? wx.redirectTo({ url: "/lionfish_comshop/pages/order/order?id=" + a + "&?isfail=1" }) : wx.redirectTo({ url: "/lionfish_comshop/pages/order/index?isfail=1" }) } })) : 1 == t.data.code ? (o.canPay = !0, wx.showModal({ title: "提示", content: t.data.RETURN_MSG || "支付失败", showCancel: !1, confirmColor: "#F75451", success: function(e) { e.confirm && (t.data.is_go_orderlist <= 1 ? wx.redirectTo({ url: "/lionfish_comshop/pages/order/order?id=" + a + "&isfail=1" }) : wx.redirectTo({ url: "/lionfish_comshop/pages/order/index?is_show=1&?isfail=1" })) } })) : 2 == t.data.code ? (o.canPay = !0, 1 == t.data.is_forb && (i.btnDisable = !0, i.btnText = "已抢光"), wx.showToast({ title: t.data.msg, icon: "none" })) : console.log(t), o.setData(_extends({ btnLoading: !1, payBtnLoading: !1 }, i)) } }) } }, changeReceiverName: function(e) { var t = this.data, a = t.tabAddress, i = t.tabIdx, o = e.detail.value.trim(); if (!(a[i].name = o)) { var s = "请填写收货人"; 0 == i && (s = "请填写提货人"), wx.showToast({ title: s, icon: "none" }) } return this.setData({ tabAddress: a }), { value: o } }, bindReceiverMobile: function(e) { var t = this.data, a = t.tabAddress, i = t.tabIdx, o = e.detail.value.trim(); return a[i].mobile = o, this.setData({ tabAddress: a }), { value: o } }, changeReceiverAddress: function(e) { var t = this.data, a = t.tabAddress; return a[t.tabIdx].receiverAddress = e.detail.value.trim(), this.setData({ tabAddress: a }), { value: e.detail.value.trim() } }, changeTuanAddress: function(e) { var t = this.data, a = t.tabAddress; return a[t.tabIdx].lou_meng_hao = e.detail.value.trim(), this.setData({ tabAddress: a }), { value: e.detail.value.trim() } }, conformOrder: function() { this.setData({ showConfirmModal: !0 }) }, closeConfirmModal: function() { this.canPay = !0, this.setData({ showConfirmModal: !1 }) }, bindRegionChange: function(e) { var t = e.detail.value; t && this.checkOut(t[1]), this.setData({ region: t }) }, checkOut: function(e) { var r = this, t = wx.getStorageSync("token"), a = wx.getStorageSync("community").communityId, i = wx.getStorageSync("latitude2"), o = wx.getStorageSync("longitude2"), s = this.data.buy_type, n = this.data.soli_id; console.log(i);console.log(o); app.util.request({ url: "entry/wxapp/user", data: { controller: "car.checkout", token: t, community_id: a, mb_city_name: e, latitude: i, longitude: o, buy_type: s, soli_id: n }, dataType: "json", method: "POST", success: function(e) { console.log(e); if (1 == e.data.code) { var t = e.data, a = t.vipcard_save_money, i = t.shop_buy_distance, o = t.is_limit_distance_buy, s = t.current_distance, n = t.level_save_money; 1 == r.data.tabIdx && 1 == o && i < s && wx.showModal({ title: "提示", content: "超出配送范围,请重新选择", showCancel: !1, confirmColor: "#F75451" }), r.setData({ vipcard_save_money: a, level_save_money: n, is_limit_distance_buy: o || 0, current_distance: s || "", trans_free_toal: t.trans_free_toal, is_man_delivery_tuanz_fare: t.is_man_delivery_tuanz_fare, fare_man_delivery_tuanz_fare_money: t.fare_man_delivery_tuanz_fare_money, is_man_shipping_fare: t.is_man_shipping_fare, fare_man_shipping_fare_money: t.fare_man_shipping_fare_money }, function() { r.calcPrice() }) } } }) }, choseLocation: function() { var e = this.data, s = e.tabAddress, n = e.tabIdx, r = this; wx.chooseLocation({ success: function(e) { console.log(e); var t = r.data.region, a = e.name, i = (e.address, null); function o() { console.log("setData"), t && "市" != t[1] && r.checkOut(t[1]), s[n].region = t, s[n].receiverAddress = a, r.setData({ tabAddress: s }) } console.log("patt", i), locat.getGpsLocation(e.latitude, e.longitude).then(function(e) { console.log("反推了", e), e && (t[0] = e.province, t[1] = e.city, t[2] = e.district, a || (a = e.street)), o() }), wcache.put("latitude2", e.latitude), wcache.put("longitude2", e.longitude) }, fail: function(e) { console.log(e), "chooseLocation:fail auth deny" == e.errMsg && (console.log("无权限"), locat.checkGPS(app, locat.openSetting())) } }) }, getWxAddress: function() { var e = this.data, a = e.tabAddress, i = e.tabIdx, o = a[i].region || [], s = this; wx.getSetting({ success: function(e) { console.log("vres.authSetting['scope.address']:", e.authSetting["scope.address"]), e.authSetting["scope.address"] ? wx.chooseAddress({ success: function(e) { console.log("step1"), o[0] = e.provinceName || "选择地址", o[1] = e.cityName || "", o[2] = e.countyName || ""; var t = e.detailInfo; a[i].name = e.userName, a[i].mobile = e.telNumber, a[i].region = o, a[i].receiverAddress = t, s.setData({ tabAddress: a }), o && "市" != o[1] && s.checkOut(o[1]) }, fail: function(e) { console.log("step4"), console.log(e) } }) : 0 == e.authSetting["scope.address"] ? wx.openSetting({ success: function(e) { console.log(e.authSetting) } }) : (console.log("step2"), wx.chooseAddress({ success: function(e) { console.log("step3"), o[0] = e.provinceName || "选择地址", o[1] = e.cityName || "", o[2] = e.countyName || ""; var t = e.detailInfo; o && "市" != o[1] && s.checkOut(o[1]), a[i].name = e.userName, a[i].mobile = e.telNumber, a[i].region = o, a[i].receiverAddress = t, s.setData({ tabAddress: a }) } })) } }) }, tabSwitch: function(e) { var t = 1 * e.currentTarget.dataset.idx; console.log(t); 0 != t && wx.showToast({ title: "配送变更,费用已变化", icon: "none" }), this.setData({ tabIdx: t }, function() { this.calcPrice(1) }) }, show_voucher: function(e) { var t = e.currentTarget.dataset.seller_id, a = [], i = this.data.seller_chose_id, o = this.data.seller_chose_store_id, s = this.data.seller_goodss; for (var n in s) { s[n].store_info.s_id == t && (a = s[n].voucher_list, 0 == i && (i = s[n].chose_vouche.id || 0, o = s[n].chose_vouche.store_id || 0)) } this.setData({ ssvoucher_list: a, voucher_serller_id: t, seller_chose_id: i, seller_chose_store_id: o, hide_quan: !1 }) }, chose_voucher_id: function(e) { wx.showLoading(); var s = e.currentTarget.dataset.voucher_id, n = e.currentTarget.dataset.seller_id, r = this, t = wx.getStorageSync("token"), a = n + "_" + s, i = wx.getStorageSync("latitude2"), o = wx.getStorageSync("longitude2"), d = r.data.buy_type, c = this.data.soli_id, _ = wx.getStorageSync("community").communityId || ""; app.util.request({ url: "entry/wxapp/user", data: { controller: "car.checkout", token: t, community_id: _, voucher_id: s, use_quan_str: a, buy_type: d, latitude: i, longitude: o, soli_id: c }, dataType: "json", method: "POST", success: function(e) { if (wx.hideLoading(), 1 == e.data.code) { var t = e.data.seller_goodss, a = ""; for (var i in t) t[i].goodsnum = Object.keys(t[i].goods).length, "[object Object]" == Object.prototype.toString.call(t[i].chose_vouche) && (a = t[i].chose_vouche); var o = e.data; r.setData({ seller_goodss: t, seller_chose_id: s, seller_chose_store_id: n, hide_quan: !0, goods: o.goods, buy_type: o.buy_type || "dan", yupay: o.can_yupay, is_yue_open: o.is_yue_open, total_free: o.total_free, sel_chose_vouche: a, current_distance: o.current_distance || "" }, function() { r.calcPrice() }) } } }) }, closeCouponModal: function() { this.setData({ hide_quan: !0 }) }, calcPrice: function() { console.log(arguments); var e = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : 0, t = this.data, a = t.total_free, i = t.delivery_tuanz_money, o = t.trans_free_toal, s = t.tabIdx, n = t.goods, r = (t.is_open_vipcard_buy, t.is_member_level_buy, t.is_vip_card_member, t.canLevelBuy); a *= 1, i *= 1, o *= 1; var d = 0, c = 0, _ = 0, u = !0, l = !1, h = void 0; try { for (var p, m = Object.keys(n)[Symbol.iterator](); !(u = (p = m.next()).done); u = !0) { var y = n[p.value]; c += y.total, r && y.is_mb_level_buy && (_ += 1 * y.total - 1 * y.level_total) } } catch (e) { l = !0, h = e } finally { try { !u && m. return &&m. return () } finally { if (l) throw h } } console.log(c); var g = c; if (0 == s) d = a; else if (1 == s) { d = 0 == t.is_man_delivery_tuanz_fare ? i + a : a, g += i } else if (2 == s) { g += o, d = 0 == t.is_man_shipping_fare ? o + a : a } var f = t.use_score; f && (d -= 1 * t.score_for_money); var v; v = (g - 1 * d).toFixed(2), this.setData({ total_all: g.toFixed(2), disAmount: v, tot_price: d.toFixed(2), total_goods_price: c.toFixed(2), levelAmount: _.toFixed(2) }) }, bindInputMessage: function(e) { var t = this.data.commentArr, a = e.currentTarget.dataset.idx, i = e.detail.value; t[a] = i, this.setData({ commentArr: t }) }, changeIndexList: function() { var e = this.data.goods || []; 0 < e.length && e.forEach(function(e) { 0 == e.option.length && status.indexListCarCount(e.goods_id, 0) }) }, subscriptionNotice: function() { console.log("subscriptionNotice"); var s = this; return new Promise(function(e, t) { var o = s.data.need_subscript_template, a = Object.keys(o).map(function(e) { return o[e] }); wx.requestSubscribeMessage ? a.length && wx.requestSubscribeMessage({ tmplIds: a, success: function(t) { var a = 1, i = []; Object.keys(o).forEach(function(e) { "accept" == t[o[e]] ? i.push(e) : a = 0 }), i.length && s.addAccept(i), s.setData({ is_need_subscript: a }), e() }, fail: function() { t() } }) : t() }) }, addAccept: function(e) { var t = wx.getStorageSync("token"), a = e.join(","); app.util.request({ url: "entry/wxapp/user", data: { controller: "user.collect_subscriptmsg", token: t, type: a }, dataType: "json", method: "POST", success: function() {} }) } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/cells/cells.js "use strict"; var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) { return typeof t } : function(t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }; module.exports = function(e) { function o(t) { if (n[t]) return n[t].exports; var r = n[t] = { i: t, l: !1, exports: {} }; return e[t].call(r.exports, r, r.exports, o), r.l = !0, r.exports } var n = {}; return o.m = e, o.c = n, o.d = function(t, e, n) { o.o(t, e) || Object.defineProperty(t, e, { enumerable: !0, get: n }) }, o.r = function(t) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: !0 }) }, o.t = function(e, n) { if (1 & n && (e = o(e)), 8 & n) return e; if (4 & n && "object" === (void 0 === e ? "undefined" : t(e)) && e && e.__esModule) return e; var r = Object.create(null); if (o.r(r), Object.defineProperty(r, "default", { enumerable: !0, value: e }), 2 & n && "string" != typeof e) for (var u in e) o.d(r, u, function(t) { return e[t] }.bind(null, u)); return r }, o.n = function(t) { var e = t && t.__esModule ? function() { return t. default } : function() { return t }; return o.d(e, "a", e), e }, o.o = function(t, e) { return Object.prototype.hasOwnProperty.call(t, e) }, o.p = "", o(o.s = 6) }({ 6: function(t, e, o) { Component({ options: { addGlobalClass: !0, multipleSlots: !0 }, properties: { title: { type: String, value: "" }, extClass: { type: String, value: "" }, footer: { type: String, value: "" } }, data: { firstItem: null, checkboxCount: 0, checkboxIsMulti: !1 }, relations: { "../cell/cell": { type: "descendant", linked: function(t) { this.data.firstItem || (this.data.firstItem = t), t !== this.data.firstItem && t.setOuterClass("weui-cell_wxss") } }, "../checkbox-group/checkbox-group": { type: "descendant", linked: function(t) { this.setData({ checkboxCount: this.data.checkboxCount + 1, checkboxIsMulti: t.data.multi }) }, unlinked: function(t) { this.setData({ checkboxCount: this.data.checkboxCount - 1, checkboxIsMulti: t.data.multi }) } } }, methods: { setCellMulti: function(t) { this.setData({ checkboxIsMulti: t }) } } }) } });<file_sep>/lionfish_comshop/pages/user/articleProtocol.js var app = getApp(),WxParse = require("../../wxParse/wxParse.js"); Page({ data: { list: "" }, token: "", articleId: 0, onLoad: function(t) { var a = t.id || 0; this.articleId = a; var e = t.about || 0, i = wx.getStorageSync("token"); this.token = i, wx.showLoading({ title: "加载中" }), e ? this.get_about_us() : this.get_article() }, get_article: function() { var e = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "article.get_article", token: e.token, id: e.articleId }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var a = t.data.data; var b = a.content; var c = WxParse.wxParse("instructions", "html", b, e, 0); e.setData({ article: c }), wx.setNavigationBarTitle({ title: a.title }) } } }) }, get_about_us: function() { var e = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "user.get_about_us" }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var a = t.data.data; e.setData({ article: a }), wx.setNavigationBarTitle({ title: "关于我们" }) } } }) }, onShareAppMessage: function() {} });<file_sep>/lionfish_comshop/moduleA/components/cartModal.js var app = getApp(); Component({ properties: { show: { type: Boolean, value: !1 }, carts: { type: Object || Array, value: {} }, soliId: { type: Number, value: 0 }, stitle: { type: String, value: "已选商品" } }, data: { token: "", community: "" }, attached: function() { var t = wx.getStorageSync("token"), a = wx.getStorageSync("community"); this.setData({ token: t, community: a }) }, methods: { changeNumber: function(t) { var a = this, o = t.currentTarget.dataset.cartid, e = t.currentTarget.dataset.gidx, r = t.detail.value; if (0 == r) this.cofirm_del(o, e); else { var s = a.data.carts, n = s[o].shopcarts[e].goodsnum; s[o].shopcarts[e].goodsnum = r, this.setData({ carts: s }, function() { a.go_record().then(function() { a.triggerEvent("changeCart", s) }). catch (function() { s[o].shopcarts[e].goodsnum = n, a.setData({ carts: s }) }) }) } }, handleModal: function() { console.log("关闭购物车弹窗"), this.triggerEvent("hideModal") }, cofirm_del: function(e, r) { var s = this; wx.showModal({ title: "提示", content: "确定删除这件商品吗?", confirmColor: "#FF0000", success: function(t) { if (t.confirm) { var a = s.data.carts, o = a[e].shopcarts[r].key; a[e].shopcarts.splice(r, 1), s.setData({ carts: a }), s.del_car_goods(o) } else console.log("取消删除") } }) }, del_car_goods: function(t) { var a = this; console.log("del_car_goods:开始"); var o = this.data, e = o.token, r = o.community.communityId; app.util.request({ url: "entry/wxapp/index", data: { controller: "car.del_car_goods", carkey: t, community_id: r, token: e }, method: "POST", dataType: "json", success: function(t) { 0 == t.data.code && a.triggerEvent("changeCart", a.data.carts) } }) }, go_record: function() { var h = this; return new Promise(function(a, o) { var t = h.data, e = t.carts, r = t.token, s = t.community, n = t.soliId, c = [], i = [], d = s.communityId; for (var u in e) for (var l in e[u].shopcarts) c.push(e[u].shopcarts[l].key), i.push(e[u].shopcarts[l].key + "_" + e[u].shopcarts[l].goodsnum); app.util.request({ url: "entry/wxapp/index", data: { controller: "car.checkout_flushall", token: r, car_key: c, community_id: d, all_keys_arr: i, buy_type: "soitaire", soli_id: n }, method: "POST", dataType: "json", success: function(t) { 0 == t.data.code ? a() : (wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }), o()) } }) }) } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/cell/cell.js "use strict"; var e = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e) { return typeof e } : function(e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }; module.exports = function(t) { function r(e) { if (n[e]) return n[e].exports; var o = n[e] = { i: e, l: !1, exports: {} }; return t[e].call(o.exports, o, o.exports, r), o.l = !0, o.exports } var n = {}; return r.m = t, r.c = n, r.d = function(e, t, n) { r.o(e, t) || Object.defineProperty(e, t, { enumerable: !0, get: n }) }, r.r = function(e) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(e, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(e, "__esModule", { value: !0 }) }, r.t = function(t, n) { if (1 & n && (t = r(t)), 8 & n) return t; if (4 & n && "object" === (void 0 === t ? "undefined" : e(t)) && t && t.__esModule) return t; var o = Object.create(null); if (r.r(o), Object.defineProperty(o, "default", { enumerable: !0, value: t }), 2 & n && "string" != typeof t) for (var l in t) r.d(o, l, function(e) { return t[e] }.bind(null, l)); return o }, r.n = function(e) { var t = e && e.__esModule ? function() { return e. default } : function() { return e }; return r.d(t, "a", t), t }, r.o = function(e, t) { return Object.prototype.hasOwnProperty.call(e, t) }, r.p = "", r(r.s = 7) }({ 7: function(e, t, r) { Component({ options: { addGlobalClass: !0, multipleSlots: !0 }, properties: { hover: { type: Boolean, value: !1 }, link: { type: Boolean, value: !1 }, extClass: { type: String, value: "" }, iconClass: { type: String, value: "" }, icon: { type: String, value: "" }, title: { type: String, value: "" }, value: { type: String, value: "" }, showError: { type: Boolean, value: !1 }, prop: { type: String, value: "" }, url: { type: String, value: "" }, footerClass: { type: String, value: "" }, footer: { type: String, value: "" }, inline: { type: Boolean, value: !0 } }, relations: { "../form/form": { type: "ancestor" }, "../cells/cells": { type: "ancestor" } }, data: { inForm: !1 }, methods: { setError: function(e) { this.setData({ error: e || !1 }) }, setInForm: function() { this.setData({ inForm: !0 }) }, setOuterClass: function(e) { this.setData({ outerClass: e }) }, navigateTo: function() { var e = this, t = this.data; t.url && t.link && wx.navigateTo({ url: t.url, success: function(t) { e.triggerEvent("navigatesuccess", t, {}) }, fail: function(t) { e.triggerEvent("navigateerror", t, {}) } }) } } }) } });<file_sep>/lionfish_comshop/utils/util.js var _extends = Object.assign || function (e) { for (var t = 1; t < arguments.length; t++) { var n = arguments[t]; for (var o in n) Object.prototype.hasOwnProperty.call(n, o) && (e[o] = n[o]) } return e }; function getdomain() { var e = getApp(); return e.siteInfo.uniacid + "_" + e.siteInfo.siteroot } function api() { return "https://mall.shiziyu888.com/dan/" } function check_login() { var e = wx.getStorageSync("token"), t = wx.getStorageSync("member_id"); return !!(e && null != t && 0 < t.length) } function check_login_new() { var n = wx.getStorageSync("token"), o = wx.getStorageSync("member_id"); return new Promise(function (e, t) { wx.checkSession({ success: function () { console.log("checkSession 未过期"), n && null != o && 0 < o.length ? e(!0) : e(!1) }, fail: function () { console.log("checkSession 过期"), e(!1) } }) }) } function checkRedirectTo(e, t) { var n = !1; if (t) { -1 !== ["/lionfish_comshop/pages/groupCenter/apply", "/lionfish_comshop/pages/supply/apply", "/lionfish_comshop/pages/user/charge", "/lionfish_comshop/pages/order/index", "/lionfish_comshop/moduleA/solitaire/index"].indexOf(e) && (n = !0) } return n } function login(o) { console.error(o, '我是进入的o1111111111111111'); var i = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : 0, a = getApp(), r = wx.getStorageSync("share_id"); null == r && (r = "0"), wx.login({ success: function (e) { e.code && (console.log(e.code), a.util.request({ url: "entry/wxapp/user", data: { controller: "user.applogin", code: e.code }, dataType: "json", success: function (n) { console.log(n), wx.setStorage({ key: "token", data: n.data.token }), // 修改 // wx.getUserProfile({ // desc: '用于完善会员资料', // 声明获取用户个人信息后的用途,后续会展示在弹窗中,请谨慎填写 // success: (e) => { // var t = e.userInfo; // wx.setStorage({ // key: "userInfo", // data: t // }), console.log(e.userInfo), a.util.request({ // url: "entry/wxapp/user", // data: { // controller: "user.applogin_do", // token: n.data.token, // share_id: r, // nickName: e.userInfo.nickName, // avatarUrl: e.userInfo.avatarUrl, // encrypteddata: e.encryptedData, // iv: e.iv // }, // method: "post", // dataType: "json", // success: function (e) { // console.error('我进入的是第一个呢'); // wx.setStorage({ // key: "member_id", // data: e.data.member_id // }), wx.showToast({ // title: "资料已更新", // icon: "success", // duration: 2e3, // success: function () { // o && 0 < o.length && (1 == i ? wx.switchTab({ // url: o // }) : wx.redirectTo({ // url: o // })) // } // }) // } // }) // } // }) // 修改 wx.getUserInfo({ success: function(e) { var t = e.userInfo; wx.setStorage({ key: "userInfo", data: t }), console.log(e.userInfo), a.util.request({ url: "entry/wxapp/user", data: { controller: "user.applogin_do", token: n.data.token, share_id: r, nickName: e.userInfo.nickName, avatarUrl: e.userInfo.avatarUrl, encrypteddata: e.encryptedData, iv: e.iv }, method: "post", dataType: "json", success: function(e) { console.error('我进入的是第一个呢'); wx.setStorage({ key: "member_id", data: e.data.member_id }), wx.showToast({ title: "资料已更新", icon: "success", duration: 2e3, success: function() { o && 0 < o.length && (1 == i ? wx.switchTab({ url: o }) : wx.redirectTo({ url: o })) } }) } }) }, fail: function(e) {} }) } })) } }) } function login_prosime(needPosition, userFile) { console.log(userFile); //因为无法手动触发所以调用传参 上面的userFile 也是传参的参数 var o = !(0 < arguments.length && void 0 !== arguments[0]) || arguments[0]; return new Promise(function (t, n) { getCode().then(function (e) { console.error('进来了111'); wxGetUserInfo(o, e, userFile).then(function (e) { t(e) }). catch(function (e) { console.error('进来了2222'); console.log(e), n(e) }) }) }) } function getCode() { return new Promise(function (t, n) { var o = getApp(); wx.login({ success: function (e) { e.code ? (console.log(e.code), o.util.request({ url: "entry/wxapp/user", data: { controller: "user.applogin", code: e.code }, dataType: "json", success: function (e) { t(e.data.token), wx.setStorage({ key: "token", data: e.data.token }) } })) : n(e.errMsg) } }) }) } function wxGetUserInfo(r, s, userFile) { var userFileT = userFile.userInfo; var userFileE = userFile; return new Promise(function (n, t) { // console.error(userFile, '测试数据'); // let userFile = userFile; //新增 var o = getApp(), i = wx.getStorageSync("share_id"); null == i && (i = "0"); var e = wx.getStorageSync("community"), a = e && (e.communityId || 0); e && wx.setStorageSync("lastCommunity", e), // 修改 // t = userFile.userInfo; wx.setStorage({ key: "userInfo", data: userFileT }), console.log(e.userInfo), o.util.request({ url: "entry/wxapp/user", data: { controller: "user.applogin_do", token: s, share_id: i, nickName: userFileE.userInfo.nickName, avatarUrl: userFileE.userInfo.avatarUrl, encrypteddata: userFileE.encryptedData, iv: userFileE.iv, community_id: a }, method: "post", dataType: "json", success: function (e) { console.error('我进入的是第二个呢'); 1 == (e.data.isblack || 0) ? (o.globalData.isblack = 1, wx.removeStorageSync("token"), wx.switchTab({ url: "/lionfish_comshop/pages/index/index" })) : (wx.setStorage({ key: "member_id", data: e.data.member_id }), console.log("needPosition", r), r && getCommunityInfo()), n(e) } }) // 修改 // wx.getUserInfo({ // success: function (e) { // var t = e.userInfo; // wx.setStorage({ // key: "userInfo", // data: t // }), console.log(e.userInfo), o.util.request({ // url: "entry/wxapp/user", // data: { // controller: "user.applogin_do", // token: s, // share_id: i, // nickName: e.userInfo.nickName, // avatarUrl: e.userInfo.avatarUrl, // encrypteddata: e.encryptedData, // iv: e.iv, // community_id: a // }, // method: "post", // dataType: "json", // success: function (e) { // console.error('我进入的是第二个呢'); // 1 == (e.data.isblack || 0) ? (o.globalData.isblack = 1, wx.removeStorageSync("token"), wx.switchTab({ // url: "/lionfish_comshop/pages/index/index" // })) : (wx.setStorage({ // key: "member_id", // data: e.data.member_id // }), console.log("needPosition", r), r && getCommunityInfo()), n(e) // } // }) // }, // fail: function (e) { // t(e) // } // }) }) } function stringToJson(e) { return JSON.parse(e) } function jsonToString(e) { return JSON.stringify(e) } function imageUtil(e) { var o = {}, i = e.detail.width, a = e.detail.height, r = a / i; return wx.getSystemInfo({ success: function (e) { var t = e.windowWidth, n = e.windowHeight; r < n / t ? (o.imageWidth = t, o.imageHeight = t * a / i) : (o.imageHeight = n, o.imageWidth = n * i / a) } }), o } var formatTime = function (e) { var t = e.getFullYear(), n = e.getMonth() + 1, o = e.getDate(), i = e.getHours(), a = e.getMinutes(), r = e.getSeconds(); return [t, n, o].map(formatNumber).join("/") + " " + [i, a, r].map(formatNumber).join(":") }, formatNumber = function (e) { return (e = e.toString())[1] ? e : "0" + e }, getCommunityInfo = function () { var o = 0 < arguments.length && void 0 !== arguments[0] ? arguments[0] : {}, i = getApp(), t = wx.getStorageSync("token"); return new Promise(function (n, e) { i.util.request({ url: "entry/wxapp/index", data: { controller: "index.load_history_community", token: t }, dataType: "json", success: function (e) { if (0 == e.data.code) { var t = e.data.list; 0 < Object.keys(t).length || 0 != t.communityId ? (wx.setStorageSync("community", t), i.globalData.community = t, n(t)) : n("") } else 1 == e.data.code ? (console.log(o), check_login() && void 0 === o.communityId ? (wx.redirectTo({ url: "/lionfish_comshop/pages/position/community" }), n("")) : n(o)) : n("") } }) }) }, getCommunityById = function (n) { return new Promise(function (t, e) { getApp().util.request({ url: "entry/wxapp/index", data: { controller: "index.get_community_info", community_id: n }, dataType: "json", success: function (e) { 0 == e.data.code && t(e.data) } }) }) }, addhistory = function (e) { var t = 1 < arguments.length && void 0 !== arguments[1] && arguments[1], n = e.communityId; console.log("addhistory"); var o = wx.getStorageSync("token"); getApp().util.request({ url: "entry/wxapp/index", data: { controller: "index.addhistory_community", community_id: n, token: o }, dataType: "json", success: function (e) { t && (console.log("新人 社区"), app.util.request({ url: "entry/wxapp/index", data: { controller: "index.get_community_info", community_id: n }, dataType: "json", success: function (e) { if (0 == e.data.code) { var t = e.data.data; app.globalData.community = t, app.globalData.changedCommunity = !0, wx.setStorage({ key: "community", data: t }) } } })) } }) }, getWxVersion = function () { return wx.getSystemInfoSync().SDKVersion }, wxCompareVersion = function (e, t) { e = e.split("."), t = t.split("."); for (var n = Math.max(e.length, t.length); e.length < n;) e.push("0"); for (; t.length < n;) t.push("0"); for (var o = 0; o < n; o++) { var i = parseInt(e[o]), a = parseInt(t[o]); if (a < i) return 1; if (i < a) return -1 } return 0 }, addCart = function (n) { return new Promise(function (i, t) { var e = wx.getStorageSync("token"); getApp().util.request({ url: "entry/wxapp/user", data: _extends({ controller: "car.add", token: e }, n), dataType: "json", method: "POST", success: function (e) { if (7 == e.data.code) { var t = e.data, n = t.has_image, o = t.pop_vipmember_buyimage; 1 == n && o && (e.showVipModal = 1, e.data.pop_vipmember_buyimage = o), i(e) } else i(e) }, fail: function (e) { t(e) } }) }) }; module.exports = { formatTime: formatTime, login: login, check_login: check_login, api: api, getdomain: getdomain, imageUtil: imageUtil, jsonToString: jsonToString, stringToJson: stringToJson, login_prosime: login_prosime, getCommunityInfo: getCommunityInfo, check_login_new: check_login_new, checkRedirectTo: checkRedirectTo, getCommunityById: getCommunityById, addhistory: addhistory, wxGetUserInfo: wxGetUserInfo, getWxVersion: getWxVersion, wxCompareVersion: wxCompareVersion, addCart: addCart };<file_sep>/lionfish_comshop/distributionCenter/pages/recruit.js var _extends = Object.assign || function(t) { for (var e = 1; e < arguments.length; e++) { var a = arguments[e]; for (var i in a) Object.prototype.hasOwnProperty.call(a, i) && (t[i] = a[i]) } return t }, app = getApp(), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ mixins: [require("../../mixin/commonMixin.js")], data: { comsissStatus: 0, canApply: !0 }, onLoad: function(t) { status.setNavBgColor(), status.setGroupInfo().then(function(t) { var e = t && t.commiss_diy_name || "分销"; wx.setNavigationBarTitle({ title: "会员" + e }) }), this.get_instruct() }, onShow: function() { var e = this; util.check_login_new().then(function(t) { t ? (e.setData({ needAuth: !1 }), e.getData()) : e.setData({ needAuth: !0 }) }) }, get_instruct: function() { var a = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "distribution.get_instruct" }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data.content || ""; a.setData({ article: e.replace('< img ', '< img style="max-width:100%;height:auto;display:block;margin:10px 0;"') }) } } }) }, getData: function() { var t = wx.getStorageSync("token"), h = this; app.util.request({ url: "entry/wxapp/user", data: { controller: "user.get_user_info", token: t }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = t.data.data, a = e.comsiss_flag, i = e.comsiss_state, s = t.data, n = s.commiss_level, o = s.commiss_sharemember_need, r = (s.commiss_biaodan_need, s.commiss_share_member_update), u = s.share_member_count, c = (s.commiss_become_condition, t.data.commiss_diy_name || "分销"); wx.setNavigationBarTitle({ title: "会员" + c }); var d = {}, m = 0; if (0 < n) { var l = 0, p = !1; 1 == a && 1 == i ? l = 1 : 1 == o ? (l = 2, (m = 1 * r - 1 * u) <= 0 && (l = 3, p = !0)) : p = !0, d = { formStatus: 0, need_num_update: m, comsissStatus: l, canApply: p } } h.setData(_extends({}, d, { commiss_diy_name: t.data.commiss_diy_name || "分销" })) } else h.setData({ needAuth: !0 }), wx.setStorage({ key: "member_id", data: null }) } }) }, authSuccess: function() { var t = this; this.setData({ needAuth: !1 }, function() { t.get_instruct(), t.getData() }) }, subCommis: function() { if (this.authModal()) { wx.showLoading(); var t = wx.getStorageSync("token"), e = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "distribution.sub_commission_info", token: t }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) "申请成功,平台将尽快审核" == t.data.msg ? wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/apply" }) : wx.redirectTo({ url: "/lionfish_comshop/distributionCenter/pages/me" }); else { if ("请先登录" == t.data.msg) return void e.setData({ needAuth: !0 }); if ("您未填写表单!" == t.data.msg) return void wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/apply" }); wx.showToast({ title: t.data.msg ? t.data.msg : "申请失败,请重试!", icon: "none" }) } } }) } }, goNext: function(t) { if (this.authModal()) { var e = 0, a = this.data.member_info || {}, i = a.comsiss_flag || 0, s = a.comsiss_state || 0; 1 == i && (e = 0 == s ? 1 : 2); var n = t.currentTarget.dataset.type; "share" == n ? wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/share" }) : "commiss" == n ? 2 == e ? wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/me" }) : wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/recruit" }) : "form" == n && (2 == e ? wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/me" }) : wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/apply" })) } } });<file_sep>/lionfish_comshop/moduleA/solitaire/details.js var _extends = Object.assign || function(t) { for (var e = 1; e < arguments.length; e++) { var o = arguments[e]; for (var a in o) Object.prototype.hasOwnProperty.call(o, a) && (t[a] = o[a]) } return t }, app = getApp(), WxParse = require("../../wxParse/wxParse.js"), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ mixins: [require("../../mixin/compoentCartMixin.js")], data: { showGoodsModal: !1, showCommentModal: !1, showCartModal: !1, pid: 0, hideGoods: !0, buy_type: "soitaire", groupInfo: { group_name: "社区", owner_name: "团长" }, showShareModal: !1, list: [], loadText: "加载中...", noData: 0, loadMore: !0, isIpx: app.globalData.isIpx, orderList: [], noOrderMore: !1, noOrderData: 0, myOrderList: [], noMyOrderMore: !1, noMyOrderData: !1 }, imagePath: "", options: "", page: 1, soli_id: 0, orderPage: 1, isFirst: 1, myOrderPage: 1, canCancel: !0, onLoad: function(t) { var e = this; status.setGroupInfo().then(function(t) { e.setData({ groupInfo: t }) }); var o = decodeURIComponent(t.scene); if ("undefined" !== o) { var a = o.split("_"); t.id = a[0], t.share_id = a[1] } var i = t.id, n = t.share_id; this.options = t, "undefined" != n && 0 < n && wx.setStorageSync("share_id", n), i || app.util.message("参数错误", "redirect:/lionfish_comshop/moduleA/solitaire/index", "error"), this.soli_id = i }, initFn: function() { var t = this, e = this.options && this.options.id || 0; this.page = 1, this.setData({ list: [], loadText: "加载中...", noData: 0, loadMore: !0 }, function() { e && t.getData(e), t.getCommentList() }) }, onShow: function() { var e = this, t = this.options && this.options.id || 0; t && this.getData(t), this.getCommentList(), this.getOrderList(), this.getMyOrderList(), util.check_login_new().then(function(t) { t ? e.showCartGoods(). catch (function() { console.log("购物车为空") }) : e.setData({ needAuth: !0 }) }) }, onHide: function() { this.setData({ clearTime: !0 }) }, authSuccess: function() { this.setData({ needAuth: !1 }); var t = this.data.community; console.log("authSuccess"), this.compareCommunity(t), this.visiteRecord() }, getData: function(t) { var h = wx.getStorageSync("token"), u = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_solitaire_detail", id: t, token: h }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data, o = e.head_data, a = e.soli_info, i = e.solitaire_target, n = e.solitaire_target_takemember, r = e.solitaire_target_takemoney, s = e.solitaire_target_type, d = a.content; WxParse.wxParse("article", "html", d, u, 0, app.globalData.systemInfo); var l = 1 * r - 1 * a.soli_total_money, c = 1 * n - 1 * a.order_count; 1 == u.isFirst && (u.compareCommunity(o), u.drawImg(o, a), h && u.visiteRecord()), u.setData({ community: o || "", soli_info: a, solitaire_target: i, solitaire_target_takemember: n, solitaire_target_takemoney: r, solitaire_target_type: s, diffMoney: l, diffMember: c, clearTime: !1 }, function() { u.isFirst++ }) } else app.util.message(t.data.msg, "redirect:/lionfish_comshop/moduleA/solitaire/index", "error") } }) }, showImgPrev: function(t) { var e = t ? t.currentTarget.dataset.idx : "", o = this.data.soli_info.images_list || ""; wx.previewImage({ current: o[e], urls: o }) }, compareCommunity: function(t) { var n = this, r = wx.getStorageSync("community"), s = r.communityId || "", d = wx.getStorageSync("token"), l = t.head_id || ""; l && util.getCommunityById(l).then(function(t) { var e = t.hide_community_change_btn, o = t.default_head_info; if (1 == t.open_danhead_model) { if (app.globalData.community = o, app.globalData.changedCommunity = !0, wx.setStorage({ key: "community", data: o }), d && util.addhistory(o), l != o.communityId) { var a = n.data.groupInfo; return void app.util.message("您只能访问自己" + a.group_name, "redirect:/lionfish_comshop/moduleA/solitaire/index", "error", "知道了") } } else if ("" != s && l) { if (console.log("currentCommunityId存在 比较社区"), s != l) { console.log("currentCommunityId存在 社区不同"); var i = n.data.groupInfo; if (1 == e) return console.log("禁止切换"), void app.util.message("您只能访问自己" + i.group_name, "redirect:/lionfish_comshop/moduleA/solitaire/index", "error", "知道了"); n.setData({ hide_community_change_btn: e, showChangeCommunity: !! t.data, changeCommunity: t.data, currentCommunity: r }) } } else d ? util.getCommunityInfo().then(function(t) { console.log("token存在 比较社区"), t.community_id && t.community_id != l && n.setData({ showChangeCommunity: !0, currentCommunity: t }) }). catch (function(t) { console.log("step4 新人"), "" != Object.keys(t) && util.addhistory(t, !0) }) : (console.log("token不存在 存社区"), app.globalData.community = t.data, app.globalData.changedCommunity = !0, wx.setStorage({ key: "community", data: t.data })) }) }, confrimChangeCommunity: function() { var t = this.data.changeCommunity, e = wx.getStorageSync("token"); app.globalData.community = t, app.globalData.changedCommunity = !0, wx.setStorage({ key: "community", data: t }), e && util.addhistory(t), this.setData({ showChangeCommunity: !1 }), console.log("用户点击确定") }, cancelChangeCommunity: function() { var t = this.data.groupInfo; wx.showModal({ title: "提示", content: "此接龙在您所属" + t.group_name + "不可参与", showCancel: !1, confirmColor: "#ff5041", success: function(t) { t.confirm && wx.switchTab({ url: "/lionfish_comshop/pages/index/index" }) } }) }, handleGoodsModal: function() { this.setData({ showGoodsModal: !this.data.showGoodsModal }) }, handleCommentModal: function() { this.setData({ showCommentModal: !this.data.showCommentModal }) }, changeCartNum: function(t) { var e = t.detail, o = e.goods_total_count, a = e.goods_id, i = this.data.soli_info || "", n = i.goods_list || [], r = n.findIndex(function(t) { return t.actId == a }); - 1 !== r && (this.showCartGoods(). catch (function() { console.log("购物车为空") }), n[r].goods_total_count = o || 0, i.goods_list = n, this.setData({ soli_info: i })) }, handleCartModal: function() { console.log("购物车弹窗"); var t = this; this.data.showCartModal ? this.setData({ showCartModal: !1 }) : this.showCartGoods().then(function() { t.setData({ showCartModal: !0 }) }). catch (function() { console.log("购物车为空") }) }, showCartGoods: function() { var s = !(0 < arguments.length && void 0 !== arguments[0]) || arguments[0], d = this; return new Promise(function(n, r) { var t = wx.getStorageSync("token"), e = d.soli_id || "", o = wx.getStorageSync("community").communityId || ""; e && wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "car.show_cart_goods", token: t, soli_id: e, community_id: o, buy_type: "soitaire" }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = t.data.carts; if (0 == Object.keys(e).length) d.setData({ cartNum: 0 }), r(t); else { var o = d.countCartNum(e), a = o.cartNum, i = o.totMoney; s && d.setData({ carts: e, cartNum: a, totMoney: i }), n() } } else 5 == t.data.code ? d.setData({ needAuth: !0, showAuthModal: !0 }) : console.log(t) } }) }) }, countCartNum: function(a) { var i = 0, n = 0; return Object.keys(a).forEach(function(o) { Object.keys(a[o].shopcarts).forEach(function(t) { var e = 1 * a[o].shopcarts[t].goodsnum; i += e, n += a[o].shopcarts[t].currntprice * e }) }), n = n.toFixed(2), { cartNum: i, totMoney: n } }, changeCart: function(t) { var e = this.options && this.options.id || 0, o = t.detail, a = this.countCartNum(o), i = a.cartNum, n = a.totMoney; e && this.setData({ clearTime: !0, carts: o, cartNum: i, totMoney: n }), this.getData(e) }, subComment: function(t) { var e = this.data, s = e.soli_info, d = e.pid, l = s.id || "", c = t.detail.value.content || ""; if ("" != c) { var h = this, o = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.sub_solipost", soli_id: l, content: c, pid: d, token: o }, dataType: "json", success: function(t) { if (0 == t.data.code) { var e = t.data, o = e.post_id, a = e.cur_time, i = wx.getStorageSync("userInfo"), n = { id: o, soli_id: l, pid: d, username: i.nickName, avatar: i.avatarUrl, content: c, fav_count: 0, addtime: a, reply: [], is_agree: !1 }, r = h.data.list; r.unshift(n), s.comment_total = 1 * s.comment_total + 1, h.setData({ soli_info: s, list: r, content: "", showCommentModal: !1, noData: 0 }), app.util.message(t.data.msg || "留言成功", "", "success") } else app.util.message(t.data.msg || "留言失败", "", "error") } }) } else wx.showToast({ title: "请输入内容", icon: "none" }) }, visiteRecord: function() { var t = this.soli_id || "", e = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.send_visite_record", soli_id: t, token: e }, dataType: "json", success: function(t) {} }) }, favComment: function(t) { var a = this, e = this.data.soli_info.id || "", o = t ? t.currentTarget.dataset.post_id : "", i = t ? t.currentTarget.dataset.idx : 0, n = wx.getStorageSync("token"); o && app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.fav_soli_post", soli_id: e, post_id: o, token: n }, dataType: "json", success: function(t) { if (0 == t.data.code) if (1 == t.data.do) { var e = a.data.list; e[i].is_agree = !0, e[i].fav_count = 1 * e[i].fav_count + 1, a.setData({ list: e }) } else { var o = a.data.list; o[i].is_agree = !1, o[i].fav_count = 1 * o[i].fav_count - 1, a.setData({ list: o }) } else 1 == t.data.code ? a.setData({ needAuth: !0, showAuthModal: !0 }) : wx.showToast({ title: t.data.msg || "点赞失败", icon: "none" }) } }) }, handleMoreGoods: function() { this.setData({ hideGoods: !this.data.hideGoods }) }, goPlaceOrder: function() { var e = this.data.soli_info; this.showCartGoods(!1).then(function() { var t = "/lionfish_comshop/pages/order/placeOrder?type=soitaire&soli_id=" + (e.id || ""); wx.navigateTo({ url: t }) }). catch (function() { wx.showToast({ title: "请先选择商品!", icon: "none" }) }) }, getCommentList: function() { var a = this, t = this.options && this.options.id || 0, e = wx.getStorageSync("token"); wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_comment_list", page: this.page, token: e, id: t }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = {}, o = t.data.data; o.length < 20 && (e.noMore = !0), o = a.data.list.concat(o), a.page++, a.setData(_extends({ list: o }, e)) } else 1 == t.data.code && (1 == a.page && a.setData({ noData: 1 }), a.setData({ loadMore: !1, noMore: !1, loadText: "没有更多记录了~" })) } }) }, getMyOrderList: function() { console.log("getMyOrderList"); var i = this, t = this.options && this.options.id || 0, e = wx.getStorageSync("token"); e && wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "order.orderlist", page: this.myOrderPage, token: e, soli_id: t }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = {}, o = t.data.data; o.length < 6 && (e.noMyOrderMore = !0), o = i.data.myOrderList.concat(o), i.myOrderPage++, i.setData(_extends({ myOrderList: o }, e)) } else if (1 == t.data.code) { var a = { noMyOrderMore: !0 }; 1 == i.myOrderPage && (a.noMyOrderData = 1), i.setData(a) } } }) }, getMoreMyOrder: function() { this.data.noMyOrderMore || this.getMyOrderList() }, cancelOrder: function(i) { var n = this; this.canCancel && wx.showModal({ title: "取消订单并退款", content: "取消订单后,款项将原路退回到您的支付账户;详情请查看退款进度。", confirmText: "取消订单", confirmColor: "#ff5344", cancelText: "再等等", cancelColor: "#666666", success: function(t) { if (t.confirm) { n.canCancel = !1; var e = i.currentTarget.dataset.type, o = i.currentTarget.dataset.index, a = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "order.del_cancle_order", token: a, order_id: e }, dataType: "json", method: "POST", success: function(t) { 0 == t.data.code ? wx.showModal({ title: "提示", content: "取消订单成功", showCancel: !1, confirmColor: "#ff5344", success: function(t) { if (t.confirm) { var e = n.data.myOrderList; e[o].order_status_id = 5, n.setData({ myOrderList: e }) } } }) : (n.canCancel = !0, wx.showToast({ title: t.data.msg || "取消订单失败", icon: "none" })) } }), console.log("用户点击确定") } else t.cancel && (n.canCancel = !0, console.log("用户点击取消")) } }) }, callTelphone: function(t) { var e = t.currentTarget.dataset.phone; wx.makePhoneCall({ phoneNumber: e }) }, getOrderList: function() { var n = this, t = this.options && this.options.id || 0; wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_soli_order_list", page: this.orderPage, id: t, size: 6 }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var e = {}, o = t.data.data; o.length < 6 && (e.noOrderMore = !0); var a = n.data.orderList.concat(o); n.orderPage++, n.setData(_extends({ orderList: a }, e)) } else if (1 == t.data.code) { var i = {}; 1 == n.orderPage && (i.noOrderData = 1), n.setData(_extends({ noOrderMore: !0 }, i)) } } }) }, getMoreOrder: function() { this.data.noOrderMore || this.getOrderList() }, onReachBottom: function() { if (!this.data.loadMore) return !1; this.getCommentList() }, drawImg: function(t, e) { var o = e.images_list, a = e.qrcode_image, i = e.content.replace(/&lt;\/?.+?&gt;/g, ""), n = [], r = 300; o.length && (n.push({ type: "image", url: o[0], css: { width: "442px", height: "300px", top: "230px", left: "36px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "", shadow: "", mode: "scaleToFill" } }), r = 0), this.setData({ template: { width: "514px", height: 710 - r + "px", background: "#fff", views: [{ type: "image", url: t.avatar, css: { width: "46px", height: "46px", top: "25px", left: "36px", rotate: "0", borderRadius: "3px", borderWidth: "", borderColor: "#000000", shadow: "", mode: "scaleToFill" } }, { type: "text", text: t.head_name, css: { color: "#000000", background: "", width: "385px", height: "20.02px", top: "30px", left: "96px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "14px", fontWeight: "bold", maxLines: "1", lineHeight: "20.202000000000005px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: t.community_name, css: { color: "#999999", background: "", width: "385px", height: "17.16px", top: "52px", left: "96px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "12px", fontWeight: "normal", maxLines: "1", lineHeight: "17.316000000000003px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: i, css: { color: "#666666", background: "", width: "442px", height: "52.181999999999995px", top: "158px", left: "36px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "18px", fontWeight: "normal", maxLines: "2", lineHeight: "25.974000000000004px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: e.solitaire_name, css: { color: "#000000", background: "", width: "442px", height: "42.89999999999999px", top: "95px", left: "36px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "30px", fontWeight: "normal", maxLines: "1", lineHeight: "43.290000000000006px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: "一群人正在赶来接龙", css: { color: "#999999", background: "", width: "442px", height: "22.88px", top: 595 - r + "px", left: "204px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "16px", fontWeight: "normal", maxLines: "2", lineHeight: "23.088000000000005px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "text", text: "长按识别或扫码参与", css: { color: "#999999", background: "", width: "442px", height: "22.88px", top: 630 - r + "px", left: "204px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", padding: "0px", fontSize: "16px", fontWeight: "normal", maxLines: "2", lineHeight: "23.088000000000005px", textStyle: "fill", textDecoration: "none", fontFamily: "", textAlign: "left" } }, { type: "image", url: a, css: { width: "120px", height: "120px", top: 560 - r + "px", left: "356px", rotate: "0", borderRadius: "", borderWidth: "", borderColor: "#000000", shadow: "", mode: "scaleToFill" } }].concat(n) } }) }, onImgOK: function(t) { this.imagePath = t.detail.path, this.setData({ image: this.imagePath }) }, saveImage: function() { var e = this; wx.saveImageToPhotosAlbum({ filePath: this.imagePath, success: function(t) { e.setData({ showShareModal: !1 }), wx.showToast({ title: "保存成功!" }) }, fail: function(t) { wx.showToast({ title: "保存失败,请重试!", icon: "none" }) } }) }, handleShareModal: function(t) { var e = {}; "order" == (t ? t.currentTarget.dataset.type : "") ? e.showOrderModal = !this.data.showOrderModal : e.showShareModal = !this.data.showShareModal, this.setData(e) }, onShareAppMessage: function() { var t = wx.getStorageSync("member_id") || "", e = this.data.soli_info || ""; return { title: e.solitaire_name || "", path: "lionfish_comshop/moduleA/solitaire/details?id=" + e.id + "&share_id=" + t, success: function(t) {}, fail: function(t) {} } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/checkbox/checkbox.js "use strict"; var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) { return typeof t } : function(t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }; module.exports = function(e) { function n(t) { if (o[t]) return o[t].exports; var r = o[t] = { i: t, l: !1, exports: {} }; return e[t].call(r.exports, r, r.exports, n), r.l = !0, r.exports } var o = {}; return n.m = e, n.c = o, n.d = function(t, e, o) { n.o(t, e) || Object.defineProperty(t, e, { enumerable: !0, get: o }) }, n.r = function(t) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: !0 }) }, n.t = function(e, o) { if (1 & o && (e = n(e)), 8 & o) return e; if (4 & o && "object" === (void 0 === e ? "undefined" : t(e)) && e && e.__esModule) return e; var r = Object.create(null); if (n.r(r), Object.defineProperty(r, "default", { enumerable: !0, value: e }), 2 & o && "string" != typeof e) for (var a in e) n.d(r, a, function(t) { return e[t] }.bind(null, a)); return r }, n.n = function(t) { var e = t && t.__esModule ? function() { return t. default } : function() { return t }; return n.d(e, "a", e), e }, n.o = function(t, e) { return Object.prototype.hasOwnProperty.call(t, e) }, n.p = "", n(n.s = 18) }({ 18: function(t, e, n) { Component({ options: { addGlobalClass: !0, multipleSlots: !0 }, properties: { multi: { type: Boolean, value: !0 }, checked: { type: Boolean, value: !1 }, value: { type: String, value: "" }, label: { type: String, value: "label" }, extClass: { type: String, value: "" } }, data: {}, relations: { "../checkbox-group/checkbox-group": { type: "ancestor", linked: function(t) { this.data.group = t }, unlinked: function() { this.data.group = null } } }, methods: { setMulti: function(t) { this.setData({ multi: t }) }, setOuterClass: function(t) { this.setData({ outerClass: t }) }, checkedChange: function(t) { if (this.data.multi) { var e = !this.data.checked; this.setData({ checked: e }), this.data.group && this.data.group.checkedChange(e, this) } else { var n = this.data.checked; if (n) return; this.setData({ checked: !0 }), this.data.group && this.data.group.checkedChange(n, this) } this.triggerEvent("change", { value: this.data.value, checked: this.data.checked }) } } }) } });<file_sep>/lionfish_comshop/moduleB/live/index.js var app = getApp(), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ data: { roomInfo: [], loadText: "加载中...", noData: !1, loadMore: !0, live_status_tip: { 101: "直播中", 102: "未开始", 103: "已结束", 104: "禁播", 105: "暂停中", 106: "异常", 107: "已过期" } }, page: 1, onLoad: function(a) { this.getData() }, onShow: function() { var t = this; util.check_login_new().then(function(a) { a ? (0, status.cartNum)("", !0).then(function(a) { t.setData({ cartNum: a.data }) }) : t.setData({ needAuth: !0 }) }) }, getData: function() { var i = this; wx.showLoading(), app.util.request({ url: "entry/wxapp/user", data: { controller: "livevideo.get_roominfo", page: this.page }, dataType: "json", success: function(a) { console.log(a); if (wx.hideLoading(), 0 == a.data.code) { var t = a.data.data || [], o = {}; o.showTabbar = a.data.showTabbar, t.length < 10 && (o.noMore = !0, o.loadMore = !1); var e = i.data.roomInfo; e = e.concat(t), o.roomInfo = e, i.page++, i.setData(o) } else { var n = {}; 1 == i.page && (n.noData = !0), n.showTabbar = a.data.showTabbar, n.loadMore = !1, i.setData(n) } } }) }, goLive: function(a) { var t = a.currentTarget.dataset.roomid; t && wx.navigateTo({ url: "plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=" + t }) }, onPullDownRefresh: function() {}, onReachBottom: function() { this.data.loadMore && this.getData() }, });<file_sep>/siteinfo.js module.exports = { "name": "社区团购", "uniacid": "17", "acid": "17", "multiid": "0", "version": "12.2.0", "siteroot": "https://tongcheng.1banren.com/app/index.php", "design_method": "3" }; //wx4218cbbfdb5e8ac9 126<file_sep>/lionfish_comshop/pages/user/me.js var _extends = Object.assign || function(e) { for (var t = 1; t < arguments.length; t++) { var a = arguments[t]; for (var o in a) Object.prototype.hasOwnProperty.call(a, o) && (e[o] = a[o]) } return e }, util = require("../../utils/util.js"), status = require("../../utils/index.js"), wcache = require("../../utils/wcache.js"), app = getApp(); Page({ data: { tablebar: 4, canIUse: wx.canIUse("button.open-type.getUserInfo"), theme_type: "", add_mo: 0, is_show_on: 0, level_name: "", member_level_is_open: 0, is_yue_open: 0, needAuth: !1, opencommiss: 0, inputValue: 0, getfocus: !1, showguess: !0, items: [], auditStatus: 5, isShowCoder: !1, myCoderList: [], qrcodebase64: "", setInter: null, copyright: "", common_header_backgroundimage: "", enabled_front_supply: 0, cartNum: 0, is_show_about_us: 0, groupInfo: { group_name: "社区", owner_name: "团长" }, is_show_score: 0, showGetPhone: !1, user_tool_icons: {}, community: "" }, isCalling: !1, onLoad: function(e) { wx.hideTabBar(); var t = this; status.setNavBgColor(), status.setGroupInfo().then(function(e) { t.setData({ groupInfo: e }) }), wx.showLoading() }, getMemberInfo: function() { var e = wx.getStorageSync("token"); this.getCommunityInfo(); var g = this; app.util.request({ url: "entry/wxapp/user", data: { controller: "user.get_user_info", token: e }, dataType: "json", success: function(e) { if (setTimeout(function() { wx.hideLoading() }, 1e3), 0 == e.data.code) { var t = !1; 1 != e.data.is_show_auth_mobile || e.data.data.telephone || (t = !0); var a = e.data.data || "", o = {}; if (a) { if (a.member_level_info && (a.member_level_info.discount = (a.member_level_info.discount / 10).toFixed(1)), 0 < e.data.commiss_level) { var s = 1 * e.data.commiss_share_member_update, i = 1 * e.data.share_member_count, n = 1 * e.data.commiss_share_member_update - 1 * e.data.share_member_count, r = 0; 1 == a.is_writecommiss_form && (r = 1) == a.comsiss_flag && (r = 0 == a.comsiss_state ? 1 : 2), o = { formStatus: r, commiss_level: e.data.commiss_level, commiss_sharemember_need: e.data.commiss_sharemember_need, commiss_share_member_update: s, commiss_biaodan_need: e.data.commiss_biaodan_need, share_member_count: i, today_share_member_count: e.data.today_share_member_count, yestoday_share_member_count: e.data.yestoday_share_member_count, need_num_update: n } } } else o.needAuth = !0; var u = e.data, _ = u.is_supply, c = u.is_open_vipcard_buy, m = u.modify_vipcard_name, d = u.is_vip_card_member, h = u.modify_vipcard_logo, l = u.isopen_signinreward, p = u.show_signinreward_icon; g.setData(_extends({}, o, { member_info: a, is_supply: _ || 0, showGetPhone: t, is_open_vipcard_buy: c || 0, modify_vipcard_name: m || "会员", is_vip_card_member: d || 0, modify_vipcard_logo: h, show_signinreward_icon: p, isopen_signinreward: l })) } else g.setData({ needAuth: !0 }), wx.hideTabBar(), wx.setStorage({ key: "member_id", data: null }) } }) }, getCommunityInfo: function() { var t = this, e = wx.getStorageSync("community"); e ? e.head_mobile ? t.setData({ community: e }) : util.getCommunityById(e.communityId).then(function(e) { t.setData({ community: e.data }) }) : wx.getStorageSync("token") && util.getCommunityInfo().then(function(e) { t.setData({ community: e }) }) }, getCopyright: function() { var v = this; app.util.request({ url: "entry/wxapp/user", data: { controller: "user.get_copyright" }, dataType: "json", success: function(e) { if (0 == e.data.code) { var t = e.data, a = t.enabled_front_supply, o = t.is_open_yue_pay, s = t.is_show_score, i = t.user_order_menu_icons, n = t.close_community_apply_enter, r = t.user_tool_icons, u = t.ishow_user_loginout_btn, _ = t.commiss_diy_name, c = t.supply_diy_name, m = t.user_service_switch, d = t.fetch_coder_type, h = t.show_user_pin, l = t.common_header_backgroundimage, p = t.is_show_about_us, g = t.show_user_change_comunity, f = t.open_danhead_model, w = t.default_head_info, b = t.is_open_solitaire, y = {}; 1 == f && (y.community = w), _ = _ || "分销", c = c || "供应商", wcache.put("commiss_diy_name", _), wcache.put("supply_diy_name", c), v.setData(_extends({ copyright: t.data || "", common_header_backgroundimage: l || "", is_show_about_us: p || 0, enabled_front_supply: a, is_open_yue_pay: o, is_show_score: s, user_order_menu_icons: i || {}, commiss_diy_name: _, close_community_apply_enter: n || 0, user_tool_icons: r || {}, ishow_user_loginout_btn: u || 0, supply_diy_name: c, user_service_switch: m, fetch_coder_type: d || 0, show_user_pin: h, show_user_change_comunity: g, open_danhead_model: f, is_open_solitaire: b }, y)) } } }) }, authSuccess: function() { var t = this; wx.showLoading(), t.setData({ needAuth: !1, showAuthModal: !1, tabbarRefresh: !0 }), (0, status.cartNum)("", !0).then(function(e) { 0 == e.code && t.setData({ cartNum: e.data }) }), t.getMemberInfo() }, authModal: function() { return !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, goToGroup: function() { 5 === this.data.auditStatus ? wx.navigateTo({ url: "/lionfish_comshop/pages/groupCenter/index" }) : wx.navigateTo({ url: "/lionfish_comshop/pages/groupCenter/apply" }) }, bindGetUserInfo: function(o) { var s = this; if ("getUserInfo:ok" === o.detail.errMsg) { var e = Object.assign({}, wx.getStorageSync("userInfo"), { avatarUrl: o.detail.userInfo.avatarUrl, nickName: o.detail.userInfo.nickName }), t = o.detail.userInfo, a = t.nickName, i = t.avatarUrl; app.globalData.userInfo = e, wx.setStorage({ key: "userInfo", data: e }), this.setData({ userInfo: e }), wx.showToast({ title: "资料已更新", icon: "none", duration: 2e3 }), a && app.util.request({ url: "entry/wxapp/user", data: { controller: "user.update_user_info", token: wx.getStorageSync("token"), nickName: a, avatarUrl: i }, dataType: "json", success: function(e) { if (0 == e.data.code) { var t = s.data.member_info, a = Object.assign({}, t, { avatar: o.detail.userInfo.avatarUrl, username: o.detail.userInfo.nickName }); s.setData({ member_info: a }) } } }) } else wx.showToast({ title: "资料更新失败。", icon: "none" }) }, previewImage: function(e) { var t = e.target.dataset.src; t && wx.previewImage({ current: t, urls: [t] }) }, goLink2: function(e) { if (this.authModal()) { var t = e.currentTarget.dataset.link; 3 < getCurrentPages().length ? wx.redirectTo({ url: t }) : wx.navigateTo({ url: t }) } }, onShow: function() { var t = this; util.check_login_new().then(function(e) { e ? (t.setData({ needAuth: !1, tabbarRefresh: !0 }), (0, status.cartNum)("", !0).then(function(e) { 0 == e.code && t.setData({ cartNum: e.data }) })) : (t.setData({ needAuth: !0 }), wx.hideLoading()) }), t.getCopyright(), t.getMemberInfo() }, onHide: function() { this.setData({ tabbarRefresh: !1 }) }, getReceiveMobile: function(e) { wx.showToast({ icon: "none", title: "授权成功" }), this.setData({ showGetPhone: !1 }) }, close: function() { this.setData({ showGetPhone: !1 }) }, closeDistribution: function() { this.setData({ showDistribution: !1 }) }, goDistribution: function() { var e = this.data.member_info; 0 == e.comsiss_flag ? this.distributionNext() : 0 == e.comsiss_state ? this.distributionNext() : wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/me" }) }, distributionNext: function() { if (1 == this.data.commiss_sharemember_need) { console.log("需要分享"); wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/recruit" }) } else if (1 == this.data.commiss_biaodan_need) console.log("需要表单"), wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/recruit" }); else { var e = 0, t = this.data.member_info; 1 == t.comsiss_flag && (e = 0 == t.comsiss_state ? 1 : 2); var a = "/lionfish_comshop/distributionCenter/pages/recruit"; 2 == e && (a = "/lionfish_comshop/distributionCenter/pages/me"), wx.navigateTo({ url: a }) } }, goNext: function(e) { console.log(e); var t = 0, a = this.data.member_info; 1 == a.comsiss_flag && (t = 0 == a.comsiss_state ? 1 : 2); var o = e.currentTarget.dataset.type; "share" == o ? wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/share" }) : "commiss" == o ? 2 == t ? wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/me" }) : wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/recruit" }) : "form" == o && (2 == t ? wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/me" }) : wx.navigateTo({ url: "/lionfish_comshop/distributionCenter/pages/recruit" })) }, loginOut: function() { wx.removeStorageSync("community"), wx.removeStorage({ key: "token", success: function(e) { wx.reLaunch({ url: "/lionfish_comshop/pages/user/me" }) } }) }, toggleFetchCoder: function() { this.authModal() && this.setData({ isShowCoder: !this.data.isShowCoder }) }, callTelphone: function(e) { var t = this, a = e.currentTarget.dataset.phone; a && (this.isCalling || (this.isCalling = !0, wx.makePhoneCall({ phoneNumber: a, complete: function() { t.isCalling = !1 } }))) } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/lottery-oper/lottery-oper.js "use strict"; Component({ properties: { from: { type: String, value: "pusher" }, type: { type: String, value: "unstart" }, participateType: { type: Number, value: 0 }, isParticipate: { type: Boolean, value: !1 }, participateNum: { type: Number, value: 0 }, luckName: { type: String, value: "" }, luckNum: { type: Number, value: 0 }, mySelfOpenid: { type: String }, mySelfLuckMen: { type: Object, value: {} }, curLuckMen: { type: Array, value: [] }, historyLuckMen: { type: Array, value: [] }, obtainType: { type: Number, value: 0 }, remark: { type: String, value: "" }, countTime: { type: String, value: "" }, showCountTime: { type: Boolean, value: !1 }, endLotteryAnimation: { type: Boolean, value: !1 }, isFillAddress: { type: Boolean, value: !1 }, isHistoryFillAddress: { type: Array, value: [] }, isCancelLottery: { type: Boolean, value: !1 } }, methods: { startLottery: function() { this.triggerEvent("customevent", { showLotteryOper: !0, confirmStartLottery: !0 }) }, cancelLottery: function() { this.triggerEvent("customevent", { showLotteryOper: !0, confirmCancelLottery: !0 }) }, closeLotteryOper: function() { this.triggerEvent("customevent", { confirmCloseLotteryOper: !0, showLotteryOper: !1 }) }, clickComment: function() { this.triggerEvent("customevent", { confirmClickCommentWithLottery: !0, showLotteryOper: !1, operatePushComment: !0, showPushComment: !0 }) }, clickLike: function() { this.triggerEvent("customevent", { confirmClickLikeWithLottery: !0, showLotteryOper: !1 }) }, clickResultList: function() { this.setData({ type: "result-list" }), this.triggerEvent("customevent", { confirmClickLotteryList: !0, showLotteryOper: !0 }) }, clipboardLotteryToken: function(t) { wx.setClipboardData({ data: t.currentTarget.dataset.token, success: function() { console.log("clipboard token", t.currentTarget.dataset.token) }, fail: function() { wx.showToast({ title: "复制失败", icon: "none", duration: 1500, mask: !1 }) } }), this.triggerEvent("customevent", { confirmClipboardLotteryToken: !0, showLotteryOper: !0 }) }, fillLotteryAddress: function() { this.triggerEvent("customevent", { confirmFillLotteryAddress: !0 }) }, fillHistoryLotteryAddress: function(t) { this.setData({ type: "result-list" }); var e = t.currentTarget.dataset.id, r = t.currentTarget.dataset.index; this.triggerEvent("customevent", { lotteryId: e, index: r, confirmFillHistoryLotteryAddress: !0 }) }, viewLotteryAddress: function(t) { var e = t.currentTarget.dataset.id; this.triggerEvent("customevent", { lotteryId: e, confirmViewLotteryAddress: !0 }) }, viewHistoryLotteryAddress: function(t) { this.setData({ type: "result-list" }); var e = t.currentTarget.dataset.id, r = t.currentTarget.dataset.index; this.triggerEvent("customevent", { lotteryId: e, index: r, confirmViewHistoryLotteryAddress: !0 }) } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/profile-modal/profile-modal.js "use strict"; Component({ properties: { weappImg: { type: String, value: "" }, weappName: { type: String, value: "" }, isSubscribe: { type: Boolean }, roomTitle: { type: String, value: "" }, anchorName: { type: String, value: "" }, from: { type: String, value: "" } }, methods: { closeProfileModal: function() { this.triggerEvent("customevent", { showProfileModal: !1 }) }, clickSubscribe: function() { this.triggerEvent("customevent", { confirmSubscribe: !0, isSubscribe: this.data.isSubscribe, showProfileModal: !0 }) }, clickReportRoom: function() { this.triggerEvent("customevent", { confirmReportRoom: !0, showProfileModal: !0 }) } } });<file_sep>/lionfish_comshop/pages/type/details.js var app = getApp(), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ mixins: [require("../../mixin/compoentCartMixin.js")], data: { loadMore: !0, loadText: "加载中...", rushList: [], cartNum: 0, showEmpty: !1 }, $data: { id: 0, pageNum: 1 }, onLoad: function(t) { var a = t.id || ""; (this.$data.id = a) ? this.getData() : wx.showToast({ title: "参数错误", icon: "none" }, function() { wx.switchTab({ url: "/lionfish_comshop/pages/index/index" }) }) }, onShow: function() { var e = this; util.check_login_new().then(function(t) { var a = !t; e.setData({ needAuth: a }), t && (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && e.setData({ cartNum: t.data }) }) }) }, authSuccess: function() { var t = this; this.$data.pageNum = 1, this.setData({ loadMore: !0, loadText: "加载中...", rushList: [], showEmpty: !1, needAuth: !1 }, function() { t.getData() }) }, getData: function() { var r = this; return new Promise(function(d, t) { var a = wx.getStorageSync("token"), e = wx.getStorageSync("community"), i = r.$data.id; wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "index.load_cate_goodslist", token: a, head_id: e.communityId, gid: i }, dataType: "json", success: function(t) { if (wx.hideLoading(), 0 == t.data.code) { var a = t.data, e = a.full_money, i = a.full_reducemoney, n = a.is_open_fullreduction, o = a.list, s = a.is_show_cate_tabbar, u = { full_money: e, full_reducemoney: i, is_open_fullreduction: n }, c = { rushList: r.data.rushList.concat(o), pageEmpty: !1, reduction: u, loadOver: !0, is_show_cate_tabbar: s }; 0 == o.length && (c.showEmpty = !0), wx.setNavigationBarTitle({ title: o.length && o[0].cate_info.name || "" }), c.loadText = r.data.loadMore ? "加载中..." : "没有更多商品了~", r.setData(c, function() { r.$data.pageNum += 1 }) } else 1 == t.data.code && wx.showModal({ title: "提示", content: t.data.msg || "无数据", showCancel: !1, success: function() { wx.navigateBack() } }); d(t) } }) }) }, changeCartNum: function(t) { var a = t.detail; (0, status.cartNum)(this.setData({ cartNum: a })) }, onReachBottom: function() { console.log("这是我的底线") }, onShareAppMessage: function(t) { var a = this.data.cate_info.name || "分类列表", e = wx.getStorageSync("member_id"); return { title: a, path: "lionfish_comshop/pages/type/details?id=" + this.$data.id + "&share_id=" + e, success: function(t) {}, fail: function(t) {} } }, onShareTimeline: function (t) { var a = this.data.cate_info.name || "分类列表", e = wx.getStorageSync("member_id"); return { title: a, query: "id=" + this.$data.id + "&share_id=" + e, success: function (t) { }, fail: function (t) { } } } });<file_sep>/lionfish_comshop/pages/groupCenter/groupList.js var _extends = Object.assign || function(e) { for (var t = 1; t < arguments.length; t++) { var a = arguments[t]; for (var r in a) Object.prototype.hasOwnProperty.call(a, r) && (e[r] = a[r]) } return e }, page = 1, app = getApp(), status = require("../../utils/index.js"); Page({ data: { currentTab: 0, pageSize: 10, navList: [{ name: "全部", id: "0" }, { name: "待配送", id: "1" }, { name: "待签收", id: "2" }, { name: "待提货", id: "3" }, { name: "已完成", id: "4" }], loadText: "", disUserId: "", no_order: 0, page: 1, hide_tip: !0, order: [], tip: "正在加载", searchfield: [{ field: "ordersn", name: "订单号" }, { field: "member", name: "会员昵称" }, { field: "address", name: "配送联系人" }, { field: "mobile", name: "下单手机号" }, { field: "location", name: "配送地址" }, { field: "goodstitle", name: "商品标题" }], fieldIdx: 0, groupInfo: { group_name: "社区", owner_name: "团长" } }, searchOBj: {}, onLoad: function(e) { var t = this; status.setGroupInfo().then(function(e) { t.setData({ groupInfo: e }) }), page = 1; var a = 0; null != e && (a = e.tab), this.setData({ currentTab: a }), this.getData(a) }, onShow: function() {}, bindFiledChange: function(e) { this.setData({ fieldIdx: e.detail.value }) }, searchByKey: function(e) { var t = this, a = this.data, r = a.searchfield[a.fieldIdx].field, n = e.detail.value || ""; this.searchOBj = { keyword: n, searchfield: r }, this.setData({ page: 1, order: [] }, function() { t.getData() }) }, callPhone: function(e) { var t = e.currentTarget.dataset.phone; t && wx.makePhoneCall({ phoneNumber: t }) }, switchNav: function(e) { if (this.data.currentTab === 1 * e.currentTarget.dataset.id) return !1; this.setData({ currentTab: 1 * e.currentTarget.dataset.id, page: 1, order: [] }), this.getData() }, getData: function() { wx.showLoading({ title: "加载中...", mask: !0 }), this.setData({ isHideLoadMore: !0 }), this.data.no_order = 1; var o = this, e = wx.getStorageSync("token"), t = this.data.currentTab, a = -1; 1 == t ? a = 1 : 2 == t ? a = 14 : 3 == t ? a = 4 : 4 == t && (a = 6), app.util.request({ url: "entry/wxapp/index", data: _extends({ controller: "order.orderlist", is_tuanz: 1, token: e, page: o.data.page, order_status: a }, this.searchOBj), dataType: "json", success: function(e) { var t = e.data, a = { open_aftersale: t.open_aftersale, open_aftersale_time: t.open_aftersale_time }; if (0 != e.data.code) return o.setData(_extends({ isHideLoadMore: !0 }, a)), wx.hideLoading(), !1; console.log(o.data.page); var r = e.data.data, n = o.data.order.concat(r); o.setData(_extends({ order: n, hide_tip: !0, no_order: 0 }, a)), wx.hideLoading() } }) }, sign_one: function(e) { var n = this, o = e.currentTarget.dataset.order_id, t = wx.getStorageSync("token"); wx.showModal({ title: "提示", content: "确认提货", confirmColor: "#F75451", success: function(e) { e.confirm && app.util.request({ url: "entry/wxapp/index", data: { controller: "order.sign_dan_order", token: t, order_id: o }, dataType: "json", success: function(e) { wx.showToast({ title: "签收成功", duration: 1e3 }); var t = n.data.order, a = []; for (var r in t) t[r].order_id != o && a.push(t[r]); n.setData({ order: a }) } }) } }) }, goOrderDetail: function(e) { var t = e.currentTarget.dataset.order_id; wx.navigateTo({ url: "/lionfish_comshop/pages/groupCenter/groupDetail?groupOrderId=" + t }) }, onReachBottom: function() { if (1 == this.data.no_order) return !1; this.data.page += 1, this.getData(), this.setData({ isHideLoadMore: !1 }) }, handleTipDialog: function(e) { var t = e.currentTarget.dataset.type || 0; this.setData({ showTipDialog: !this.data.showTipDialog, fen_type: t }) } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/pages/report-status/report-status.js "use strict"; var t = require("../../wxlive-components/logic/ui.js"); Component({ options: { styleIsolation: "page-apply-shared" }, properties: { path: String }, data: { uiPagePaddingTop: 0 }, methods: { onLoad: function() { (0, t.setNavFontColor)("#FFFFFF") }, onShow: function() { this.uiGetPagePaddingTop() }, uiGetPagePaddingTop: function() { this.setData({ uiPagePaddingTop: (0, t.getPaddingTop)() }) }, completeReport: function() { "reportCommentsPage" === this.data.path ? wx.navigateBack({ delta: 2 }) : "reportRoomPage" === this.data.path && wx.navigateBack({ delta: 3 }) } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/miniprogram_dist/loading/loading.js "use strict"; var t = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(t) { return typeof t } : function(t) { return t && "function" == typeof Symbol && t.constructor === Symbol && t !== Symbol.prototype ? "symbol" : typeof t }; module.exports = function(e) { function n(t) { if (o[t]) return o[t].exports; var a = o[t] = { i: t, l: !1, exports: {} }; return e[t].call(a.exports, a, a.exports, n), a.l = !0, a.exports } var o = {}; return n.m = e, n.c = o, n.d = function(t, e, o) { n.o(t, e) || Object.defineProperty(t, e, { enumerable: !0, get: o }) }, n.r = function(t) { "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t, "__esModule", { value: !0 }) }, n.t = function(e, o) { if (1 & o && (e = n(e)), 8 & o) return e; if (4 & o && "object" === (void 0 === e ? "undefined" : t(e)) && e && e.__esModule) return e; var a = Object.create(null); if (n.r(a), Object.defineProperty(a, "default", { enumerable: !0, value: e }), 2 & o && "string" != typeof e) for (var i in e) n.d(a, i, function(t) { return e[t] }.bind(null, i)); return a }, n.n = function(t) { var e = t && t.__esModule ? function() { return t. default } : function() { return t }; return n.d(e, "a", e), e }, n.o = function(t, e) { return Object.prototype.hasOwnProperty.call(t, e) }, n.p = "", n(n.s = 9) }({ 9: function(t, e, n) { Component({ options: { addGlobalClass: !0 }, properties: { extClass: { type: String, value: "" }, show: { type: Boolean, value: !0, observer: function(t) { this._computedStyle(t, this.data.animated) } }, animated: { type: Boolean, value: !1, observer: function(t) { this._computedStyle(this.data.show, t) } }, duration: { type: Number, value: 350 }, type: { type: String, value: "dot-gray" }, tips: { type: String, value: "加载中" } }, data: { animationData: {}, animationInstance: {}, displayStyle: "none" }, methods: { _computedStyle: function(t, e) { t ? this.setData({ displayStyle: "" }) : e ? this._startAnimation() : this.setData({ displayStyle: "none" }) }, _startAnimation: function() { var t = this; setTimeout(function() { var e = t.data.animationInstance; e.height(0).step(), t.setData({ animationData: e.export() }) }, 0) } }, lifetimes: { attached: function() { var t = this.data, e = wx.createAnimation({ duration: t.duration, timingFunction: "ease" }); this.setData({ animationInstance: e }), this._computedStyle(this.data.show, this.data.animated) } } }) } });<file_sep>/lionfish_comshop/moduleA/pin/index.js var util = require("../../utils/util.js"), status = require("../../utils/index.js"), app = getApp(); Page({ data: { classification: { tabs: [], activeIndex: 0 }, slider_list: [], pintuan_show_type: 0, loadMore: !0, loadText: "加载中...", loadOver: !1, showEmpty: !1, rushList: [], isIpx: app.globalData.isIpx }, pageNum: 1, onLoad: function(t) { this.initFn() }, initFn: function() { wx.showLoading(), this.getTabs(), this.getData() }, authSuccess: function() { var t = this; this.pageNum = 1, this.setData({ classification: { tabs: [], activeIndex: 0 }, slider_list: [], pintuan_show_type: 0, loadMore: !0, loadText: "加载中...", loadOver: !1, showEmpty: !1, rushList: [] }, function() { t.initFn() }) }, authModal: function() { return !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, getTabs: function() { var l = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "group.pintuan_slides" }, dataType: "json", success: function(t) { if (0 == t.data.code) { var a = t.data, e = a.category_list, i = a.pintuan_show_type, n = a.slider_list, s = a.pintuan_index_share_title, o = a.pintuan_index_share_img, u = { classification: {} }; u.slider_list = n || [], u.pintuan_show_type = i, u.pintuan_index_share_title = s || "", u.pintuan_index_share_img = o || ""; 0 < (e = e || []).length ? (e.unshift({ name: "推荐", id: 0 }), u.isShowClassification = !0, u.classification.tabs = e) : u.isShowClassification = !1, l.setData(u) } } }) }, onShow: function() { var a = this; (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && a.setData({ cartNum: t.data }) }) }, classificationChange: function(t) { console.log(t.detail.e), wx.showLoading(); var a = this; this.pageNum = 1, this.setData({ rushList: [], showEmpty: !1, "classification.activeIndex": t.detail.e, classificationId: t.detail.a }, function() { a.getData() }) }, getData: function() { var d = this, t = wx.getStorageSync("token"), a = d.data.classificationId, r = wx.getStorageSync("community").communityId || 0; app.util.request({ url: "entry/wxapp/index", data: { controller: "group.get_pintuan_list", pageNum: this.pageNum, gid: a, token: t, head_id: r }, dataType: "json", success: function(t) { if (wx.hideLoading(), wx.stopPullDownRefresh(), 0 == t.data.code) { var a = d.data.rushList; 1 == d.pageNum && (a = []); var e = {}, i = t.data.list; 1 == d.pageNum && 0 == i.length && (e.showEmpty = !0); var n = a.concat(i), s = t.data, o = { full_money: s.full_money, full_reducemoney: s.full_reducemoney, is_open_fullreduction: s.is_open_fullreduction }, u = s.pintuan_model_buy || 0; e.rushList = n, e.reduction = o, e.loadOver = !0, e.loadText = d.data.loadMore ? "加载中..." : "没有更多商品了~", 1 == (e.pintuan_model_buy = u) && (e.needPosition = !0, !r && d.needCommunity()), d.setData(e, function() { d.pageNum += 1 }) } else if (1 == t.data.code) { var l = { loadMore: !1 }; 1 == d.pageNum && (l.showEmpty = !0), d.setData(l) } else 2 == t.data.code && d.setData({ needAuth: !0 }) } }) }, needCommunity: function() { var t = wx.getStorageSync("token"), a = this; console.log("需要社区"), t && util.getCommunityInfo().then(function(t) { a.pageNum = 1, a.setData({ loadMore: !0, loadText: "加载中...", loadOver: !1, showEmpty: !1, rushList: [] }, function() { a.getData() }) }) }, goBannerUrl: function(t) { var a = t.currentTarget.dataset.idx, e = this.data, i = e.slider_list, n = e.needAuth; if (0 < i.length) { var s = i[a].link, o = i[a].linktype; if (util.checkRedirectTo(s, n)) return void this.authModal(); if (0 == o) s && wx.navigateTo({ url: "/lionfish_comshop/pages/web-view?url=" + encodeURIComponent(s) }); else if (1 == o) - 1 != s.indexOf("lionfish_comshop/pages/index/index") || -1 != s.indexOf("lionfish_comshop/pages/order/shopCart") || -1 != s.indexOf("lionfish_comshop/pages/user/me") || -1 != s.indexOf("lionfish_comshop/pages/type/index") ? s && wx.switchTab({ url: s }) : s && wx.navigateTo({ url: s }); else if (2 == o) { i[a].appid && wx.navigateToMiniProgram({ appId: i[a].appid, path: s, extraData: {}, envVersion: "release", success: function(t) {}, fail: function(t) { console.log(t) } }) } } }, onPullDownRefresh: function() { var t = this; this.pageNum = 1, this.setData({ loadMore: !0, loadText: "加载中...", loadOver: !1, showEmpty: !1, rushList: [] }, function() { t.getData() }) }, onReachBottom: function() { console.log("这是我的底线"), this.data.loadMore && (this.setData({ loadOver: !1 }), this.getData()) }, onShareAppMessage: function() { var t = wx.getStorageSync("member_id"), a = this.data; return { title: a.pintuan_index_share_title, path: "lionfish_comshop/moduleA/pin/index?share_id=" + t, imageUrl: a.pintuan_index_share_img, success: function() {}, fail: function() {} } }, onShareTimeline: function () { var t = wx.getStorageSync("member_id"), a = this.data; return { title: a.pintuan_index_share_title, query: "share_id=" + t, imageUrl: a.pintuan_index_share_img, } } });<file_sep>/lionfish_comshop/components/datetimepicker/datetimepicker.js function _defineProperty(t, a, s) { return a in t ? Object.defineProperty(t, a, { value: s, enumerable: !0, configurable: !0, writable: !0 }) : t[a] = s, t } Component({ behaviors: ["wx://form-field"], externalClasses: ["i-class"], properties: { format: { type: String }, name: { type: String }, placeholder: { type: String } }, data: {}, lifetimes: { attached: function() { var t = new Date, a = t.getFullYear(), s = t.getMonth() + 1, i = t.getDate(), e = t.getHours(), r = t.getMinutes(), h = t.getSeconds(); this.setData({ chooseYear: a }), this.initColumn(s), 2 == s && this.setData({ days: this.data.multiArray[2] }); var d = s < 10 ? "0" + s : s, o = i < 10 ? "0" + i : i, n = e < 10 ? "0" + e : e, u = r < 10 ? "0" + r : r, m = h < 10 ? "0" + h : h, y = this.data.years.indexOf(a + ""), l = this.data.months.indexOf(d + ""), f = this.data.days.indexOf(o + ""), p = this.data.hours.indexOf(n + ""), c = this.data.minutes.indexOf(u + ""), A = this.data.seconds.indexOf(m + ""), v = [], M = [], D = this.properties.format; "yyyy-MM-dd" == D && (v = [y, l, f], a + "-" + d + "-" + o, M = [this.data.years, this.data.months, this.data.days]), "HH:mm:ss" == D && (v = [p, c, A], n + ":" + u + ":" + m, M = [this.data.hours, this.data.minutes, this.data.seconds]), "yyyy-MM-dd HH:mm" == D && (v = [y, l, f, p, c], a + "-" + d + "-" + o + " " + n + ":" + u, M = [this.data.years, this.data.months, this.data.days, this.data.hours, this.data.minutes]), "yyyy-MM-dd HH:mm:ss" == D && (v = [y, l, f, p, c, A], a + "-" + d + "-" + o + " " + n + ":" + u + ":" + m, M = [this.data.years, this.data.months, this.data.days, this.data.hours, this.data.minutes, this.data.seconds]), this.setData({ multiIndex: v, multiArray: M, curMonth: s, chooseYear: a }) } }, methods: { bindPickerChange: function(t) { this.setData({ multiIndex: t.detail.value }); var a = this.data.multiIndex, s = this.properties.format, i = ""; "yyyy-MM-dd" == s && (i = this.data.multiArray[0][a[0]] + "-" + this.data.multiArray[1][a[1]] + "-" + this.data.multiArray[2][a[2]]); "HH:mm:ss" == s && (i = this.data.multiArray[0][a[0]] + ":" + this.data.multiArray[1][a[1]] + ":" + this.data.multiArray[2][a[2]]); "yyyy-MM-dd HH:mm" == s && (i = this.data.multiArray[0][a[0]] + "-" + this.data.multiArray[1][a[1]] + "-" + this.data.multiArray[2][a[2]] + " " + this.data.multiArray[3][a[3]] + ":" + this.data.multiArray[4][a[4]]); "yyyy-MM-dd HH:mm:ss" == s && (i = this.data.multiArray[0][a[0]] + "-" + this.data.multiArray[1][a[1]] + "-" + this.data.multiArray[2][a[2]] + " " + this.data.multiArray[3][a[3]] + ":" + this.data.multiArray[4][a[4]] + ":" + this.data.multiArray[5][a[5]]); this.setData({ value: i }), this.triggerEvent("dateTimePicker", i) }, initColumn: function(t) { for (var a = [], s = [], i = [], e = [], r = [], h = [], d = 2019; d <= 2099; d++) a.push(d + ""); for (var o = 1; o <= 12; o++) o < 10 && (o = "0" + o), s.push(o + ""); if (1 == t || 3 == t || 5 == t || 7 == t || 8 == t || 10 == t || 12 == t) for (var n = 1; n <= 31; n++) n < 10 && (n = "0" + n), i.push(n + ""); if (4 == t || 6 == t || 9 == t || 11 == t) for (var u = 1; u <= 30; u++) u < 10 && (u = "0" + u), i.push(u + ""); 2 == t && this.setFebDays(); for (var m = 0; m <= 23; m++) m < 10 && (m = "0" + m), e.push(m + ""); for (var y = 0; y <= 59; y++) y < 10 && (y = "0" + y), r.push(y + ""); for (var l = 0; l <= 59; l++) l < 10 && (l = "0" + l), h.push(l + ""); this.setData({ years: a, months: s, days: i, hours: e, minutes: r, seconds: h }) }, bindPickerColumnChange: function(t) { if (0 == t.detail.column && "HH:mm:ss" != this.properties.format) { var a = this.data.multiArray[t.detail.column][t.detail.value]; this.setData({ chooseYear: a }), "02" != this.data.curMonth && "02" != this.data.chooseMonth || this.setFebDays() } if (1 == t.detail.column && "HH:mm:ss" != this.properties.format) { var s = parseInt(this.data.multiArray[t.detail.column][t.detail.value]), i = []; if (1 == s || 3 == s || 5 == s || 7 == s || 8 == s || 10 == s || 12 == s) { for (var e = 1; e <= 31; e++) e < 10 && (e = "0" + e), i.push("" + e); this.setData(_defineProperty({}, "multiArray[2]", i)) } else if (4 == s || 6 == s || 9 == s || 11 == s) { for (var r = 1; r <= 30; r++) r < 10 && (r = "0" + r), i.push("" + r); this.setData(_defineProperty({}, "multiArray[2]", i)) } else 2 == s && this.setFebDays() } var h = { multiArray: this.data.multiArray, multiIndex: this.data.multiIndex }; h.multiIndex[t.detail.column] = t.detail.value, this.setData(h) }, setFebDays: function() { var t = parseInt(this.data.chooseYear), a = []; if (t % (t % 100 ? 4 : 400)) { for (var s, i = 1; i <= 28; i++) i < 10 && (i = "0" + i), a.push("" + i); this.setData((_defineProperty(s = {}, "multiArray[2]", a), _defineProperty(s, "chooseMonth", "02"), s)) } else { for (var e, r = 1; r <= 29; r++) r < 10 && (r = "0" + r), a.push("" + r); this.setData((_defineProperty(e = {}, "multiArray[2]", a), _defineProperty(e, "chooseMonth", "02"), e)) } } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/lottery/lottery.js "use strict"; var t = function(t) { return t && t.__esModule ? t : { default: t } }(require("../lottie-miniprogram/miniprogram_dist/index.js")), n = wx.getSystemInfoSync() || {}; Component({ properties: { from: { type: String, value: "pusher" }, type: { type: String, value: "" }, countTime: { type: String, value: "" }, showCountTime: { type: Boolean, value: !1 }, showEndIcon: { type: Boolean, value: !1 }, firstStartLotteryAnimation: { type: Boolean, value: !1 }, nextStartLotteryAnimation: { type: Boolean, value: !1 }, endLotteryAnimation: { type: Boolean, value: !1 } }, data: { canvas: "" }, ready: function() { "player" === this.data.from && this.createLotteryAnimation() }, observers: { showEndIcon: function(t) {}, firstStartLotteryAnimation: function(t) { t && this.playLotteryAnimation() }, nextStartLotteryAnimation: function(t) { t && this.playLotteryAnimation() }, endLotteryAnimation: function(t) { t && this.playLotteryAnimation() } }, methods: { isSupportLotteryAnimation: function() { var t = n.platform, e = n.version, i = void 0 === e ? "" : e; return i = i.split("."), ("android" === t || "ios" === t) && +("" + i[0] + i[1] + i[2]) >= 707 || "windows" === t && +("" + i[0] + i[1] + i[2]) >= 271 }, createLotteryAnimation: function() { var n = this; if (this.isSupportLotteryAnimation()) { var e = new t. default. default; this.createSelectorQuery().selectAll("#lottery__canvas").node(function(t) { var i = t[0].node, o = i.getContext("2d"); i.width = 2 * i._width, i.height = 2 * i._height, n.data.canvas = i, e.setup(i); var a = e.loadAnimation({ loop: !1, autoplay: !1, renderer: "canvas", path: "https://cdn.jsdelivr.net/gh/youbaowu/lottiefiles@v1.0/lottery/lottery.json", rendererSettings: { context: o } }); n.lotteryAnimation = a }).exec() } }, playLotteryAnimation: function() { var t = this; this.isSupportLotteryAnimation() && this.lotteryAnimation && (this.data.canvas.width = 2 * this.data.canvas._width, this.data.canvas.height = 2 * this.data.canvas._height, this.data.firstStartLotteryAnimation ? (this.lotteryAnimation.playSegments([0, 55], !0), this.lotteryAnimation.onComplete = function() { t.setData({ firstStartLotteryAnimation: !1 }) }) : this.data.nextStartLotteryAnimation ? (this.lotteryAnimation.playSegments([ [122, 144], [0, 55] ], !0), this.lotteryAnimation.onComplete = function() { t.setData({ nextStartLotteryAnimation: !1 }) }) : this.data.endLotteryAnimation && (this.lotteryAnimation.playSegments([ [56, 95, { duration: 5 }], [96, 121] ], !0), this.lotteryAnimation.onComplete = function() { t.setData({ endLotteryAnimation: !1 }) })) }, clickLottery: function() { this.triggerEvent("customevent", { confirmClickLottery: !0, showLotteryOper: !0 }) } } });<file_sep>/lionfish_comshop/distributionCenter/pages/goodsDetails.js var _extends = Object.assign || function(t) { for (var a = 1; a < arguments.length; a++) { var e = arguments[a]; for (var n in e) Object.prototype.hasOwnProperty.call(e, n) && (t[n] = e[n]) } return t }, app = getApp(), util = require("../../utils/util.js"); Page({ data: { currentTab: 0, pageSize: 10, navList: [{ name: "全部", status: "-1" }, { name: "待结算", status: "0" }, { name: "已结算", status: "1" }, { name: "已失效", status: "2" }], list: [], loadText: "加载中...", info: {}, noData: 0, loadMore: !0, stateArr: ["待结算", "已结算", "已失效"] }, page: 1, onLoad: function(t) { this.getInfo(), this.getData() }, getInfo: function() { wx.showLoading(); var t = wx.getStorageSync("token"), a = this; app.util.request({ url: "entry/wxapp/user", data: { controller: "distribution.get_commission_info", token: t }, dataType: "json", success: function(t) { wx.hideLoading(), 0 == t.data.code ? a.setData({ info: t.data.data }) : wx.showModal({ title: "提示", content: t.data.msg, showCancel: !1, success: function(t) { t.confirm && (console.log("用户点击确定"), wx.reLaunch({ url: "/lionfish_comshop/pages/user/me" })) } }) } }) }, getData: function() { var n = this, t = wx.getStorageSync("token"), a = this.data.currentTab, e = this.data.navList[a].status; wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "distribution.listorder_list", token: t, state: e, page: this.page }, dataType: "json", success: function(t) { if (0 == t.data.code) { var a = {}, e = t.data.data; e.length < 6 && (a.noMore = !0), e = n.data.list.concat(e), n.page++, n.setData(_extends({ list: e }, a)) } else 1 == n.page && n.setData({ noData: 1 }), n.setData({ loadMore: !1, noMore: !1, loadText: "没有更多记录了~" }); wx.hideLoading() } }) }, getCurrentList: function() { if (!this.data.loadMore) return !1; this.getData(), this.setData({ isHideLoadMore: !1 }) }, onReachBottom: function() { this.getCurrentList() }, bindChange: function(t) { var a = this; this.page = 1, this.setData({ currentTab: t, list: [], noData: 0, loadMore: !0, loadText: "加载中..." }, function() { console.log("我变啦"), a.getData() }) }, switchNav: function(t) { var a = this; if (this.data.currentTab === 1 * t.target.dataset.current) return !1; var e = 1 * t.target.dataset.current; this.setData({ currentTab: e }, function() { a.bindChange(e) }) }, handleTipDialog: function() { this.setData({ showTipDialog: !this.data.showTipDialog }) } });<file_sep>/lionfish_comshop/pages/supply/recruit.js var app = getApp(), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ data: {}, onLoad: function(t) { status.setNavBgColor(); var s = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "supply.get_apply_page" }, dataType: "json", success: function(t) { var a = t.data.supply_diy_name || "供应商"; if (wx.setNavigationBarTitle({ title: a }), s.setData({ supply_diy_name: a }), 0 == t.data.code) { console.log(t); var e = t.data.data || ""; s.setData({ article: e.replace('< img ', '< img style="max-width:100%;height:auto;display:block;margin:10px 0;"') }) } } }) }, onShow: function() { var a = this; util.check_login_new().then(function(t) { a.setData({ needAuth: !t }) }) }, authModal: function() { return !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, authSuccess: function() { this.setData({ needAuth: !1, showAuthModal: !1 }) }, goLink: function(t) { if (this.authModal()) { var a = t.currentTarget.dataset.link; 3 < getCurrentPages().length ? wx.redirectTo({ url: a }) : wx.navigateTo({ url: a }) } }, onShareAppMessage: function() {} });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/end-block/end-block.js "use strict"; Component({ properties: function(e, t, i) { return t in e ? Object.defineProperty(e, t, { value: i, enumerable: !0, configurable: !0, writable: !0 }) : e[t] = i, e }({ from: { type: String, value: "" }, liveDuration: { type: String, value: "" }, liveStat: { type: Object, value: {} }, liveStatSimulateWatch: { type: String }, liveStatSimulateLike: { type: String } }, "from", { type: String, value: "" }), data: {}, methods: {} });<file_sep>/lionfish_comshop/moduleA/menu/list.js var app = getApp(), util = require("../../utils/util.js"); Page({ data: { loadMore: !0, classification: { tabs: [], activeIndex: 0 } }, pageNum: 1, onLoad: function(t) { this.gid = t.gid || ""; var n = t.name || ""; n && wx.setNavigationBarTitle({ title: n }), this._doRefreshMasonry() }, onShow: function() { var n = this; util.check_login_new().then(function(t) { n.setData({ needAuth: !t }) }) }, noLogin: function() { this.setData({ needAuth: !0, showAuthModal: !0 }) }, authSuccess: function() { var t = this; this.pageNum = 1, this.setData({ loadMore: !0, showEmpty: 0, needAuth: !1, showAuthModal: !1 }, function() { t._doRefreshMasonry() }) }, authModal: function() { return !this.data.needAuth || (this.setData({ showAuthModal: !this.data.showAuthModal }), !1) }, onPullDownRefresh: function() { var t = this; this.pageNum = 1, this.setData({ loadMore: !0, showEmpty: 0 }, function() { t.getInfo(), t._doRefreshMasonry() }) }, onReachBottom: function() { this.data.loadMore && this._doAppendMasonry() }, _doRefreshMasonry: function() { var n = this; this.masonryListComponent = this.selectComponent("#masonry"), this.getData().then(function(t) { n.masonryListComponent.start(t).then(function() {}) }). catch (function() { n.masonryListComponent.start([]).then(function() {}) }) }, _doAppendMasonry: function() { var n = this; this.masonryListComponent = this.selectComponent("#masonry"), this.getData().then(function(t) { n.masonryListComponent.append(t).then(function() { console.log("refresh completed") }) }). catch (function() { console.log("没有更多了") }) }, getData: function() { var o = this; return new Promise(function(e, a) { var s = o, t = wx.getStorageSync("token"), n = s.gid; wx.showLoading(), app.util.request({ url: "entry/wxapp/index", data: { controller: "recipe.get_recipe_list", token: t, gid: n, pageNum: o.pageNum }, dataType: "json", success: function(t) { if (wx.stopPullDownRefresh(), 0 == t.data.code) { var n = t.data.data; s.pageNum++, e(n) } else { var o = { loadMore: !1 }; 1 == s.pageNum && (o.showEmpty = 1), s.setData(o), a("") } wx.hideLoading() } }) }) } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/logic/ui.js "use strict"; function t() { return wx.getMenuButtonBoundingClientRect() } function e() { return wx.getSystemInfoSync().statusBarHeight + 44 } function n() { return wx.getSystemInfoSync().model.indexOf("iPhone X") >= 0 } function o(t) { wx.setNavigationBarColor({ frontColor: "#000000", backgroundColor: t }) } function r() { try { return wx.getSystemInfoSync().windowWidth } catch (t) { return 0 } } function i() { try { return wx.getSystemInfoSync().windowHeight } catch (t) { return 0 } } function u() { try { return "ios" === wx.getSystemInfoSync().platform } catch (t) { return 0 } } Object.defineProperty(exports, "__esModule", { value: !0 }), module.exports = { getMenuButtonBoundingPosition: t, getPaddingTop: e, isIPhoneX: n, setNavFontColor: o, getScreenWidth: r, getScreenHeight: i, isIos: u }, exports. default = { getMenuButtonBoundingPosition: t, getPaddingTop: e, isIPhoneX: n, setNavFontColor: o, getScreenWidth: r, getScreenHeight: i, isIos: u };<file_sep>/lionfish_comshop/components/painter/lib/downloader.js Object.defineProperty(exports, "__esModule", { value: !0 }); var _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(e) { return typeof e } : function(e) { return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e }, _createClass = function() { function n(e, t) { for (var i = 0; i < t.length; i++) { var n = t[i]; n.enumerable = n.enumerable || !1, n.configurable = !0, "value" in n && (n.writable = !0), Object.defineProperty(e, n.key, n) } } return function(e, t, i) { return t && n(e.prototype, t), i && n(e, i), e } }(); function _classCallCheck(e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") } var util = require("./util"), SAVED_FILES_KEY = "savedFiles", KEY_TOTAL_SIZE = "totalSize", KEY_PATH = "path", KEY_TIME = "time", KEY_SIZE = "size", MAX_SPACE_IN_B = 6291456, savedFiles = {}, Dowloader = function() { function e() { _classCallCheck(this, e), getApp().PAINTER_MAX_LRU_SPACE && (MAX_SPACE_IN_B = getApp().PAINTER_MAX_LRU_SPACE), wx.getStorage({ key: SAVED_FILES_KEY, success: function(e) { e.data && (savedFiles = e.data) } }) } return _createClass(e, [{ key: "download", value: function(o) { return new Promise(function(t, i) { if (o && util.isValidUrl(o)) { var n = getFile(o); n ? wx.getSavedFileInfo({ filePath: n[KEY_PATH], success: function(e) { t(n[KEY_PATH]) }, fail: function(e) { console.error("the file is broken, redownload it, " + JSON.stringify(e)), downloadFile(o).then(function(e) { t(e) }, function() { i() }) } }) : downloadFile(o).then(function(e) { t(e) }, function() { i() }) } else t(o) }) } }]), e }(); function downloadFile(r) { return new Promise(function(n, o) { wx.downloadFile({ url: r, success: function(t) { if (200 !== t.statusCode) return console.error("downloadFile " + r + " failed res.statusCode is not 200"), void o(); var i = t.tempFilePath; wx.getFileInfo({ filePath: i, success: function(e) { var t = e.size; doLru(t).then(function() { saveFile(r, t, i).then(function(e) { n(e) }) }, function() { n(i) }) }, fail: function(e) { console.error("getFileInfo " + t.tempFilePath + " failed, " + JSON.stringify(e)), n(t.tempFilePath) } }) }, fail: function(e) { console.error("downloadFile failed, " + JSON.stringify(e) + " "), o() } }) }) } function saveFile(n, o, t) { return new Promise(function(i, e) { wx.saveFile({ tempFilePath: t, success: function(e) { var t = savedFiles[KEY_TOTAL_SIZE] ? savedFiles[KEY_TOTAL_SIZE] : 0; savedFiles[n] = {}, savedFiles[n][KEY_PATH] = e.savedFilePath, savedFiles[n][KEY_TIME] = (new Date).getTime(), savedFiles[n][KEY_SIZE] = o, savedFiles.totalSize = o + t, wx.setStorage({ key: SAVED_FILES_KEY, data: savedFiles }), i(e.savedFilePath) }, fail: function(e) { console.error("saveFile " + n + " failed, then we delete all files, " + JSON.stringify(e)), i(t), reset() } }) }) } function reset() { wx.removeStorage({ key: SAVED_FILES_KEY, success: function() { wx.getSavedFileList({ success: function(e) { removeFiles(e.fileList) }, fail: function(e) { console.error("getSavedFileList failed, " + JSON.stringify(e)) } }) } }) } function doLru(d) { return new Promise(function(e, t) { var i = savedFiles[KEY_TOTAL_SIZE] ? savedFiles[KEY_TOTAL_SIZE] : 0; if (d + i <= MAX_SPACE_IN_B) e(); else { var n = [], o = JSON.parse(JSON.stringify(savedFiles)); delete o[KEY_TOTAL_SIZE]; var r = Object.keys(o).sort(function(e, t) { return o[e][KEY_TIME] - o[t][KEY_TIME] }), l = !0, s = !1, a = void 0; try { for (var f, u = r[Symbol.iterator](); !(l = (f = u.next()).done); l = !0) { var c = f.value; if (i -= savedFiles[c].size, n.push(savedFiles[c][KEY_PATH]), delete savedFiles[c], i + d < MAX_SPACE_IN_B) break } } catch (e) { s = !0, a = e } finally { try { !l && u. return &&u. return () } finally { if (s) throw a } } savedFiles.totalSize = i, wx.setStorage({ key: SAVED_FILES_KEY, data: savedFiles, success: function() { 0 < n.length && removeFiles(n), e() }, fail: function(e) { console.error("doLru setStorage failed, " + JSON.stringify(e)), t() } }) } }) } function removeFiles(e) { var t = !0, i = !1, n = void 0; try { for (var o, r = function() { var t = o.value, e = t; "object" === (void 0 === t ? "undefined" : _typeof(t)) && (e = t.filePath), wx.removeSavedFile({ filePath: e, fail: function(e) { console.error("removeSavedFile " + t + " failed, " + JSON.stringify(e)) } }) }, l = e[Symbol.iterator](); !(t = (o = l.next()).done); t = !0) r() } catch (e) { i = !0, n = e } finally { try { !t && l. return &&l. return () } finally { if (i) throw n } } } function getFile(e) { if (savedFiles[e]) return savedFiles[e].time = (new Date).getTime(), wx.setStorage({ key: SAVED_FILES_KEY, data: savedFiles }), savedFiles[e] } exports. default = Dowloader;<file_sep>/lionfish_comshop/pages/order/shopCart.js var util = require("../../utils/util.js"), status = require("../../utils/index.js"), a = require("../../utils/public"), app = getApp(), addFlag = 1; Page({ data: { allselect: !1, community_id: 0, allnum: 0, tablebar: 3, allcount: "0.00", recount: "0.00", carts: {}, isEmpty: !1, needAuth: !1, cartNum: 0, isIpx: !1, disAmount: 0, totalAmount: 0, reduceNum: 0, tabIdx: 0, updateCart: 0, invalidCarts: {}, tabList: [] }, onLoad: function(t) { wx.hideTabBar(), wx.showLoading() }, authSuccess: function() { wx.reLaunch({ url: "/lionfish_comshop/pages/order/shopCart" }) }, authModal: function() { this.data.needAuth && this.setData({ showAuthModal: !this.data.showAuthModal }) }, onShow: function() { var s = this; util.check_login_new().then(function(t) { if (console.log(t), t) { var a = wx.getStorageSync("community").communityId || ""; s.setData({ needAuth: !1, isEmpty: !1, tabbarRefresh: !0, community_id: a, isIpx: app.globalData.isIpx }), (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && s.setData({ cartNum: t.data }) }), s.showCartGoods() } else s.setData({ needAuth: !0, isEmpty: !0 }), wx.hideLoading() }) }, showCartGoods: function() { var w = this, t = wx.getStorageSync("community").communityId; console.log("onshow购物车里面的community_id:"), w.setData({ community_id: t }); var a = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "car.show_cart_goods", token: a, community_id: t, buy_type: "dan" }, dataType: "json", success: function(t) { if (setTimeout(function() { wx.hideLoading() }, 1e3), 0 == t.data.code) { var a = t.data.mult_carts || [], s = {}, e = w.data.tabIdx, o = !1, r = [{ id: 0, name: "团长代收", enabled: !1 }, { id: 1, name: "快递直发", enabled: !1 }, { id: 2, name: "到店核销", enabled: !1 }], c = Object.keys(a), i = c.length; 1 < i ? (o = !0, c.forEach(function(t) { r[t].enabled = !0 }), s = a[e] || {}) : 1 == i && (s = a[e = c[0]] || {}); var n = !0; 0 != Object.keys(s).length && (n = !1, s = w.sortCarts(s)); var d = t.data, l = d.man_free_tuanzshipping, u = d.delivery_tuanz_money, h = d.is_comunity_rest, p = d.open_man_orderbuy, m = d.man_orderbuy_money, _ = d.is_show_guess_like, g = d.is_open_vipcard_buy, y = d.is_vip_card_member, f = d.vipcard_save_money, v = d.modify_vipcard_name, x = d.is_member_level_buy, k = d.level_save_money, b = !1; 1 == g ? 1 != y && 1 == x && (b = !0) : 1 == x && (b = !0), w.setData({ carts: s, mult_carts: a, showTab: o, isEmpty: n, is_comunity_rest: h, open_man_orderbuy: p, man_orderbuy_money: 1 * m, is_show_guess_like: _, man_free_tuanzshipping: l, delivery_tuanz_money: u, is_open_vipcard_buy: g, is_vip_card_member: y, vipcard_save_money: f, modify_vipcard_name: v, is_member_level_buy: x, canLevelBuy: b, level_save_money: k, tabList: r }), w.xuan_func() } else w.setData({ needAuth: !0, isEmpty: !0 }), wx.hideTabBar() } }) }, onHide: function() { this.setData({ tabbarRefresh: !1 }), console.log("onHide") }, sortCarts: function(a) { var o = 0, r = 0, c = 0, i = 0, n = {}, d = 0, t = function(s) { r = a[s].is_open_fullreduction, c = a[s].full_reducemoney, i = a[s].full_money, n[s] = { id: a[s].id, shopcarts: [] }; var t = a[s].shopcarts, e = []; t.forEach(function(t, a) { 0 == t.can_buy || 0 == t.option_can_buy ? (n[s].shopcarts.push(t), d += 1) : (e.push(t), 1 == t.can_man_jian && o++) }), (a[s].shopcarts = e).sort(function(t, a) { return t.can_man_jian < a.can_man_jian ? 1 : t.can_man_jian > a.can_man_jian ? -1 : 0 }) }; for (var s in a) t(s); return this.setData({ reduceNum: o, is_open_fullreduction: r, full_reducemoney: c, full_money: i, invalidCarts: n, hasInvalid: d }), a }, xuan_func: function() { var t = 0, a = 0, s = 1, e = !1, o = 1, r = this.data; r.is_open_vipcard_buy, r.is_vip_card_member; for (var c in this.data.carts) { var i = 0; this.data.carts[c].goodstypeselect = 0, this.data.carts[c].goodstype = this.data.carts[c].shopcarts.length; for (var n = 0; n < this.data.carts[c].shopcarts.length; n++) { var d = this.data.carts[c].shopcarts[n]; 0 == d.isselect && 1 == d.can_buy && 1 == d.can_buy && 1 == d.option_can_buy && (s = 0), d.isselect && 1 == d.can_buy && 1 == d.can_buy && 1 == d.option_can_buy && (o = 0, i = this.calcVipPrice(i, d), this.data.carts[c].goodstypeselect++, t = parseInt(t) + parseInt(d.goodsnum)), 0 == d.can_buy && (d.isselect = !1) } this.data.carts[c].count = i.toFixed(2), a += i } 1 == s && 0 == o && (e = !0), this.setData({ allselect: e, allnum: t, allcount: a.toFixed(2), carts: this.data.carts }), this.calcAmount() }, edit: function(t) { var a = parseInt(t.target.dataset.index); this.data.carts[a].caredit = "none", this.data.carts[a].finish = "inline"; for (var s = 0; s < this.data.carts[a].shopcarts.length; s++) this.data.carts[a].shopcarts[s].edit = "none", this.data.carts[a].shopcarts[s].finish = "inline", this.data.carts[a].shopcarts[s].description = "onedit-description", this.data.carts[a].shopcarts[s].cartype = "block"; this.setData({ carts: this.data.carts }) }, finish: function(t) { var a = parseInt(t.target.dataset.index); this.data.carts[a].caredit = "inline", this.data.carts[a].finish = "none"; for (var s = 0; s < this.data.carts[a].shopcarts.length; s++) this.data.carts[a].shopcarts[s].edit = "inline", this.data.carts[a].shopcarts[s].finish = "none", this.data.carts[a].shopcarts[s].description = "description", this.data.carts[a].shopcarts[s].cartype = "inline"; this.setData({ carts: this.data.carts }) }, goLink: function(t) { var a = t.currentTarget.dataset.link; wx.redirectTo({ url: a }) }, goGoods: function(t) { var a = t.currentTarget.dataset.type; 3 < getCurrentPages().length ? wx.redirectTo({ url: "/Snailfish_shop/pages/goods/index?id=" + a }) : wx.navigateTo({ url: "/Snailfish_shop/pages/goods/index?id=" + a }) }, shopselect: function(t) { var a = parseInt(t.target.dataset.index), s = this.data.allselect, e = 0, o = 0, r = 0; if (1 == this.data.carts[a].isselect) { s = this.data.carts[a].isselect = !1; for (var c = 0; c < this.data.carts[a].shopcarts.length; c++) 1 == this.data.carts[a].shopcarts[c].isselect && (this.data.carts[a].shopcarts[c].isselect = !1, e = parseInt(e) + parseInt(this.data.carts[a].shopcarts[c].goodsnum), this.data.carts[a].goodstypeselect = this.data.carts[a].goodstypeselect - 1); e = this.data.allnum - e, o = parseFloat(this.data.allcount) - parseFloat(this.data.carts[a].count), this.data.carts[a].count = "0.00", this.setData({ carts: this.data.carts, allnum: e, allcount: o.toFixed(2), allselect: s }) } else { var i = 0; this.data.carts[a].isselect = !0; for (c = 0; c < this.data.carts[a].shopcarts.length; c++) { var n = this.data.carts[a].shopcarts[c]; 0 == n.isselect && (n.isselect = !0, this.data.carts[a].goodstypeselect = this.data.carts[a].goodstypeselect + 1, e = parseInt(e) + parseInt(n.goodsnum), i = this.calcVipPrice(i, n)), r = this.calcVipPrice(r, n) } e = this.data.allnum + e, o = parseFloat(this.data.allcount) + i, this.data.carts[a].count = r.toFixed(2); var d = 1; for (var c in this.data.carts) for (var l = 0; l < this.data.carts[c].shopcarts.length; l++) 0 == this.data.carts[c].shopcarts[l].isselect && (d = 0); 1 == d && (s = !0), this.setData({ carts: this.data.carts, allnum: e, allcount: o.toFixed(2), allselect: s }) } this.go_record() }, goodsselect: function(t) { var a = parseInt(t.target.dataset.parentid), s = parseInt(t.target.dataset.index), e = this.data.allselect, o = this.data.carts[a].shopcarts[s]; if (1 == o.isselect) { o.isselect = !1, e && (e = !1), this.data.carts[a].goodstypeselect = parseInt(this.data.carts[a].goodstypeselect) - 1, this.data.carts[a].goodstypeselect <= 0 && (this.data.carts[a].isselect = !1); var r = parseInt(this.data.allnum) - parseInt(o.goodsnum), c = this.calcVipPrice(this.data.allcount, o, "", "red"), i = this.calcVipPrice(this.data.carts[a].count, o, "", "red"); this.data.carts[a].count = i.toFixed(2), this.setData({ carts: this.data.carts, allnum: r, allcount: c.toFixed(2), allselect: e }) } else { o.isselect = !0, this.data.carts[a].goodstypeselect = parseInt(this.data.carts[a].goodstypeselect) + 1, 0 < this.data.carts[a].goodstypeselect && (this.data.carts[a].isselect = !0); var n = 1; for (var d in this.data.carts) { console.log("in"); for (var l = 0; l < this.data.carts[d].shopcarts.length; l++) 0 == this.data.carts[d].shopcarts[l].isselect && 1 == this.data.carts[d].shopcarts[l].can_buy && 1 == this.data.carts[d].shopcarts[l].option_can_buy && (n = 0) } 1 == n && (e = !0); r = parseInt(this.data.allnum) + parseInt(o.goodsnum), c = this.calcVipPrice(this.data.allcount, o), i = this.calcVipPrice(this.data.carts[a].count, o); this.data.carts[a].count = i.toFixed(2), this.setData({ carts: this.data.carts, allnum: r, allcount: c.toFixed(2), allselect: e }) } this.go_record() }, allselect: function(t) { var a = this.data.allselect; this.data.carts; if (a) { a = !1; var s = 0, e = 0; for (var o in this.data.carts) for (var r in this.data.carts[o].count = "0.00", this.data.carts[o].isselect = !1, this.data.carts[o].goodstypeselect = 0, this.data.carts[o].shopcarts) this.data.carts[o].shopcarts[r].isselect = !1; this.setData({ carts: this.data.carts, allnum: s, allcount: e.toFixed(2), allselect: a }) } else { a = !0; s = 0, e = 0; for (var o in this.data.carts) { var c = 0; this.data.carts[o].isselect = !0; var i = this.data.carts[o].shopcarts; for (var r in this.data.carts[o].goodstypeselect = i.length, i) 1 == i[r].can_buy && 1 == i[r].option_can_buy && (c = this.calcVipPrice(c, i[r]), s = parseInt(s) + parseInt(this.data.carts[o].shopcarts[r].goodsnum), i[r].isselect = !0); this.data.carts[o].count = c.toFixed(2), e += c } this.setData({ carts: this.data.carts, allnum: s, allcount: e.toFixed(2), allselect: a }) } this.go_record() }, regoodsnum: function(t) { var a = parseInt(t.currentTarget.dataset.parentid), s = parseInt(t.currentTarget.dataset.index), e = this.data.updateCart, o = this.data.carts[a].shopcarts[s], r = this; if (1 == o.goodsnum) r.cofirm_del(a, s); else if (1 == o.isselect) { var c = parseInt(this.data.allnum) - 1, i = this.calcVipPrice(r.data.allcount, o, 1, "red"), n = this.calcVipPrice(this.data.carts[a].count, o, 1, "red"); r.data.carts[a].count = n.toFixed(2), o.goodsnum = o.goodsnum - 1, this.setData({ carts: this.data.carts, allnum: c, allcount: i.toFixed(2) }) } else o.goodsnum = parseInt(o.goodsnum) - 1, this.setData({ carts: this.data.carts }); if ("" == o.goodstype) { var d = 1 * o.goodsnum, l = t.currentTarget.dataset.gid; status.indexListCarCount(l, d), r.setData({ updateCart: e + 1 }) } r.go_record() }, cofirm_del: function(l, u) { 2 < arguments.length && void 0 !== arguments[2] && arguments[2]; var h = this, p = this.data.updateCart; wx.showModal({ title: "提示", content: "确定删除这件商品吗?", confirmColor: "#FF0000", success: function(t) { if (t.confirm) { var a = h.data.carts[l].shopcarts[u]; if ("" == a.goodstype) { var s = a.id; status.indexListCarCount(s, 0), h.setData({ updateCart: p + 1 }) } var e = a.key, o = h.data.reduceNum; if (1 == a.can_man_jian && (o--, h.setData({ reduceNum: o }), console.log(o)), 1 == a.isselect) { var r = h.data.allnum - 1, c = h.calcVipPrice(h.data.allcount, a, 1, "red"), i = h.calcVipPrice(h.data.carts[l].count, a, 1, "red"); if (h.data.carts[l].count = i.toFixed(2), h.data.carts[l].goodstype = h.data.carts[l].goodstype - 1, h.data.carts[l].goodstypeselect = h.data.carts[l].goodstypeselect - 1, 0 == h.data.carts[l].goodstype) { var n = h.data.carts; delete n[l], 0 == Object.keys(n).length && h.setData({ isEmpty: !0 }) } else h.data.carts[l].shopcarts.splice(u, 1), h.isAllSelect(); h.setData({ carts: h.data.carts, allnum: r, allcount: c.toFixed(2) }) } else { if (h.data.carts[l].goodstype = h.data.carts[l].goodstype - 1, 0 == h.data.carts[l].goodstype) { var d = h.data.carts; delete d[l], 0 == Object.keys(d).length && h.setData({ isEmpty: !0 }) } else h.data.carts[l].shopcarts.splice(u, 1); h.setData({ carts: h.data.carts }) } h.del_car_goods(e), h.calcAmount() } else console.log("取消删除") } }) }, isAllSelect: function() { var t = 1, a = !1, s = this.data.carts, e = 0; for (var o in s) for (var r = 0; r < s[o].shopcarts.length; r++) 1 == s[o].shopcarts[r].can_buy && 1 == s[o].shopcarts[r].option_can_buy && (e = 1), 0 == s[o].shopcarts[r].isselect && 1 == s[o].shopcarts[r].can_buy && 1 == s[o].shopcarts[r].option_can_buy && (t = 0); 1 == t && 1 == e && (a = !0), this.setData({ allselect: a }) }, addgoodsnum: function(r) { if (0 != addFlag) { addFlag = 0; var c = parseInt(r.currentTarget.dataset.parentid), t = parseInt(r.currentTarget.dataset.index), i = this, n = this.data.carts[c].shopcarts[t], a = parseInt(n.max_quantity); if (1 == n.isselect) { var d = parseInt(this.data.allnum) + 1, s = this.calcVipPrice(this.data.allcount, n, 1), e = this.calcVipPrice(this.data.carts[c].count, n, 1); if (i.data.carts[c].count = e.toFixed(2), !(n.goodsnum < a)) { addFlag = 1, n.goodsnum = a, d--; var o = "最多购买" + a + "个"; return wx.showToast({ title: o, icon: "none", duration: 2e3 }), !1 } n.goodsnum = parseInt(n.goodsnum) + 1, this.setData({ carts: this.data.carts, allnum: d, allcount: s.toFixed(2) }) } else { if (!(parseInt(n.goodsnum) < a)) { addFlag = 1; o = "最多购买" + a + "个"; return wx.showToast({ title: o, icon: "none", duration: 2e3 }), !1 } n.goodsnum = parseInt(n.goodsnum) + 1 } var l = wx.getStorageSync("token"), u = [], h = [], p = (d = this.data.allnum, this.data.carts); for (var m in p) for (var _ in p[m].shopcarts) u.push(p[m].shopcarts[_].key), h.push(p[m].shopcarts[_].key + "_" + p[m].shopcarts[_].goodsnum); var g = this.data.updateCart || 0; app.util.request({ url: "entry/wxapp/index", data: { controller: "car.checkout_flushall", token: l, car_key: u, community_id: i.data.community_id, all_keys_arr: h }, method: "POST", dataType: "json", success: function(t) { if (0 == t.data.code) { if (i.setData({ carts: i.data.carts }), (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && i.setData({ cartNum: t.data }) }), "" == n.goodstype) { var a = 1 * n.goodsnum, s = r.currentTarget.dataset.gid; status.indexListCarCount(s, a), i.setData({ updateCart: g + 1 }) } } else { if (n.goodsnum = parseInt(n.goodsnum) - 1, 1 == n.isselect) { var e = i.calcVipPrice(i.data.allcount, n, 1, "red"), o = i.calcVipPrice(i.data.carts[c].count, n, 1, "red"); i.data.carts[c].count = o.toFixed(2), d--, i.setData({ allnum: d, allcount: e.toFixed(2) }) } i.setData({ carts: i.data.carts }), wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }) } addFlag = 1, i.calcAmount() } }) } }, changeNumber: function(t) { if (!(Object.keys(this.data.carts).length <= 0)) { wx.hideLoading(); var e = this, o = parseInt(t.currentTarget.dataset.parentid), r = parseInt(t.currentTarget.dataset.index), a = t.detail.value, c = e.count_goods(o, r), s = this.data.carts[o].shopcarts[r], i = s.goodsnum; console.log(a); var n = this.data.updateCart || 0; if (0 < a) { var d = parseInt(s.max_quantity); d < a && (a = d, wx.showToast({ title: "不能购买更多啦", icon: "none" })), s.goodsnum = a, 1 == e.data.carts[o].shopcarts[r].isselect && (c = e.count_goods(o, r)), this.setData({ carts: this.data.carts, allnum: c.allnum, allcount: c.allcount }); var l = wx.getStorageSync("token"), u = [], h = [], p = (this.data.allnum, this.data.carts); for (var m in p) for (var _ in p[m].shopcarts) u.push(p[m].shopcarts[_].key), h.push(p[m].shopcarts[_].key + "_" + p[m].shopcarts[_].goodsnum); app.util.request({ url: "entry/wxapp/index", data: { controller: "car.checkout_flushall", token: l, car_key: u, community_id: e.data.community_id, all_keys_arr: h }, method: "POST", dataType: "json", success: function(t) { if (0 == t.data.code) { if (e.setData({ carts: e.data.carts }), (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && e.setData({ cartNum: t.data }) }), "" == e.data.carts[o].shopcarts[r].goodstype) { var a = 1 * e.data.carts[o].shopcarts[r].goodsnum, s = e.data.carts[o].shopcarts[r].id; status.indexListCarCount(s, a), e.setData({ updateCart: n + 1 }) } e.go_record() } else e.data.carts[o].shopcarts[r].goodsnum = i, 1 == e.data.carts[o].shopcarts[r].isselect && (c = e.count_goods(o, r)), e.setData({ carts: e.data.carts, allnum: c.allnum, allcount: c.allcount }), wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }) } }) } else { wx.hideLoading(), (this.data.carts[o].shopcarts[r].goodsnum = 1) == e.data.carts[o].shopcarts[r].isselect && (c = e.count_goods(o, r)), this.setData({ carts: this.data.carts, allnum: c.allnum, allcount: c.allcount }); l = wx.getStorageSync("token"), u = [], h = [], this.data.allnum, p = this.data.carts; for (var m in p) for (var _ in p[m].shopcarts) u.push(p[m].shopcarts[_].key), h.push(p[m].shopcarts[_].key + "_" + p[m].shopcarts[_].goodsnum); app.util.request({ url: "entry/wxapp/index", data: { controller: "car.checkout_flushall", token: l, car_key: u, community_id: e.data.community_id, all_keys_arr: h }, method: "POST", dataType: "json", success: function(t) { if (0 == t.data.code) { if (e.setData({ carts: e.data.carts }), (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && e.setData({ cartNum: t.data }) }), "" == e.data.carts[o].shopcarts[r].goodstype) { var a = 1 * e.data.carts[o].shopcarts[r].goodsnum, s = e.data.carts[o].shopcarts[r].id; status.indexListCarCount(s, a), e.setData({ updateCart: n + 1 }) } e.go_record() } } }), e.cofirm_del(o, r) } } }, count_goods: function(t, a) { var s = this, e = this.data.carts, o = 0, r = 0, c = !0, i = !1, n = void 0; try { for (var d, l = Object.keys(e)[Symbol.iterator](); !(c = (d = l.next()).done); c = !0) { e[d.value].shopcarts.forEach(function(t, a) { t.isselect && (r = s.calcVipPrice(r, t), o += parseInt(t.goodsnum)) }) } } catch (t) { i = !0, n = t } finally { try { !c && l. return &&l. return () } finally { if (i) throw n } } return { allnum: o, allcount: r.toFixed(2) } }, delgoods: function(t) { var d = parseInt(t.target.dataset.parentid), l = parseInt(t.target.dataset.index), u = this; wx.showModal({ title: "提示", content: "确定删除这件商品吗?", confirmColor: "#FF0000", success: function(t) { if (t.confirm) { var a = u.data.carts[d].shopcarts[l], s = a.key; if (1 == a.isselect) { var e = parseInt(u.data.allnum) - parseInt(a.goodsnum), o = u.calcVipPrice(u.data.allcount, a, 1, "red"), r = u.calcVipPrice(u.data.carts[d].count, a, 1, "red"); u.data.carts[d].count = r.toFixed(2), u.data.carts[d].goodstype = u.data.carts[d].goodstype - 1, u.data.carts[d].goodstypeselect = u.data.carts[d].goodstypeselect - 1, 0 == u.data.carts[d].goodstype && console.log(d), u.data.carts[d].shopcarts.splice(l, 1); for (var c = 0, i = 0; i < u.data.carts.length; i++) for (var n = 0; n < u.data.carts[i].shopcarts.length; n++) c += u.data.carts[i].shopcarts[n].goodsnum; e == c && (u.data.allselect = !0), u.setData({ carts: u.data.carts, allnum: e, allcount: o.toFixed(2), allselect: u.data.allselect }) } else { u.data.carts[d].goodstype = u.data.carts[d].goodstype - 1, u.data.carts[d].goodstype, u.data.carts[d].shopcarts.splice(l, 1); for (c = 0, i = 0; i < u.data.carts.length; i++) for (n = 0; n < u.data.carts[i].shopcarts.length; n++) c += u.data.carts[i].shopcarts[n].goodsnum; u.data.allnum == c && (u.data.allselect = !0), u.setData({ carts: u.data.carts, allselect: u.data.allselect }) } 0 == u.data.carts[d].shopcarts.length && (delete u.data.carts[d], 0 == Object.keys(u.data.carts).length && u.setData({ carts: [] })), u.del_car_goods(s) } } }), this.go_record() }, del_car_goods: function(t) { var a = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : 0, s = wx.getStorageSync("token"), e = this, o = this.data.updateCart; console.log("del_car_goods:开始"); var r = wx.getStorageSync("community").communityId; console.log("缓存中的:" + r), console.log("使用中的:" + e.data.community_id), app.util.request({ url: "entry/wxapp/index", data: { controller: "car.del_car_goods", carkey: t, community_id: e.data.community_id, token: s }, method: "POST", dataType: "json", success: function(t) { 0 == t.data.code && 1 != a && (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && e.setData({ cartNum: t.data, updateCart: o + 1 }) }) } }) }, delete: function(t) { var i = parseInt(t.currentTarget.dataset.parentid), n = parseInt(t.currentTarget.dataset.index), d = t.currentTarget.dataset.islost || 0, l = this; wx.showModal({ title: "提示", content: "确认删除这件商品吗?", confirmColor: "#FF0000", success: function(t) { if (t.confirm) if (1 == d) { var a = l.data, s = a.hasInvalid, e = a.invalidCarts; console.log(i); var o = e[i].shopcarts[n].key; e[i].shopcarts.splice(n, 1), s -= 1, l.setData({ invalidCarts: e, hasInvalid: s }), l.del_car_goods(o, 1) } else { var r = l.data.carts, c = r[i].shopcarts[n].key; r[i].shopcarts.splice(n, 1), l.setData({ carts: r }), 0 == r[i].shopcarts.length && (delete r[i], 0 == Object.keys(r).length && l.setData({ carts: {} })), l.del_car_goods(c) } } }) }, clearlose: function() { var e = this; wx.showModal({ title: "提示", content: "确认清空失效商品吗?", confirmColor: "#FF0000", success: function(t) { if (t.confirm) { var a = e.data.invalidCarts; for (var s in a) { a[s].shopcarts.forEach(function(t) { var a = t.key; e.del_car_goods(a, 1) }) } e.setData({ hasInvalid: 0, invalidCarts: {} }) } } }) }, go_record: function() { var a = this, t = wx.getStorageSync("token"), s = [], e = [], o = (this.data.allnum, this.data.carts); for (var r in o) for (var c in o[r].shopcarts) o[r].shopcarts[c].isselect && s.push(o[r].shopcarts[c].key), e.push(o[r].shopcarts[c].key + "_" + o[r].shopcarts[c].goodsnum); app.util.request({ url: "entry/wxapp/index", data: { controller: "car.checkout_flushall", token: t, car_key: s, community_id: a.data.community_id, all_keys_arr: e }, method: "POST", dataType: "json", success: function(t) { 0 == t.data.code ? (0, status.cartNum)("", !0).then(function(t) { 0 == t.code && a.setData({ cartNum: t.data }) }) : wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }) } }), a.calcAmount() }, toorder: function() { var t = wx.getStorageSync("token"), a = [], s = [], e = this; if (0 < this.data.allnum) { var o = this.data.carts; for (var r in o) for (var c in o[r].shopcarts) o[r].shopcarts[c].isselect && a.push(o[r].shopcarts[c].key), s.push(o[r].shopcarts[c].key + "_" + o[r].shopcarts[c].goodsnum); app.util.request({ url: "entry/wxapp/index", data: { controller: "car.checkout_flushall", token: t, community_id: e.data.community_id, car_key: a, all_keys_arr: s }, method: "POST", dataType: "json", success: function(t) { if (0 == t.data.code) { var a = t.data.data || 0; wx.navigateTo({ url: "/lionfish_comshop/pages/order/placeOrder?type=dan&is_limit=" + a }) } else e.showCartGoods(), wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }) } }) } else wx.showModal({ title: "提示", content: "请选择您要购买的商品", confirmColor: "#FF0000", success: function(t) { t.confirm } }) }, goindex: function() { wx.switchTab({ url: "/lionfish_comshop/pages/index/index" }) }, calcAmount: function() { var t = this.data, o = t.is_open_vipcard_buy, r = t.is_vip_card_member, c = t.carts, i = t.delivery_tuanz_money, n = t.man_free_tuanzshipping, a = t.vipcard_save_money, d = t.canLevelBuy, s = t.level_save_money, e = t.allcount, l = 0, u = 0, h = 0, p = Object.getOwnPropertyNames(c), m = [], _ = 0, g = 0, y = 0, f = 0, v = 0; p.forEach(function(t, a) { var s = c[t]; if (0 == (s.is_open_fullreduction || 0)) return !1; var e = s.shopcarts; _ = 1 * s.full_money, g = 1 * s.full_reducemoney, e.forEach(function(t) { t.isselect && t.can_man_jian && m.push(t), t.isselect && 0 < n && 0 < i && (1 == o && 1 == r && 1 == t.is_take_vipcard ? x += t.card_price * t.goodsnum * 1 : d && 1 == t.is_mb_level_buy ? x += t.levelprice * t.goodsnum * 1 : x += t.currntprice * t.goodsnum * 1), 1 == o && 1 == r && 1 == t.is_take_vipcard && t.isselect && (f += (t.currntprice - t.card_price) * t.goodsnum * 1), 1 == d && 1 == t.is_mb_level_buy && t.isselect && (v += (t.currntprice - t.levelprice) * t.goodsnum * 1) }) }); var x = 0; m.forEach(function(t) { t.isselect && t.can_man_jian && (1 == o && 1 == r && 1 == t.is_take_vipcard ? x += t.card_price * t.goodsnum * 1 : d && 1 == t.is_mb_level_buy ? x += t.levelprice * t.goodsnum * 1 : x += t.currntprice * t.goodsnum * 1) }), _ <= x ? u += g : h = _ - x, l = (1 * e - u).toFixed(2), 1 == o && 1 == r ? l = (l - 1 * a).toFixed(2) : d && (l = (l - 1 * s).toFixed(2)); var k = 1 * (l = l <= 0 ? 0 : l) - this.data.man_orderbuy_money, b = 1 * e - f, w = 1 * e - v; console.log("deliveryGoodsTot", y); var D = 0; (y = l) < 1 * n && (D = 1 * n - y), this.setData({ totalAmount: l, disAmount: u.toFixed(2), diffMoney: h.toFixed(2), canbuy_other: k.toFixed(2), diffDeliveryMoney: D.toFixed(2), vipFee: f.toFixed(2), vipTotal: b.toFixed(2), levelFee: v.toFixed(2), levelToTal: w.toFixed(2) }) }, calcVipPrice: function(t, a) { var s = 2 < arguments.length && void 0 !== arguments[2] ? arguments[2] : 0, e = 3 < arguments.length && void 0 !== arguments[3] ? arguments[3] : "add", o = this.data, r = (o.is_open_vipcard_buy, o.is_vip_card_member, o.canLevelBuy, 0 < s ? s : parseFloat(a.goodsnum)); return "red" === e && (r *= -1), (t = parseFloat(t)) + parseFloat(a.currntprice) * r }, openSku: function(t) { var a = t.detail, s = a.actId, e = a.skuList; this.setData({ addCar_goodsid: s }); var o = e.list || [], r = []; if (0 < o.length) { for (var c = 0; c < o.length; c++) { var i = o[c].option_value[0], n = { name: i.name, id: i.option_value_id, index: c, idx: 0 }; r.push(n) } for (var d = "", l = 0; l < r.length; l++) l == r.length - 1 ? d += r[l].id : d = d + r[l].id + "_"; var u = e.sku_mu_list[d]; this.setData({ sku: r, sku_val: 1, cur_sku_arr: u, skuList: a.skuList, visible: !0, showSku: !0 }) } else { var h = a.allData; this.setData({ sku: [], sku_val: 1, skuList: [], cur_sku_arr: h }); var p = { detail: { formId: "" } }; p.detail.formId = "the formId is a mock one", this.gocarfrom(p) } }, gocarfrom: function(t) { wx.showLoading(), a.collectFormIds(t.detail.formId), this.goOrder() }, goOrder: function() { var o = this; o.data.can_car && (o.data.can_car = !1); wx.getStorageSync("token"); var t = wx.getStorageSync("community"), r = o.data.addCar_goodsid, a = t.communityId, s = o.data.sku_val, e = o.data.cur_sku_arr, c = "", i = o.data.updateCart; e && e.option_item_ids && (c = e.option_item_ids); var n = { goods_id: r, community_id: a, quantity: s, sku_str: c, buy_type: "dan", pin_id: 0, is_just_addcar: 1 }; util.addCart(n).then(function(t) { if (1 == t.showVipModal) { var a = t.data.pop_vipmember_buyimage; wx.hideLoading(), o.setData({ pop_vipmember_buyimage: a, showVipModal: !0, visible: !1 }) } else if (3 == t.data.code || 7 == t.data.code) wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }); else if (4 == t.data.code) wx.showToast({ title: "您未登录", duration: 2e3, success: function() { o.setData({ needAuth: !0, isEmpty: !0 }) } }); else if (6 == t.data.code) { var s = t.data.max_quantity || ""; 0 < s && o.setData({ sku_val: s, updateCart: i + 1 }); var e = t.data.msg; wx.showToast({ title: e, icon: "none", duration: 2e3 }) } else o.closeSku(), o.showCartGoods(), status.indexListCarCount(r, t.data.cur_count), (0, status.cartNum)(t.data.total), o.setData({ cartNum: t.data.total, updateCart: i + 1 }), wx.showToast({ title: "已加入购物车", image: "../../images/addShopCart.png" }) }). catch (function(t) { app.util.message(t || "请求失败", "", "error") }) }, selectSku: function(t) { var a = t.currentTarget.dataset.type.split("_"), s = this.data.sku, e = { name: a[3], id: a[2], index: a[0], idx: a[1] }; s.splice(a[0], 1, e), this.setData({ sku: s }); for (var o = "", r = 0; r < s.length; r++) r == s.length - 1 ? o += s[r].id : o = o + s[r].id + "_"; var c = this.data.skuList.sku_mu_list[o]; this.setData({ cur_sku_arr: c }) }, setNum: function(t) { var a = t.currentTarget.dataset.type, s = 1, e = 1 * this.data.sku_val; "add" == a ? s = e + 1 : "decrease" == a && 1 < e && (s = e - 1); var o = this.data.sku, r = this.data.skuList; if (0 < o.length) for (var c = "", i = 0; i < o.length; i++) i == o.length - 1 ? c += o[i].id : c = c + o[i].id + "_"; 0 < r.length ? s > r.sku_mu_list[c].canBuyNum && (s -= 1) : s > this.data.cur_sku_arr.canBuyNum && (s -= 1); this.setData({ sku_val: s }) }, skuConfirm: function() { this.closeSku(), (0, status.cartNum)().then(function(t) { 0 == t.code && that.setData({ cartNum: t.data }) }) }, closeSku: function() { this.setData({ visible: 0, stopClick: !1 }) }, changeTabs: function(t) { var a = this, s = t.currentTarget.dataset.idx || 0, e = this.data, o = e.tabIdx, r = e.carts, c = e.mult_carts; if (o != s) { c[o] = r, r = c[s]; var i = !0; 0 != Object.keys(r).length && (i = !1), this.setData({ tabIdx: s, mult_carts: c, isEmpty: i, carts: r }, function() { a.xuan_func() }) } }, vipModal: function(t) { this.setData(t.detail) } });<file_sep>/lionfish_comshop/pages/video/detail.js var app = getApp(); Page({ data: { is_heng: 1 }, onLoad: function(o) { var t = o.id || ""; this.get_goods_details(t) }, onShow: function() {}, goDetails: function() { var o = this.data.goods.id || ""; o && wx.redirectTo({ url: "/lionfish_comshop/pages/goods/goodsDetail?id=" + o }) }, get_goods_details: function(o) { var a = this; if (!o) return wx.hideLoading(), wx.showModal({ title: "提示", content: "参数错误", showCancel: !1, confirmColor: "#F75451", success: function(o) { o.confirm && wx.redirectTo({ url: "/lionfish_comshop/pages/index/index" }) } }), !1; var t = wx.getStorageSync("token"), i = wx.getStorageSync("community").communityId || ""; app.util.request({ url: "entry/wxapp/index", data: { controller: "goods.get_goods_detail", token: t, id: o, community_id: i }, dataType: "json", success: function(o) { wx.hideLoading(); var t = o.data.data && o.data.data.goods || ""; t && 0 != t.length && "" != Object.keys(t) || wx.showModal({ title: "提示", content: "该商品不存在,回首页", showCancel: !1, confirmColor: "#F75451", success: function(o) { o.confirm && wx.switchTab({ url: "/lionfish_comshop/pages/index/index" }) } }), a.currentOptions = o.data.data.options, a.setData({ goods: t, options: o.data.data.options, order: { goods_id: o.data.data.goods.goods_id, pin_id: o.data.data.pin_id }, share_title: t.share_title, goods_image: o.data.data.goods_image }) } }) }, onShareAppMessage: function() { var o = wx.getStorageSync("community"), t = this.data.goods, a = o.communityId, i = this.data.share_title, e = wx.getStorageSync("member_id"), d = "lionfish_comshop/pages/video/detail?id=" + t.id + "&share_id=" + e + "&community_id=" + a, s = this.data.goods.goods_share_image; return console.log("商品分享地址:", d), { title: i, path: d, imageUrl: s, success: function(o) {}, fail: function(o) {} } } });<file_sep>/lionfish_comshop/moduleA/solitaire/pub.js var _extends = Object.assign || function(t) { for (var e = 1; e < arguments.length; e++) { var i = arguments[e]; for (var a in i) Object.prototype.hasOwnProperty.call(i, a) && (t[a] = i[a]) } return t }, app = getApp(), util = require("../../utils/util.js"), chooseFlag = !0, myDate = new Date; Page({ data: { begin_time: "", end_time: "", noteMaxLen: 500, imgGroup: [], goods: [], type: 0, title: "", content: "" }, onLoad: function(t) { this.getData() }, onShow: function() {}, titleInput: function(t) { var e = t.detail.value; this.setData({ title: e }) }, beginTimePicker: function(t) { this.setData({ begin_time: t.detail }) }, endTimePicker: function(t) { this.setData({ end_time: t.detail }) }, contentInput: function(t) { var e = t.detail.value, i = parseInt(e.length); i > this.data.noteMaxLen || this.setData({ currentNoteLen: i, limitNoteLen: this.data.noteMaxLen - i, content: e }) }, chooseImage: function() { chooseFlag = !1 }, changeImg: function(t) { chooseFlag = t.detail.len === t.detail.value.length, this.setData({ imgGroup: t.detail.value }) }, deleteGoods: function(t) { var e = t.detail; console.log(e); var i = this.data.goods; - 1 != e && (i.splice(e, 1), this.setData({ goods: i })) }, getData: function() { var t = wx.getStorageSync("token"), e = this; app.util.request({ url: "entry/wxapp/index", data: { controller: "solitaire.get_solitaire_headinfo", token: t }, dataType: "json", success: function(t) { if (0 != t.data.code) return 1 == t.data.code ? void app.util.message("您还未登录", "switchTo:/lionfish_comshop/pages/index/index", "error") : void app.util.message(t.data.msg, "switchTo:/lionfish_comshop/pages/index/index", "error"); e.setData({ community: t.data.data || "" }) } }) }, subForm: function() { var t = this.data, e = t.title, i = t.content, a = t.begin_time, o = t.end_time, n = t.imgGroup, s = t.goods; if ("" != e) if ("" != i) if (n.length <= 0) wx.showToast({ title: "请上传接龙图片", icon: "none" }); else if (s.length <= 0) wx.showToast({ title: "请选择商品", icon: "none" }); else { var l = []; s.forEach(function(t) { l.push(t.gid) }); var r = l.join(","), c = wx.getStorageSync("token"), d = { title: e, content: i, begin_time: a, end_time: o, images_list: n.join(","), goods_list: r, token: c }; app.util.request({ url: "entry/wxapp/index", data: _extends({ controller: "solitaire.sub_head_solitaire" }, d), dataType: "json", success: function(t) { 0 == t.data.code ? app.util.message("提交成功", "redirect:/lionfish_comshop/moduleA/solitaire/groupIndex", "success") : app.util.message(t.data.msg || "提交失败", "", "error") } }) } else wx.showToast({ title: "请输入内容", icon: "none" }); else wx.showToast({ title: "请输入标题", icon: "none" }) } });<file_sep>/lionfish_comshop/pages/groupCenter/communityMembers.js var page = 1, app = getApp(), util = require("../../utils/util.js"), timeFormat = require("../../utils/timeFormat"); Page({ data: { isCalling: !1, queryData: { createTime: null, communityId: null, order: [], page: page, pageSize: 20 }, maxDate: (0, timeFormat.formatYMD)(new Date), searchKey: "", date: "", containerHeight: 0, showLoadMore: !1, no_order: 0, page: 1, hide_tip: !0, order: [], tip: "正在加载" }, onLoad: function(e) { var a = wx.getSystemInfoSync(); this.setData({ containerHeight: a.windowHeight - Math.round(a.windowWidth / 375 * 125) }), page = 1, this.data.queryData.communityId = app.globalData.disUserInfo.communityId, this.data.queryData.createTime = null, this.getData() }, onShow: function() { var e = this.data.is_show_on; 0 < e ? (this.setData({ page: 1, order: [] }), this.getData()) : this.setData({ is_show_on: e + 1 }) }, getData: function() { wx.showLoading({ title: "加载中...", mask: !0 }), this.setData({ isHideLoadMore: !0 }), this.data.no_order = 1; var i = this, e = wx.getStorageSync("token"); app.util.request({ url: "entry/wxapp/index", data: { controller: "community.get_community_member_orderlist", date: i.data.date, searchKey: i.data.searchKey, token: e, page: i.data.page }, dataType: "json", success: function(e) { if (0 != e.data.code) return i.setData({ isHideLoadMore: !0 }), wx.hideLoading(), !1; var a = e.data.close_community_delivery_orders || 0, t = i.data.order.concat(e.data.data); i.setData({ order: t, hide_tip: !0, no_order: 0, close_community_delivery_orders: a }), wx.hideLoading() } }) }, getTodayMs: function() { var e = new Date; return e.setHours(0), e.setMinutes(0), e.setSeconds(0), e.setMilliseconds(0), Date.parse(e) }, bindSearchChange: function(e) { this.setData({ searchKey: e.detail.value }) }, searchByKey: function() { page = 1, this.setData({ order: [], no_order: 0, page: 1 }), this.data.queryData.memberNickName = this.data.searchKey, this.getData() }, cancel: function() { page = 1, this.setData({ searchKey: "", order: [] }), this.data.queryData.memberNickName = null, this.getData() }, bindDateChange: function(e) { page = 1, this.setData({ date: e.detail.value, order: [], no_order: 0, page: 1 }), this.data.queryData.createTime = new Date(e.detail.value).getTime() - 288e5, this.getData() }, clearDate: function() { page = 1, this.setData({ date: "", order: [], no_order: 0, page: 1 }), this.data.queryData.createTime = null, this.getData() }, callTelphone: function(e) { var a = this, t = e.currentTarget.dataset.phone; "未下单" != t && (this.data.isCalling || (this.data.isCalling = !0, wx.makePhoneCall({ phoneNumber: t, complete: function() { a.data.isCalling = !1 } }))) }, getMore: function() { if (1 == this.data.no_order) return !1; this.data.page += 1, this.getData(), this.setData({ isHideLoadMore: !1 }) }, goLink: function(e) { if (1 != this.data.close_community_delivery_orders) { var a = getCurrentPages(), t = e.currentTarget.dataset.link; 3 < a.length ? wx.redirectTo({ url: t }) : wx.navigateTo({ url: t }) } } });<file_sep>/lionfish_comshop/components/painter/lib/pen.js Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function i(t, s) { for (var e = 0; e < s.length; e++) { var i = s[e]; i.enumerable = i.enumerable || !1, i.configurable = !0, "value" in i && (i.writable = !0), Object.defineProperty(t, i.key, i) } } return function(t, s, e) { return s && i(t.prototype, s), e && i(t, e), t } }(); function _toConsumableArray(t) { if (Array.isArray(t)) { for (var s = 0, e = Array(t.length); s < t.length; s++) e[s] = t[s]; return e } return Array.from(t) } function _classCallCheck(t, s) { if (!(t instanceof s)) throw new TypeError("Cannot call a class as a function") } var QR = require("./qrcode.js"), GD = require("./gradient.js"), Painter = function() { function e(t, s) { _classCallCheck(this, e), this.ctx = t, this.data = s, this.globalWidth = {}, this.globalHeight = {} } return _createClass(e, [{ key: "paint", value: function(t) { this.style = { width: this.data.width.toPx(), height: this.data.height.toPx() }, this._background(); var s = !0, e = !1, i = void 0; try { for (var h, a = this.data.views[Symbol.iterator](); !(s = (h = a.next()).done); s = !0) { var r = h.value; this._drawAbsolute(r) } } catch (t) { e = !0, i = t } finally { try { !s && a. return &&a. return () } finally { if (e) throw i } } this.ctx.draw(!1, function() { t() }) } }, { key: "_background", value: function() { this.ctx.save(); var t = this.style, s = t.width, e = t.height, i = this.data.background; this.ctx.translate(s / 2, e / 2), this._doClip(this.data.borderRadius, s, e), i ? i.startsWith("#") || i.startsWith("rgba") || "transparent" === i.toLowerCase() ? (this.ctx.fillStyle = i, this.ctx.fillRect(-s / 2, -e / 2, s, e)) : GD.api.isGradient(i) ? (GD.api.doGradient(i, s, e, this.ctx), this.ctx.fillRect(-s / 2, -e / 2, s, e)) : this.ctx.drawImage(i, -s / 2, -e / 2, s, e) : (this.ctx.fillStyle = "#fff", this.ctx.fillRect(-s / 2, -e / 2, s, e)), this.ctx.restore() } }, { key: "_drawAbsolute", value: function(t) { switch (t.css && t.css.length && (t.css = Object.assign.apply(Object, _toConsumableArray(t.css))), t.type) { case "image": this._drawAbsImage(t); break; case "text": this._fillAbsText(t); break; case "rect": this._drawAbsRect(t); break; case "qrcode": this._drawQRCode(t) } } }, { key: "_doClip", value: function(t, s, e) { if (t && s && e) { var i = Math.min(t.toPx(), s / 2, e / 2); this.ctx.globalAlpha = 0, this.ctx.fillStyle = "white", this.ctx.beginPath(), this.ctx.arc(-s / 2 + i, -e / 2 + i, i, 1 * Math.PI, 1.5 * Math.PI), this.ctx.lineTo(s / 2 - i, -e / 2), this.ctx.arc(s / 2 - i, -e / 2 + i, i, 1.5 * Math.PI, 2 * Math.PI), this.ctx.lineTo(s / 2, e / 2 - i), this.ctx.arc(s / 2 - i, e / 2 - i, i, 0, .5 * Math.PI), this.ctx.lineTo(-s / 2 + i, e / 2), this.ctx.arc(-s / 2 + i, e / 2 - i, i, .5 * Math.PI, 1 * Math.PI), this.ctx.closePath(), this.ctx.fill(), getApp().systemInfo && getApp().systemInfo.version <= "6.6.6" && "ios" === getApp().systemInfo.platform || this.ctx.clip(), this.ctx.globalAlpha = 1 } } }, { key: "_doBorder", value: function(t, s, e) { if (t.css) { var i = t.css, h = i.borderRadius, a = i.borderWidth, r = i.borderColor; if (a) { this.ctx.save(), this._preProcess(t, !0); var c = void 0; c = h ? Math.min(h.toPx(), s / 2, e / 2) : 0; var o = a.toPx(); this.ctx.lineWidth = o, this.ctx.strokeStyle = r || "black", this.ctx.beginPath(), this.ctx.arc(-s / 2 + c, -e / 2 + c, c + o / 2, 1 * Math.PI, 1.5 * Math.PI), this.ctx.lineTo(s / 2 - c, -e / 2 - o / 2), this.ctx.arc(s / 2 - c, -e / 2 + c, c + o / 2, 1.5 * Math.PI, 2 * Math.PI), this.ctx.lineTo(s / 2 + o / 2, e / 2 - c), this.ctx.arc(s / 2 - c, e / 2 - c, c + o / 2, 0, .5 * Math.PI), this.ctx.lineTo(-s / 2 + c, e / 2 + o / 2), this.ctx.arc(-s / 2 + c, e / 2 - c, c + o / 2, .5 * Math.PI, 1 * Math.PI), this.ctx.closePath(), this.ctx.stroke(), this.ctx.restore() } } } }, { key: "_preProcess", value: function(t, s) { var e = 0, i = void 0, h = void 0; switch (t.type) { case "text": for (var a = t.text.split("\n"), r = 0; r < a.length; ++r) "" === a[r] && (a[r] = " "); var c = "bold" === t.css.fontWeight ? "bold" : "normal"; t.css.fontSize = t.css.fontSize ? t.css.fontSize : "20rpx", this.ctx.font = "normal " + c + " " + t.css.fontSize.toPx() + "px " + (t.css.fontFamily ? t.css.fontFamily : "sans-serif"); for (var o = 0, l = [], n = 0; n < a.length; ++n) { var x = this.ctx.measureText(a[n]).width, d = t.css.width ? t.css.width.toPx() : x, f = Math.ceil(x / d); e = e < d ? d : e, o += f, l[n] = f } o = t.css.maxLines < o ? t.css.maxLines : o; var g = t.css.lineHeight ? t.css.lineHeight.toPx() : t.css.fontSize.toPx(); i = g * o, h = { lines: o, lineHeight: g, textArray: a, linesArray: l }; break; case "image": var u = getApp().systemInfo.pixelRatio ? getApp().systemInfo.pixelRatio : 2; t.css && (t.css.width || (t.css.width = "auto"), t.css.height || (t.css.height = "auto")), !t.css || "auto" === t.css.width && "auto" === t.css.height ? (e = Math.round(t.sWidth / u), i = Math.round(t.sHeight / u)) : "auto" === t.css.width ? (i = t.css.height.toPx(), e = t.sWidth / t.sHeight * i) : "auto" === t.css.height ? (e = t.css.width.toPx(), i = t.sHeight / t.sWidth * e) : (e = t.css.width.toPx(), i = t.css.height.toPx()); break; default: if (!t.css.width || !t.css.height) return void console.error("You should set width and height"); e = t.css.width.toPx(), i = t.css.height.toPx() } var v = void 0; if (t.css && t.css.right) if ("string" == typeof t.css.right) v = this.style.width - t.css.right.toPx(!0); else { var P = t.css.right; v = this.style.width - P[0].toPx(!0) - this.globalWidth[P[1]] * (P[2] || 1) } else if (t.css && t.css.left) if ("string" == typeof t.css.left) v = t.css.left.toPx(!0); else { var b = t.css.left; v = b[0].toPx(!0) + this.globalWidth[b[1]] * (b[2] || 1) } else v = 0; var p = void 0; if (t.css && t.css.bottom) p = this.style.height - i - t.css.bottom.toPx(!0); else if (t.css && t.css.top) if ("string" == typeof t.css.top) p = t.css.top.toPx(!0); else { var w = t.css.top; p = w[0].toPx(!0) + this.globalHeight[w[1]] * (w[2] || 1) } else p = 0; var y = t.css && t.css.rotate ? this._getAngle(t.css.rotate) : 0; switch (t.css && t.css.align ? t.css.align : t.css && t.css.right ? "right" : "left") { case "center": this.ctx.translate(v, p + i / 2); break; case "right": this.ctx.translate(v - e / 2, p + i / 2); break; default: this.ctx.translate(v + e / 2, p + i / 2) } return this.ctx.rotate(y), !s && t.css && t.css.borderRadius && "rect" !== t.type && this._doClip(t.css.borderRadius, e, i), this._doShadow(t), t.id && (this.globalWidth[t.id] = e, this.globalHeight[t.id] = i), { width: e, height: i, x: v, y: p, extra: h } } }, { key: "_doBackground", value: function(t) { this.ctx.save(); var s = this._preProcess(t, !0), e = s.width, i = s.height, h = t.css, a = h.background, r = h.padding, c = [0, 0, 0, 0]; if (r) { var o = r.split(/\s+/); if (1 === o.length) { var l = o[0].toPx(); c = [l, l, l, l] } if (2 === o.length) { var n = o[0].toPx(), x = o[1].toPx(); c = [n, x, n, x] } if (3 === o.length) { var d = o[0].toPx(), f = o[1].toPx(); c = [d, f, o[2].toPx(), f] } if (4 === o.length) c = [o[0].toPx(), o[1].toPx(), o[2].toPx(), o[3].toPx()] } var g = e + c[1] + c[3], u = i + c[0] + c[2]; this._doClip(t.css.borderRadius, g, u), GD.api.isGradient(a) ? GD.api.doGradient(a, g, u, this.ctx) : this.ctx.fillStyle = a, this.ctx.fillRect(-g / 2, -u / 2, g, u), this.ctx.restore() } }, { key: "_drawQRCode", value: function(t) { this.ctx.save(); var s = this._preProcess(t), e = s.width, i = s.height; QR.api.draw(t.content, this.ctx, -e / 2, -i / 2, e, i, t.css.background, t.css.color), this.ctx.restore(), this._doBorder(t, e, i) } }, { key: "_drawAbsImage", value: function(t) { if (t.url) { this.ctx.save(); var s = this._preProcess(t), e = s.width, i = s.height, h = t.sWidth, a = t.sHeight, r = 0, c = 0, o = e / i; t.sWidth / t.sHeight <= o ? (a = h / o, c = Math.round((t.sHeight - a) / 2)) : (h = a * o, r = Math.round((t.sWidth - h) / 2)), t.css && "scaleToFill" === t.css.mode ? this.ctx.drawImage(t.url, -e / 2, -i / 2, e, i) : this.ctx.drawImage(t.url, r, c, h, a, -e / 2, -i / 2, e, i), this.ctx.restore(), this._doBorder(t, e, i) } } }, { key: "_fillAbsText", value: function(t) { if (t.text) { t.css.background && this._doBackground(t), this.ctx.save(); var s = this._preProcess(t, t.css.background && t.css.borderRadius), e = s.width, i = s.height, h = s.extra; this.ctx.fillStyle = t.css.color || "black"; var a = h.lines, r = h.lineHeight, c = h.textArray, o = h.linesArray; if (t.id) { for (var l = 0, n = 0; n < c.length; ++n) l = this.ctx.measureText(c[n]).width > l ? this.ctx.measureText(c[n]).width : l; this.globalWidth[t.id] = e ? l < e ? l : e : l } for (var x = 0, d = 0; d < c.length; ++d) for (var f = Math.round(c[d].length / o[d]), g = 0, u = 0, v = 0; v < o[d] && !(a <= x); ++v) { u = f; for (var P = c[d].substr(g, u), b = this.ctx.measureText(P).width; g + u <= c[d].length && (e - b > t.css.fontSize.toPx() || e < b);) { if (b < e) P = c[d].substr(g, ++u); else { if (P.length <= 1) break; P = c[d].substr(g, --u) } b = this.ctx.measureText(P).width } if (g += P.length, x === a - 1 && (d < c.length - 1 || g < c[d].length)) { for (; this.ctx.measureText(P + "...").width > e && !(P.length <= 1);) P = P.substring(0, P.length - 1); P += "...", b = this.ctx.measureText(P).width } this.ctx.setTextAlign(t.css.textAlign ? t.css.textAlign : "left"); var p = void 0; switch (t.css.textAlign) { case "center": p = 0; break; case "right": p = e / 2; break; default: p = -e / 2 } var w = -i / 2 + (0 === x ? t.css.fontSize.toPx() : t.css.fontSize.toPx() + x * r); x++, "stroke" === t.css.textStyle ? this.ctx.strokeText(P, p, w, b) : this.ctx.fillText(P, p, w, b); var y = t.css.fontSize.toPx(); t.css.textDecoration && (this.ctx.beginPath(), /\bunderline\b/.test(t.css.textDecoration) && (this.ctx.moveTo(p, w), this.ctx.lineTo(p + b, w)), /\boverline\b/.test(t.css.textDecoration) && (this.ctx.moveTo(p, w - y), this.ctx.lineTo(p + b, w - y)), /\bline-through\b/.test(t.css.textDecoration) && (this.ctx.moveTo(p, w - y / 3), this.ctx.lineTo(p + b, w - y / 3)), this.ctx.closePath(), this.ctx.strokeStyle = t.css.color, this.ctx.stroke()) } this.ctx.restore(), this._doBorder(t, e, i) } } }, { key: "_drawAbsRect", value: function(t) { this.ctx.save(); var s = this._preProcess(t), e = s.width, i = s.height; GD.api.isGradient(t.css.color) ? GD.api.doGradient(t.css.color, e, i, this.ctx) : this.ctx.fillStyle = t.css.color; var h = t.css.borderRadius, a = h ? Math.min(h.toPx(), e / 2, i / 2) : 0; this.ctx.beginPath(), this.ctx.arc(-e / 2 + a, -i / 2 + a, a, 1 * Math.PI, 1.5 * Math.PI), this.ctx.lineTo(e / 2 - a, -i / 2), this.ctx.arc(e / 2 - a, -i / 2 + a, a, 1.5 * Math.PI, 2 * Math.PI), this.ctx.lineTo(e / 2, i / 2 - a), this.ctx.arc(e / 2 - a, i / 2 - a, a, 0, .5 * Math.PI), this.ctx.lineTo(-e / 2 + a, i / 2), this.ctx.arc(-e / 2 + a, i / 2 - a, a, .5 * Math.PI, 1 * Math.PI), this.ctx.closePath(), this.ctx.fill(), this.ctx.restore(), this._doBorder(t, e, i) } }, { key: "_doShadow", value: function(t) { if (t.css && t.css.shadow) { var s = t.css.shadow.replace(/,\s+/g, ",").split(" "); 4 < s.length ? console.error("shadow don't spread option") : (this.ctx.shadowOffsetX = parseInt(s[0], 10), this.ctx.shadowOffsetY = parseInt(s[1], 10), this.ctx.shadowBlur = parseInt(s[2], 10), this.ctx.shadowColor = s[3]) } } }, { key: "_getAngle", value: function(t) { return Number(t) * Math.PI / 180 } }]), e }(); exports. default = Painter;<file_sep>/lionfish_comshop/components/painter/painter.js var _pen = require("./lib/pen"), _pen2 = _interopRequireDefault(_pen), _downloader = require("./lib/downloader"), _downloader2 = _interopRequireDefault(_downloader); function _interopRequireDefault(t) { return t && t.__esModule ? t : { default: t } } var util = require("./lib/util"), downloader = new _downloader2. default, MAX_PAINT_COUNT = 5; function setStringPrototype(a, o) { String.prototype.toPx = function(t) { var e = (t ? /^-?[0-9]+([.]{1}[0-9]+){0,1}(rpx|px)$/g : /^[0-9]+([.]{1}[0-9]+){0,1}(rpx|px)$/g).exec(this); if (!this || !e) return console.error("The size: " + this + " is illegal"), 0; var n = e[2], r = parseFloat(this), i = 0; return "rpx" === n ? i = Math.round(r * a * (o || 1)) : "px" === n && (i = Math.round(r * (o || 1))), i } } Component({ canvasWidthInPx: 0, canvasHeightInPx: 0, paintCount: 0, properties: { customStyle: { type: String }, palette: { type: Object, observer: function(t, e) { this.isNeedRefresh(t, e) && (this.paintCount = 0, this.startPaint()) } }, widthPixels: { type: Number, value: 0 }, dirty: { type: Boolean, value: !1 } }, data: { picURL: "", showCanvas: !0, painterStyle: "" }, methods: { isEmpty: function(t) { for (var e in t) return !1; return !0 }, isNeedRefresh: function(t, e) { return !(!t || this.isEmpty(t) || this.data.dirty && util.equal(t, e)) }, startPaint: function() { var i = this; if (!this.isEmpty(this.properties.palette)) { if (!getApp().systemInfo || !getApp().systemInfo.screenWidth) try { getApp().systemInfo = wx.getSystemInfoSync() } catch (t) { var e = "Painter get system info failed, " + JSON.stringify(t); return that.triggerEvent("imgErr", { error: e }), void console.error(e) } var a = getApp().systemInfo.screenWidth / 750; setStringPrototype(a, 1), this.downloadImages().then(function(t) { var e = t.width, n = t.height; if (e && n) { i.canvasWidthInPx = e.toPx(), i.properties.widthPixels && (setStringPrototype(a, i.properties.widthPixels / i.canvasWidthInPx), i.canvasWidthInPx = i.properties.widthPixels), i.canvasHeightInPx = n.toPx(), i.setData({ painterStyle: "width:" + i.canvasWidthInPx + "px;height:" + i.canvasHeightInPx + "px;" }); var r = wx.createCanvasContext("k-canvas", i); new _pen2. default (r, t).paint(function() { i.saveImgToLocal() }) } else console.error("You should set width and height correctly for painter, width: " + e + ", height: " + n) }) } }, downloadImages: function() { var c = this; return new Promise(function(n, t) { var r = 0, i = 0, a = JSON.parse(JSON.stringify(c.properties.palette)); if (a.background && (r++, downloader.download(a.background).then(function(t) { a.background = t, r === ++i && n(a) }, function() { r === ++i && n(a) })), a.views) { var e = !0, o = !1, s = void 0; try { for (var u, h = function() { var e = u.value; e && "image" === e.type && e.url && (r++, downloader.download(e.url).then(function(t) { e.url = t, wx.getImageInfo({ src: e.url, success: function(t) { e.sWidth = t.width, e.sHeight = t.height }, fail: function(t) { e.url = "", console.error("getImageInfo " + e.url + " failed, " + JSON.stringify(t)) }, complete: function() { r === ++i && n(a) } }) }, function() { r === ++i && n(a) })) }, l = a.views[Symbol.iterator](); !(e = (u = l.next()).done); e = !0) h() } catch (t) { o = !0, s = t } finally { try { !e && l. return &&l. return () } finally { if (o) throw s } } } 0 === r && n(a) }) }, saveImgToLocal: function() { var t = this, e = this; setTimeout(function() { wx.canvasToTempFilePath({ canvasId: "k-canvas", destWidth: e.canvasWidthInPx, destHeight: e.canvasHeightInPx, success: function(t) { e.getImageInfo(t.tempFilePath) }, fail: function(t) { console.error("canvasToTempFilePath failed, " + JSON.stringify(t)), e.triggerEvent("imgErr", { error: t }) } }, t) }, 300) }, getImageInfo: function(n) { var r = this; wx.getImageInfo({ src: n, success: function(t) { if (r.paintCount > MAX_PAINT_COUNT) { var e = "The result is always fault, even we tried " + MAX_PAINT_COUNT + " times"; return console.error(e), void r.triggerEvent("imgErr", { error: e }) } Math.abs((t.width * r.canvasHeightInPx - r.canvasWidthInPx * t.height) / (t.height * r.canvasHeightInPx)) < .01 ? r.triggerEvent("imgOK", { path: n }) : r.startPaint(), r.paintCount++ }, fail: function(t) { console.error("getImageInfo failed, " + JSON.stringify(t)), r.triggerEvent("imgErr", { error: t }) } }) } } });<file_sep>/lionfish_comshop/pages/user/rule.js var app = getApp(); Page({ onLoad: function(a) { var i = a.type || ""; if (!i) return wx.showModal({ title: "提示", content: "参数错误", showCancel: !1, confirmColor: "#F75451", success: function(a) { a.confirm && wx.navigateBack() } }), !1; wx.setNavigationBarTitle({ title: { vipcard: "权益规则", pintuan: "拼团规则", signin: "活动规则", solitaire: "接龙规则" }[i] || "规则" }), wx.showLoading(), this.getData(i) }, getData: function(t) { wx.showLoading(); var a = wx.getStorageSync("token"), e = this; app.util.request({ url: "entry/wxapp/user", data: { controller: { vipcard: "vipcard.get_vipcard_baseinfo", pintuan: "group.pintuan_slides", signin: "signinreward.get_signinreward_baseinfo", solitaire: "solitaire.get_rule" }[t], token: a }, dataType: "json", success: function(a) { if (wx.hideLoading(), 0 == a.data.code) { var i = ""; if ("vipcard" == t) i = a.data.data.vipcard_buy_pagenotice; else if ("pintuan" == t) { i = a.data.pintuan_publish } else if ("signin" == t) { i = a.data.data.signinreward_pagenotice } else if ("solitaire" == t) { i = a.data.solitaire_notice } e.setData({ article: i.replace('< img ', '< img style="max-width:100%;height:auto;display:block;margin:10px 0;"') }) } } }) } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/profile-card/profile-card.js "use strict"; var t = require("../logic/ui.js"), e = null, i = null, n = function(t) { return t < 10 ? "0" + t : String(t) }, a = function(t) { t = Number(t); var e = Math.floor(t / 3600), i = Math.floor((t - 3600 * e) / 60), a = Math.floor(t - 3600 * e - 60 * i); return n(e) + ":" + n(i) + ":" + n(a) }; Component({ properties: { weappImg: { type: String, value: "" }, weappName: { type: String, value: "" }, liveStat: { type: Object, value: { watch_pv: 0 } }, liveStatSimulateWatch: { type: String }, from: { type: String, value: "" }, watchSecond: { type: Number }, isSubscribe: { type: Boolean, value: !1 }, status: { type: String, value: "ready" } }, data: { endBtnDisabled: !0, rightPosition: 0, navigationTitleWidth: "7em" }, observers: { watchSecond: function(t) { e && clearTimeout(e), this.initWatchTime(t) }, status: function(t) { var e = this; t === i && "recording" === t || ("recording" === t ? (i = t, this.setData({ endBtnDisabled: !0 }), setTimeout(function() { e.setData({ endBtnDisabled: !1 }) }, 5e3)) : i = t) } }, lifetimes: { ready: function() { var e = (0, t.getScreenWidth)(); if (e) { var i = "pusher" === this.data.from && "recording" === this.data.status ? e - 260 - 49 - 5 + "px" : e - 260 - 5 + "px"; this.setData({ navigationTitleWidth: i }) } } }, methods: { initWatchTime: function(t) { var i = this, n = a(t); this.setData({ watchTimeStr: n }), e = setTimeout(function() { i.initWatchTime(t + 1) }, 1e3) }, clickProfileModal: function() { this.triggerEvent("customevent", { showProfileModal: !0 }) }, clickSubscribe: function() { this.triggerEvent("customevent", { confirmSubscribe: !0, isSubscribe: this.data.isSubscribe }) }, onClickEndLive: function() { this.data.endBtnDisabled || this.triggerEvent("EndLive", {}) } } });<file_sep>/lionfish_comshop/components/rush-spu-col/index.js var app = getApp(), t = require("../../utils/public"), status = require("../../utils/index.js"), util = require("../../utils/util.js"); Component({ properties: { spuItem: { type: Object, value: { spuId: "", skuId: "", spuImage: "", spuName: "", endTime: 0, beginTime: "", actPrice: ["", ""], marketPrice: ["", ""], spuCanBuyNum: "", soldNum: "", actId: "", limitMemberNum: "", limitOrderNum: "", serverTime: "", isLimit: !1, skuList: [], spuDescribe: "", is_take_fullreduction: 0, label_info: "", car_count: 0 } }, isPast: { type: Boolean, value: !1 }, actEnd: { type: Boolean, value: !1 }, reduction: { type: Object, value: { full_money: "", full_reducemoney: "", is_open_fullreduction: 0 } }, changeCarCount: { type: Boolean, value: !1, observer: function(t) { t && this.setData({ number: this.data.spuItem.car_count }) } }, needAuth: { type: Boolean, value: !1 }, notNum: { type: Boolean, value: !1 }, width250: { type: Boolean, value: !1 }, is_open_vipcard_buy: { type: Number, value: 0 }, canLevelBuy: { type: Boolean, value: !1 } }, attached: function() { this.setData({ placeholdeImg: app.globalData.placeholdeImg }) }, data: { disabled: !1, placeholdeImg: "", number: 0 }, ready: function() { this.setData({ number: this.data.spuItem.car_count || 0 }) }, methods: { openSku: function() { if (this.data.needAuth) this.triggerEvent("authModal"); else { console.log("step1"), this.setData({ stopClick: !0, disabled: !1 }); var t = this.data.spuItem; void 0 === t.skuList.length ? this.triggerEvent("openSku", { actId: t.actId, skuList: t.skuList, promotionDTO: t.promotionDTO, is_take_vipcard: t.is_take_vipcard, is_mb_level_buy: t.is_mb_level_buy, allData: { spuName: t.spuName, skuImage: t.skuImage, actPrice: t.actPrice, canBuyNum: t.spuCanBuyNum, stock: t.spuCanBuyNum, marketPrice: t.marketPrice } }) : this.addCart({ value: 1, type: "plus" }) } }, countDownEnd: function() { this.setData({ actEnd: !0 }) }, submit2: function(e) { (0, t.collectFormIds)(e.detail.formId) }, changeNumber: function(t) { var e = t.detail; e && this.addCart(e) }, outOfMax: function(t) { t.detail; var e = this.data.spuItem.spuCanBuyNum; this.data.number >= e && wx.showToast({ title: "不能购买更多啦", icon: "none" }) }, addCart: function(t) { var e = wx.getStorageSync("token"), a = wx.getStorageSync("community"), u = this.data.spuItem.actId, i = a.communityId, s = this; if ("plus" == t.type) { var o = { goods_id: u, community_id: i, quantity: 1, sku_str: "", buy_type: "dan", pin_id: 0, is_just_addcar: 1 }; util.addCart(o).then(function(t) { if (1 == t.showVipModal) { var e = t.data.pop_vipmember_buyimage; s.triggerEvent("vipModal", { pop_vipmember_buyimage: e, showVipModal: !0, visible: !1 }) } else if (3 == t.data.code) wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }); else if (6 == t.data.code || 7 == t.data.code) { var a = t.data.max_quantity || ""; 0 < a && s.setData({ number: a }); var i = t.data.msg; wx.showToast({ title: i, icon: "none", duration: 2e3 }) } else status.indexListCarCount(u, t.data.cur_count), s.triggerEvent("changeCartNum", t.data.total), s.setData({ number: t.data.cur_count }), wx.showToast({ title: "已加入购物车", image: "../../images/addShopCart.png" }) }) } else app.util.request({ url: "entry/wxapp/user", data: { controller: "car.reduce_car_goods", token: e, goods_id: u, community_id: i, quantity: 1, sku_str: "", buy_type: "dan", pin_id: 0, is_just_addcar: 1 }, dataType: "json", method: "POST", success: function(t) { 3 == t.data.code ? wx.showToast({ title: t.data.msg, icon: "none", duration: 2e3 }) : (status.indexListCarCount(u, t.data.cur_count), s.setData({ number: t.data.cur_count }), s.triggerEvent("changeCartNum", t.data.total)) } }) } } });<file_sep>/lionfish_comshop/moduleB/plugin/wx2b03c6e691cd7370/wxlive-components/logic/config.js "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var _ = { SYSTEM_ERROR: -1, TIMEOUT: -2, NO_CONCENT: -3 }, E = { ROOM_FLAG_NORMAL: 1, ROOM_FLAG_BAN_COMMENT: 2 }, T = { LIVE_STATUS_LIVE: 101, LIVE_STATUS_NOT_START: 102, LIVE_STATUS_END: 103, LIVE_STATUS_FORBID: 104, LIVE_STATUS_PAUSE: 105, LIVE_STATUS_ERROR: 106 }, O = { RTMP: 1, HTTP_FLV: 2, HTTPS_FLV: 3, HTTP_HLS: 4, HTTPS_HLS: 5 }, R = { ROOM_MM_ERR_PEOPLE_LIMIT: 11009, ROOM_MM_ERR_DELETE: 11006, ROOM_MM_ERR_BIZ_INVALID_SCOPE: -12001, ROOM_MM_ERR_ROOMID: 11001, ROOM_MM_ERR_END_LOTTERY: 22007, ROOM_MM_ERR_EXPIRE: -9999901 }, I = { SHOW_LIMIT_NUMBER: 100, SHOW_NEWMSG_LIMIT_NUMBER: 300, SHOW_NEWMSG_NUMBER: 99, FRESH_TIME: 700, SHOW_SECOND_NUMBER: 20, PUSH_COMMENT_HIT_FREQ_LIMIT: 20 }, S = { ERR_COMMENT_PUSH: 13e3, ERR_COMMENT_HIT_KEYWORD_INTERCEPT: 13001, ERR_COMMENT_HIT_FREQ_LIMIT: 13002 }, M = { LOADING: "loading", NORMAL: "normal", ERROR: "error" }, L = { PRICE_TYPE_FIXED_PRICE: 1, PRICE_TYPE_RANGE: 2, PRICE_TYPE_DISCOUNT: 3 }, A = { GOODS_FLAG_NORMAL: 1, GOODS_FLAG_DELETE_BY_USER: 2, GOODS_FLAG_DELETE_BY_AUDIT: 3 }, N = { LOTTERY_NOT_PUSH: 1, LOTTERY_PUSHED: 2, LOTTERY_RUNNING: 3, LOTTERY_FINISHED: 4, LOTTERY_ERROR: 5 }, P = { LOTTERY_COMMENT: 0, LOTTERY_LIKE: 1 }, D = { LOTTERY_OBTAIN_ADDRESS: 0, LOTTERY_OBTAIN: 1 }, U = { SHARE: 1, SUBSCRIBE: 2, PREVIEW: 3, SEARCH: 4, WECHAT_PRO: 7, ADDRESS: 8 }, C = { VIDEO_BITRATE: 101005, AUDIO_BITRATE: 101006, VIDEO_FPS: 101007, NET_SPEED: 101008, NET_JITTER: 101009, HAS_NET_JITTER: 101011, VIDEO_CATON: 101012, SLOW_SPEED: 101013, SETDATA_TIME: 102010, LOTTIE_LIKE_ANIMATION_FPS: 102014, CANVAS_LIKE_ANIMATION_FPS: 102015, WXS_LIKE_ANIMATION_FPS: 102016 }; exports. default = { PLUGIN_APPID: "wx2b03c6e691cd7370", LIVE_ROOM_FLAG: E, LIVE_STATUS_CODE: T, PLAY_URL_TYPE: O, ROOM_ERROR_CODE: R, COUNT_DOWN_TIME: 1e3, LONG_POLLING_TIME: 5e3, REQUEST_DEFAULT_TIMEOUT: 1e4, COMMENT: I, COMMENT_ERROR_CODE: S, STORE_LIST_STATUS: M, GOODS_PRICE_TYPE: L, GOODS_FLAG: A, LOTTERY_STATUS: N, LOTTERY_PARTIPATE_TYPE: P, LOTTERY_OBTAIN_TYPE: D, SCENE_TYPE: U, TEST_SPEED_REPORT_ID: C, OPERATEWXDATA_CODE: _ };<file_sep>/lionfish_comshop/moduleA/special/index.js var app = getApp(), util = require("../../utils/util.js"), status = require("../../utils/index.js"); Page({ mixins: [require("../../mixin/cartMixin.js")], data: { list: [], info: {}, cartNum: 0, needAuth: !1 }, specialId: 0, onLoad: function(e) { var t = e.id || 0; this.specialId = t, "undefined" != e.share_id && 0 < e.share_id && wx.setStorageSync("share_id", e.share_id), this.getData(t) }, authSuccess: function() { this.getData(this.specialId), this.setData({ needAuth: !1 }) }, getData: function(e) { wx.showLoading(); var t = wx.getStorageSync("token"), l = this, i = wx.getStorageSync("community"); app.util.request({ url: "entry/wxapp/index", data: { controller: "marketing.get_special", token: t, head_id: i.communityId, id: e }, dataType: "json", success: function(e) { if (wx.hideLoading(), 0 == e.data.code) { var t = e.data.list, i = e.data.data, a = e.data.ishow_special_share_btn || 0; wx.setNavigationBarTitle({ title: i.special_title || "专题" }); var n = e.data, s = n.full_money, o = n.full_reducemoney, c = n.is_open_fullreduction, d = (n.is_open_vipcard_buy, n.is_vip_card_member, n.is_member_level_buy, { full_money: s, full_reducemoney: o, is_open_fullreduction: c }), u = 0 == t.length; l.setData({ list: t, info: i, ishowShareBtn: a, noData: u, reduction: d }) } else 1 == e.data.code ? wx.showModal({ title: "提示", content: e.data.msg, showCancel: !1, success: function(e) { e.confirm && wx.switchTab({ url: "/lionfish_comshop/pages/index/index" }) } }) : 2 == e.data.code && l.setData({ needAuth: !0 }) } }) }, onShow: function() { var i = this, a = this; util.check_login_new().then(function(e) { if (e) i.setData({ needAuth: !1 }), (0, status.cartNum)("", !0).then(function(e) { 0 == e.code && a.setData({ cartNum: e.data }) }); else { var t = i.specialId; i.setData({ needAuth: !0, navBackUrl: "/lionfish_comshop/pages/supply/index?id=" + t }) } }) }, onPullDownRefresh: function() {}, onShareAppMessage: function(e) { var t = this.data.info.special_title || "活动专题", i = wx.getStorageSync("member_id"); return { title: t, path: "lionfish_comshop/moduleA/special/index?id=" + this.specialId + "&share_id=" + i, success: function(e) {}, fail: function(e) {} } }, onShareTimeline: function (e) { var t = this.data.info.special_title || "活动专题", i = wx.getStorageSync("member_id"); return { title: t, query: "id=" + this.specialId + "&share_id=" + i, success: function (e) { }, fail: function (e) { } } } });<file_sep>/lionfish_comshop/components/orderInfo/index.js Component({ properties: { orderInfo: { type: Object, observer: function(t) { var o = 1 * t.real_total, e = (t.total, parseFloat(o) - parseFloat(t.shipping_fare)), a = parseFloat(t.voucher_credit) + parseFloat(t.fullreduction_money); a = e < a ? e : a, this.setData({ goodsTotal: e.toFixed(2), disAmount: a.toFixed(2) }) } }, order_goods_list: { type: Array, observer: function(t) { var a = 0; t && t.length && t.forEach(function(t) { var o = 1 * t.total, e = 1 * t.old_total; 1 != t.is_level_buy && 1 != t.is_vipcard_buy || (a += e - o) }), this.setData({ levelAmount: a.toFixed(2) }) } }, ordername: { type: String, value: "订单" } }, data: { disAmount: 0, goodsTotal: 0 } });<file_sep>/lionfish_comshop/components/parser/libs/config.js function makeMap(e) { for (var t = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}, a = e.split(","), s = a.length; s--;) t[a[s]] = !0; return t } var trustAttrs = makeMap("align,alt,app-id,appId,author,autoplay,border,cellpadding,cellspacing,class,color,colspan,controls,data-src,dir,face,height,href,id,ignore,loop,muted,name,path,poster,rowspan,size,span,src,start,style,type,unit-id,unitId,width,xmlns"), trustTags = makeMap("a,abbr,ad,audio,b,blockquote,br,code,col,colgroup,dd,del,dl,dt,div,em,fieldset,h1,h2,h3,h4,h5,h6,hr,i,img,ins,label,legend,li,ol,p,q,source,span,strong,sub,sup,table,tbody,td,tfoot,th,thead,tr,title,ul,video"), blockTags = makeMap("address,article,aside,body,center,cite,footer,header,html,nav,pre,section"), ignoreTags = makeMap("area,base,basefont,canvas,circle,command,ellipse,embed,frame,head,iframe,input,isindex,keygen,line,link,map,meta,param,path,polygon,rect,script,source,svg,textarea,track,use,wbr"), richOnlyTags = makeMap("a,colgroup,fieldset,legend,sub,sup,table,tbody,td,tfoot,th,thead,tr"), selfClosingTags = makeMap("area,base,basefont,br,col,circle,ellipse,embed,frame,hr,img,input,isindex,keygen,line,link,meta,param,path,polygon,rect,source,track,use,wbr"), blankChar = makeMap(" , ,\t,\r,\n,\f"), userAgentStyles = { a: "color:#366092;word-break:break-all;padding:1.5px 0 1.5px 0", address: "font-style:italic", blockquote: "background-color:#f6f6f6;border-left:3px solid #dbdbdb;color:#6c6c6c;padding:5px 0 5px 10px", center: "text-align:center", cite: "font-style:italic", dd: "margin-left:40px", img: "max-width:100%", mark: "background-color:yellow", pre: "font-family:monospace;white-space:pre;overflow:scroll", s: "text-decoration:line-through", u: "text-decoration:underline" }, screenWidth = wx.getSystemInfoSync().screenWidth; function bubbling(e) { for (var t = e._STACK.length; t--;) { if (richOnlyTags[e._STACK[t].name]) return !1; e._STACK[t].c = 1 } return !0 } wx.canIUse("editor") ? (makeMap("bdi,bdo,caption,rt,ruby,big,small,pre", trustTags), makeMap("bdi,bdo,caption,rt,ruby,pre", richOnlyTags), ignoreTags.rp = !0, blockTags.pre = void 0) : (blockTags.caption = !0, userAgentStyles.big = "display:inline;font-size:1.2em", userAgentStyles.small = "display:inline;font-size:0.8em"), module.exports = { highlight: null, LabelHandler: function(e, t) { var a = e.attrs; switch (a.style = t.CssHandler.match(e.name, a, e) + (a.style || ""), e.name) { case "div": case "p": a.align && (a.style = "text-align:" + a.align + ";" + a.style, a.align = void 0); break; case "img": a["data-src"] && (a.src = a.src || a["data-src"], a["data-src"] = void 0), a.width && parseInt(a.width) > screenWidth && (a.style += ";height:auto !important"), a.src && !a.ignore && (bubbling(t) ? a.i = (t._imgNum++).toString() : a.ignore = "T"); break; case "a": case "ad": bubbling(t); break; case "font": if (a.color && (a.style = "color:" + a.color + ";" + a.style, a.color = void 0), a.face && (a.style = "font-family:" + a.face + ";" + a.style, a.face = void 0), a.size) { var s = parseInt(a.size); s < 1 ? s = 1 : 7 < s && (s = 7); a.style = "font-size:" + ["xx-small", "x-small", "small", "medium", "large", "x-large", "xx-large"][s - 1] + ";" + a.style, a.size = void 0 } break; case "video": case "audio": a.id ? t["_" + e.name + "Num"]++ : a.id = e.name + ++t["_" + e.name + "Num"], "video" == e.name && (a.width && (a.style = "width:" + parseFloat(a.width) + (a.width.includes("%") ? "%" : "px") + ";" + a.style, a.width = void 0), a.height && (a.style = "height:" + parseFloat(a.height) + (a.height.includes("%") ? "%" : "px") + ";" + a.style, a.height = void 0), 3 < t._videoNum && (e.lazyLoad = !0)), a.source = [], a.src && a.source.push(a.src), a.controls || a.autoplay || console.warn("存在没有 controls 属性的 " + e.name + " 标签,可能导致无法播放", e), bubbling(t); break; case "source": var r = t._STACK[t._STACK.length - 1]; !r || "video" != r.name && "audio" != r.name || (r.attrs.source.push(a.src), r.attrs.src || (r.attrs.src = a.src)) } var i = a.style.toLowerCase().split(";"), l = {}; a.style = ""; for (var n = 0, o = i.length; n < o; n++) { var c = i[n].split(":"); if (2 == c.length) { var d = c[0].trim(), g = c[1].trim(); if (g.includes("url")) { var u = g.indexOf("("); if (-1 != u++) { for (; '"' == g[u] || "'" == g[u] || blankChar[g[u]];) u++; "/" == g[u] && ("/" == g[u + 1] ? g = g.substring(0, u) + t._protocol + ":" + g.substring(u) : t._domain && (g = g.substring(0, u) + t._domain + g.substring(u))) } } else g.includes("rpx") && (g = g.replace(/[0-9.]*rpx/g, function(e) { return parseFloat(e) * screenWidth / 750 + "px" })); g.includes("-webkit") || g.includes("-moz") || g.includes("-ms") || g.includes("-o") || g.includes("safe") ? a.style += ";" + d + ":" + g : l[d] && !g.includes("import") && l[d].includes("import") || (l[d] = g) } } for (var d in "img" == e.name && l.width && l.width.includes("%") && parseInt(l.width) > screenWidth && (l.height = "auto !important"), l) a.style += ";" + d + ":" + l[d]; a.style = a.style.substr(1), a.style || (a.style = void 0), t._useAnchor && a.id && bubbling(t) }, trustAttrs: trustAttrs, trustTags: trustTags, blockTags: blockTags, ignoreTags: ignoreTags, selfClosingTags: selfClosingTags, blankChar: blankChar, userAgentStyles: userAgentStyles, screenWidth: screenWidth };
e3080c4e840e8e8b153fea64f29fdbce076532f9
[ "JavaScript" ]
75
JavaScript
18722480995/naizhan
fcdf31248d3b4ebca20eb6b60db0f65ef3fa4ddb
406e83f81dafc646b75a591d6bd13d647c8be6a7
refs/heads/master
<repo_name>AntonyAndrei/Estrutura.De.Dados<file_sep>/src/pilhas/Pilha.java package pilhas; public class Pilha<T> { private T[] vetor; private T[] vetor2; private int qntElementos = 0; private int tamanhoTotalVetor = 0; @SuppressWarnings("unchecked") public Pilha(int tam) { vetor = (T[]) new Object[tam]; this.tamanhoTotalVetor = tam; } public boolean existeDado() { return (vetor[this.qntElementos] != null); } public boolean verificaDado(int pos) { return vetor[pos] != null; } public T Recuperar(int pos) { if ((pos < 0 && pos > Tamanho()) || (!verificaDado(pos))) { throw new ArrayIndexOutOfBoundsException("Posição Inválida"); } return vetor[pos]; } public T Top() { return vetor[vetor.length]; } public boolean vazio() { return Tamanho() == 0; } //Adiciona na Pilha public void Push(T elemento) { if (Tamanho() == vetor.length) { redimensionar(); } Iterador <T> it = new Iterador<>(vetor); int i=0; while (it.hasNext()){ if (it.next() == null) { vetor[i] = elemento; qntElementos++; break; } i++; } } public void listarDados() { if (vazio()) { System.out.println("Pilha Vazia! Não ha nada pra Mostrar!"); } else { Iterador<T> it = new Iterador<>(vetor); int i = 0; System.out.print("["); while (it.hasNext()) { if (it.next() != null) { System.out.print(Recuperar(i)); i++; if (i < qntElementos) { System.out.print(", "); } } } System.out.println("] = " + this.qntElementos + "\n"); } } //Remove do topo da pilha public void Pop() { if (this.qntElementos == 0) { System.out.println("A Pilha já está vazio! \n"); } else { this.qntElementos--; vetor[qntElementos] = null; } } public int Tamanho() { return qntElementos; } public void Limpar() { if (this.qntElementos == 0) { System.out.println("O Vetor já está Limpo! \n"); } else { Iterador<T> it = new Iterador<>(vetor); int i = 0; while (it.hasNext() && this.qntElementos - 1 > i) { if (it.next() != null) { vetor[i] = null; i++; } } this.qntElementos = 0; } } public int getQntElementos() { return qntElementos; } public void redimensionar(){ vetor2 = (T[]) new Object[this.vetor.length * 2]; Iterador<T> it = new Iterador<>(vetor2); int i = 0; while (it.hasNext() && i < this.tamanhoTotalVetor) { if (it.next() == null) { vetor2[i] = vetor[i]; i++; } } vetor = vetor2; } }<file_sep>/src/filas/Fila.java package filas; public class Fila<T> { private Celula inicio, fim; private int tamanho; public Fila() { this.inicio = null; this.fim = null; this.tamanho = 0; } public boolean existeDado (T elemento) { return elemento == this.inicio.getElemento(); } public void enfileirar(T elemento) { if (tamanho == 0) { Celula nova = new Celula(elemento); if (this.tamanho == 0) { inicio = fim = nova; this.tamanho += 1; } else { nova.setProximo(inicio); inicio = nova; this.tamanho += 1; } } else { Celula nova = new Celula(elemento); this.fim.setProximo(nova); this.fim = nova; this.tamanho++; } } public boolean isEmpty() { return this.tamanho == 0; } public T Recupera() { Celula primeira = this.inicio; return (T) primeira.getElemento(); } public T RecuperaCelula() { Celula primeira = this.inicio; return (T) primeira; } public void alterar (T elemento) { Celula alterar = new Celula(elemento); Celula proxima = new Celula(inicio.getProximo()); this.inicio = alterar; this.inicio.setProximo(proxima); } public void atender() { if (this.tamanho == 0) { System.out.println("A lista está vazia!"); } else if (inicio == fim) { inicio = fim = null; this.tamanho -= 1; } else { inicio = inicio.getProximo(); this.tamanho -= 1; } } public int tamanho() { return this.tamanho; } public void limpar () { this.inicio = null; this.fim = null; this.tamanho = 0; } @Override public String toString() { if (tamanho == 0) { return "[]"; } StringBuilder builder = new StringBuilder("• "); Celula atual = inicio; for (int i = 0; i < tamanho - 1; i++) { builder.append(atual.getElemento()); builder.append(" <- "); atual = atual.getProximo(); } builder.append(atual.getElemento()); builder.append(" - " + tamanho); return builder.toString(); } } <file_sep>/src/pilhas/Application.java package pilhas; public class Application { public static void main(String[] args) { /*Instanciando a classe genérica Vetor e nesse momento informando que ela é do tipo Aluno*/ Pilha<Aluno> pilhaAlunos = new Pilha<Aluno>(4); //Instanciando um aluno Aluno a = new Aluno("ANA", 30); Aluno a2 = new Aluno("MARIA", 35); Aluno a3 = new Aluno("ANTONY", 21); Aluno a4 = new Aluno("JAALA", 21); Aluno a5 = new Aluno("FULANO", 21); Aluno a6 = new Aluno("CICLANO", 25); //Adicionando o aluno no vetor pilhaAlunos.Push(a); pilhaAlunos.Push(a2); pilhaAlunos.Push(a3); pilhaAlunos.Push(a4); pilhaAlunos.listarDados(); pilhaAlunos.Pop(); pilhaAlunos.listarDados(); pilhaAlunos.Limpar(); pilhaAlunos.listarDados(); } } <file_sep>/src/revisaoProva1/Application.java package revisaoProva1; public class Application { public static void main(String[] args) { Onibus a1 = new Onibus("Atalaia", 99); Onibus a2 = new Onibus("Bugio", 500); Onibus a3 = new Onibus("SaoJose", 706); Onibus a4 = new Onibus("CasteloBranco", 707); Onibus a5 = new Onibus("AugustoFranco", 30); ListaOnibus<Onibus> lista = new ListaOnibus<Onibus>(); lista.adicionaInicio(a1); lista.adicionaInicio(a2); lista.adicionaInicio(a3); lista.adicionaInicio(a4); lista.adicionaInicio(a5); lista.adicionaInicio(a3); System.out.println("Imprimir Intinerario: "); System.out.println(lista); System.out.println(); System.out.println("Remover Ultimo Onibus: "); lista.removeFim(); System.out.println(lista); System.out.println(); } }
c61ae4e5bfb2722ea7f04483a3a02eef08ac97a9
[ "Java" ]
4
Java
AntonyAndrei/Estrutura.De.Dados
29907bda9d74216c7c1850d39a884787060f4192
1cdde245d52b4a8e3fdcba0311ab0f39bd7d815c
refs/heads/main
<repo_name>MDHUtbilding/DVA_231<file_sep>/Lab2/PHP/readnews.php <?php // this PHP script is to be used for displaying news in the grid boxes $news = json_decode(file_get_contents('../JSON/news.json'), true); echo json_encode($news); ?><file_sep>/Lab2/PHP/form1.php <?php session_start(); // Initialize the session ?> <!DOCTYPE html> <html> <body> <form method="POST" action="form2.php"> <pre> Name: <input type="text" name="user_name"> </pre> <pre> Email Address: <input type="text" name="user_email_address"> </pre> <input type="submit" value="Next"> </form> </body> </html> <file_sep>/Lab2/PHP/admin.php <?php session_start(); // Initialize the session // Store the submitted data sent via POST method, stored // Temporarily in $_POST structure. $_SESSION['name'] = $_POST['user_name']; $_SESSION['email_address'] = $_POST['user_email_address']; ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="../CSS/admin.css"> <title>Admin</title> </head> <nav> <div class="homepage"> <ul> <li><a href="../HTML/index.html">Home Page</a></li> </ul> </div> </nav> <body> <div class="container"> <div class="item"> <h1>Welcome Admin</h1> <?php echo "Name is " . $_SESSION["name"] . ".<br>"; echo "Email is " . $_SESSION["email_address"] . "."; ?> </div> <div class="content"> <form> <label for="txtfile">Enter your textfile here: </label><br><br><br> <input type="file" id="newsfile" name="newsfile"><br><br> <input type="submit" id="Apply" name="submitbtn"> </form> </div> </div> <!-- Form for other details--> <form method="POST" action="../PHP/form3.php"> <input type="submit" value="Destroy session."> </form> </body> </html><file_sep>/Lab2/PHP/SignIn.php <?php session_start(); // Initialize the session ?> <!DOCTYPE html> <html> <head> <title>Sign In</title> <link rel="stylesheet" type="text/css" href="../CSS/signin.css"> </head> <body> <form method="POST" action="admin.php"> <pre> Name: <input type="text" name="user_name"> </pre> <pre> Email Address: <input type="text" name="user_email_address"> </pre> <input type="submit" value="Next"> </form> </body> </html><file_sep>/Lab2/PHP/readJSON.php <?php $people_json = file_get_contents('file.json'); $decoded_json = json_decode($people_json, true); $customers = $decoded_json['customers']; foreach($customers as $customer) { $name = $customer['name']; $countries = $customer['countries']; foreach($countries as $country) { echo $name.' visited '.$country['name'].' in '.$country['year'].'.'; } } ?><file_sep>/Lab2/PHP/form2.php <?php session_start(); // Initialize the session // Store the submitted data sent via POST method, stored // Temporarily in $_POST structure. $_SESSION['name'] = $_POST['user_name']; $_SESSION['email_address'] = $_POST['user_email_address']; ?> <!DOCTYPE html> <html> <body> <?php echo "Name is " . $_SESSION["name"] . ".<br>"; echo "Email is " . $_SESSION["email_address"] . "."; ?> <!-- Form for other details--> <form method="POST" action="form3.php"> <input type="submit" value="Destroy session."> </form> </body> </html> <file_sep>/Lab2/index.php <?php $json = file_get_contents("../JSON/news.json"); echo $json; ?> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="../CSS/gridNavigation.css"> <link rel="stylesheet" type="text/css" href="../CSS/gridImage.css"> <link rel="stylesheet" type="text/css" href="../CSS/bottomMenu.css"> <link rel="stylesheet" type="text/css" href="../CSS/topMenu.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div class="gridNavigation"> <div class="nasaLogo"><img src="../Img/nasa-logo.svg"></div> <div id="topcontainer"> <div id="topMenu"> <div class="dropdown"> <button class="dropbtn">Missions</button> <div class="dropdown-content"> <a href="#">Commercial Crew</a> <a href="#">International Spacestation</a> <a href="#">Parker Solar Probe</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Galleries</button> <div class="dropdown-content"> <a href="#">Image of the day</a> <a href="#">Ultra high-def Videos</a> <a href="#">Images</a> <a href="#">Videos</a> </div> </div> <div class="dropdown"> <button class="dropbtn">NASA TV</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Follow NASA</button> <div class="dropdown-content"> <a href="#">Get involved</a> <a href="#">NASA Live</a> <a href="#">Social media</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Downloads</button> <div class="dropdown-content"> <a href="#">Apps</a> <a href="#">Podcasts</a> <a href="#">Third rock radio</a> </div> </div> <div class="dropdown"> <button class="dropbtn">About</button> <div class="dropdown-content"> <a href="#">About NASA</a> <a href="#">Leadership</a> <a href="#">People of NASA</a> </div> </div> <div class="dropdown"> <button class="dropbtn">NASA Audiences </button> <div class="dropdown-content"> <a href="#">For Media</a> <a href="#">For Educators</a> <a href="#">For students</a> </div> </div> <div class="endpic"><img src="../Img/share.png"></div> <div class="search-container"> <form action="/action_page.php"> <input type="text" placeholder="Search.." name="search"> <button type="submit"><i class="fa fa-search"></i></button> </form> </div> </div> <div class="bottomMenu"> <div class="bottomMenuBar"> <ul> <li><a href="">International Space Station</a></li> <li><a href="">Journey to Mars</a></li> <li><a href="">Earth</a></li> <li><a href="">Technology</a></li> <li><a href="">Aeronautics</a></li> <li><a href="">Solar System and Beyond</a></li> <li><a href="">Education</a></li> <li><a href="">History</a></li> <li><a href="">Benefits to You</a></li> </ul> </div> </div> </div> <div class="admin"> <div class="adminlink"> <ul> <li><a href="../HTML/SignIn.php">Admin Page</a></li> </ul> </div> </div> </div> <div class="gridImage"> <div class="image1"> <img class="carouselImg" src="../Img/pic1.JPG"> <img class="carouselImg" src="../Img/pic2.JPG"> <img class="carouselImg" src="../Img/pic3.JPG"> </div> <script> var myIndex = 0; carousel(); function carousel() { var i; var x = document.getElementsByClassName("carouselImg"); for (i = 0; i < x.length; i++) x[i].style.display = "none"; myIndex++; if (myIndex > x.length) myIndex = 1 x[myIndex-1].style.display = "block"; setTimeout(carousel, 30000); // Change image every 30 seconds } </script> <div class="image2"> <div class="textWrap"> <div id="moreText"> <div id="img"> </div> </div> </div> </div> <script> fetch('../JSON/news1.json') .then(function (response) { return response.json(); }) .then(function (data) { appendData(data); }) .catch(function (err) { console.log('error: ' + err); }); function appendData(data) { var mainContainer = document.getElementById("moreText"); for (var i = 0; i < data.length; i++) { var div = document.createElement("div"); div.innerHTML = 'Content: ' + data[i].content; mainContainer.appendChild(div); } } </script> <div class="image3"> <div class="textWrap"> <div class="moreText"> Drowsy drivers are a cause of car crashes. You would think self-driving cars would fix that since computers don't go sleepy. Cars with partially automated systems today, can still require a driver to take over at a moment notice. But studies has shown that drivers get more sleepy from automatic systems. The study was carried out to understand how humans interact with automatic systems and to help make automatic systems better for cars, aviation and space rockets. </div> </div> </div> <div class="image4"> <img id="image4attr" src="../Img/Venus.jpg"> </div> <div class="image5"> <div class="textWrap"> <div class="moreText"> NASA began flight testing with Joby Aviation's all-electric vertical takeoff and landing aircraft (eVTOL) as a part of the agency's Advanced Air Mobility National Campaign. This is the first time NASA will test an eVTOL aircraft as part of the campaign. In the future, eVTOL aircraft could serve as airtaxis. </div> </div> </div> <div class="image6"> <div class="textWrap"> <div class="moreText"> Recovery and assessments continue at NASA's Michoud Assembly Facility in New Orleans following hurricane Ida. The powerful category 4 hurricane made landfall in Louisiana Aug. 29, on the 16th anniversary of hurricane Katrina. The Michoud Safety and Security team completed an initial assessment of the 829-acre facility and its 81 buildings and structures on Aug 31. Winds from the storm caused damage to several buildings as well as to the roof deck panels and lightning protection systems. Many of the roofing systems did sustain significant damage and caused water intrusion into some buildings. </div> </div> </div> <div class="image7"> <iframe width="350" height="290" src="https://www.youtube.com/embed/FUq5d7dqlVY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> <div id="myData"></div> </div> </body> </html> <!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="../CSS/gridNavigation.css"> <link rel="stylesheet" type="text/css" href="../CSS/gridImage.css"> <link rel="stylesheet" type="text/css" href="../CSS/bottomMenu.css"> <link rel="stylesheet" type="text/css" href="../CSS/topMenu.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> </head> <body> <div class="gridNavigation"> <div class="nasaLogo"><img src="../Img/nasa-logo.svg"></div> <div id="topcontainer"> <div id="topMenu"> <div class="dropdown"> <button class="dropbtn">Missions</button> <div class="dropdown-content"> <a href="#">Commercial Crew</a> <a href="#">International Spacestation</a> <a href="#">Parker Solar Probe</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Galleries</button> <div class="dropdown-content"> <a href="#">Image of the day</a> <a href="#">Ultra high-def Videos</a> <a href="#">Images</a> <a href="#">Videos</a> </div> </div> <div class="dropdown"> <button class="dropbtn">NASA TV</button> <div class="dropdown-content"> <a href="#">Link 1</a> <a href="#">Link 2</a> <a href="#">Link 3</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Follow NASA</button> <div class="dropdown-content"> <a href="#">Get involved</a> <a href="#">NASA Live</a> <a href="#">Social media</a> </div> </div> <div class="dropdown"> <button class="dropbtn">Downloads</button> <div class="dropdown-content"> <a href="#">Apps</a> <a href="#">Podcasts</a> <a href="#">Third rock radio</a> </div> </div> <div class="dropdown"> <button class="dropbtn">About</button> <div class="dropdown-content"> <a href="#">About NASA</a> <a href="#">Leadership</a> <a href="#">People of NASA</a> </div> </div> <div class="dropdown"> <button class="dropbtn">NASA Audiences </button> <div class="dropdown-content"> <a href="#">For Media</a> <a href="#">For Educators</a> <a href="#">For students</a> </div> </div> <div class="endpic"><img src="../Img/share.png"></div> <div class="search-container"> <form action="/action_page.php"> <input type="text" placeholder="Search.." name="search"> <button type="submit"><i class="fa fa-search"></i></button> </form> </div> </div> <div class="bottomMenu"> <div class="bottomMenuBar"> <ul> <li><a href="">International Space Station</a></li> <li><a href="">Journey to Mars</a></li> <li><a href="">Earth</a></li> <li><a href="">Technology</a></li> <li><a href="">Aeronautics</a></li> <li><a href="">Solar System and Beyond</a></li> <li><a href="">Education</a></li> <li><a href="">History</a></li> <li><a href="">Benefits to You</a></li> </ul> </div> </div> </div> <div class="admin"> <div class="adminlink"> <ul> <li><a href="../HTML/admin.html">Admin Page</a></li> </ul> </div> </div> </div> <div class="gridImage"> <div class="image1"> <img class="carouselImg" src="../Img/pic1.JPG"> <img class="carouselImg" src="../Img/pic2.JPG"> <img class="carouselImg" src="../Img/pic3.JPG"> <p class="text-topnews"></p> </div> <div class="image2"> <div class="textWrap"> <!-- <div class="moreText">--> NASA Eart Science Divison has many online tools to help understand and track climate change. Sea Level Projection Tool allows the user to visualize and project the global sea levels. Sea Level and Evaluation Assessment Tool provides data for assesing sea level and its causes. Earth Observatory: Fires tool is a collection of current wildfires and natural disasters. <!--</div> --> </div> </div> <div class="image3"> <div class="textWrap"> <div class="moreText"> Drowsy drivers are a cause of car crashes. You would think self-driving cars would fix that since computers don't go sleepy. Cars with partially automated systems today, can still require a driver to take over at a moment notice. But studies has shown that drivers get more sleepy from automatic systems. The study was carried out to understand how humans interact with automatic systems and to help make automatic systems better for cars, aviation and space rockets. </div> </div> </div> <div class="image4"> <img id="image4attr" src="../Img/Venus.jpg"> </div> <div class="image5"> <div class="textWrap"> <div class="moreText"> NASA began flight testing with Joby Aviation's all-electric vertical takeoff and landing aircraft (eVTOL) as a part of the agency's Advanced Air Mobility National Campaign. This is the first time NASA will test an eVTOL aircraft as part of the campaign. In the future, eVTOL aircraft could serve as airtaxis. </div> </div> </div> <div class="image6"> <div class="textWrap"> <div class="moreText"> Recovery and assessments continue at NASA's Michoud Assembly Facility in New Orleans following hurricane Ida. The powerful category 4 hurricane made landfall in Louisiana Aug. 29, on the 16th anniversary of hurricane Katrina. The Michoud Safety and Security team completed an initial assessment of the 829-acre facility and its 81 buildings and structures on Aug 31. Winds from the storm caused damage to several buildings as well as to the roof deck panels and lightning protection systems. Many of the roofing systems did sustain significant damage and caused water intrusion into some buildings. </div> </div> </div> <div class="image7"> <iframe width="350" height="290" src="https://www.youtube.com/embed/FUq5d7dqlVY" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </div> </div> </body> </html>
dabb0b5725fe23bdc1161a1150070c5c35aaeac7
[ "PHP" ]
7
PHP
MDHUtbilding/DVA_231
f2ea6b0f1e4128b8c70f30167954deb1f80d035f
7164cd69f7a117b22c36a096503632a740cb1070
refs/heads/master
<file_sep>from gender import Gender class Person: def __init__(self, first_name, last_name, title, gender: Gender): self.__gender = gender self.__title = title self.__last_name = last_name self.__first_name = first_name self.__fired = False gender: Gender @property def first_name(self): return self.__first_name @property def last_name(self): return self.__last_name @property def title(self): return self.__title @property def gender(self): return self.__gender @property def fired(self): return self.__fired def tostring(self): return self.__title + " " + self.first_name + " " + self.__last_name + " " + str(self.__gender) def fire(self): self.__fired = True print("fired") def sex_change(self, new_gender: Gender, new_first_name, new_title=""): self.__gender = new_gender self.__first_name = new_first_name if len(new_title) == 0: if new_gender == Gender.Male: self.__title = "Mr" else: self.__title = "Ms" else: self.__title = new_title <file_sep>from department import Department from gender import Gender from person import Person p = Person("David", "Harrington", "Mr", Gender.Male) p.department = Department("Sales", Person("Bill", "Smith", "Mr", Gender.Male)) print("Person: " + p.tostring() + ". Works in " + str(p.department.name)) print("Manager is " + p.department.manager.first_name + " " + p.department.manager.last_name) print("Fired: " + str(p.fired)) p.fire() print("Fired: " + str(p.fired)) p.sex_change(Gender.Female, "Doris", "Mrs") print(p.tostring()) <file_sep>from person import Person class Department: def __init__(self, name, manager: Person): self.__name__ = name self.__manager__ = manager @property def name(self): return self.__name__ @property def manager(self): return self.__manager__ <file_sep>import enum class Gender(enum.Enum): Male = 0 Female = 1 Unknown = 2
ce95e823b8e60b307f82dbf1f2c4c788654fa7be
[ "Python" ]
4
Python
daveyboy103/python
b05bf0cf8a43e39c72c868f3add5b79c927ed485
d7ccc8c537a0c7c430f59be8393044ef0692e46e
refs/heads/master
<file_sep>import React from 'react'; const Rect = React.memo((props) => { const {x,y,active,bSize} = props; return <rect x={x} y={y} width={bSize} height={bSize} fill={active?'red':'black'}/>; }); export default Rect;<file_sep>import React from 'react'; import Cell from './Cell'; function Grid(props){ const {grid: {cells, size, cellSize}, view, dispatch} = props; const offsetCenter = [size[0] * cellSize / 2, size[1] * cellSize / 2]; const v = view.split(' ').map((v) => parseFloat(v)); const cellCache = cellSize * 2; return cells.map((c,i) => { const px = c.x * cellSize - offsetCenter[0]; const py = c.y * cellSize - offsetCenter[1]; const showCellX = ((px > v[0] - cellCache || (px + cellSize) > v[0] - cellCache) && (px < (v[0] + v[2] + cellCache) || (px + cellSize) < (v[0] + v[2] + cellCache) )); const showCellY = ((py > v[1] - cellCache || (py + cellSize) > v[1] - cellCache) && (py < (v[1] + v[3] + cellCache) || (py + cellSize) < (v[1] + v[3] + cellCache) )); const showCell = showCellX && showCellY; return showCell ? <Cell key={i} x={c.x} y={c.y} px={px} py={py} color={c.color ? `#${c.color}` : null} size={cellSize} offsetCenter={offsetCenter} dispatch={dispatch}/> : null }) }; export default Grid;<file_sep>import React, {useRef} from 'react'; import Grid from './Grid'; function Board(props){ const {dispatch} = props; return <svg viewBox={props.view}> <g transform={`rotate(${props.angle})`}> <Grid {...props} dispatch={dispatch}/> </g> </svg>; }; export default Board;<file_sep>import React, {useReducer} from 'react'; import Container from './Container'; import Board from './Board'; const initialState = { appName: 'PixelArt', action: 'NONE', selectedColor: '550055', grid: { size: [32,32], cellSize: 50, cells: generateGrid([32,32])} } function generateGrid(size){ let grid = []; for(let i = 0; i < size[0]; i++){ for(let j = 0; j < size[1]; j++){ grid[i+j*size[0]] = {x:i,y:j}; } } return grid; } function reducer(state,action){ switch (action.type) { case 'test': return {...state,appName:'test'} case 'setCell': return {...state,grid:{...state.grid,cells: state.grid.cells.map(c => (c.x == action.x && c.y == action.y) ? {...c,color:state.selectedColor} : c)}} case 'setAction': return {...state,action: action.action} default: return state; } } function App(){ const [state, dispatch] = useReducer(reducer, initialState); return <Container {...state} dispatch={dispatch}/>; } export default App;<file_sep>import React from 'react'; const Cell = React.memo((props) => { const {x,y, px,py,size,color,offsetCenter,dispatch} = props; function click(){ dispatch( {type: 'setCell', x: x, y: y} ) } return <g> <rect x={px} y={py} width={size} height={size} fill={color ? color : 'white'} stroke="black" onClick = {click}/> {/* <text x={px + 5} y={py+25}>{`(${px},${py})`}</text> */} </g>; }, (prev, next) => { return prev.px == next.px && prev.py == next.py && prev.color == next.color }); export default Cell;<file_sep>export const icons = { color: 'data:image/svg+xml;base64,<KEY> edit: 'data:image/svg+xml;base64,<KEY> pan: 'data:image/svg+xml;base64,<KEY> }<file_sep>import React,{useState} from 'react'; function toHex(rgb) { const hex = rgb.toString(16); return hex.length < 2 ? "0" + hex : hex; }; function PrimaryColor(props){ const {cx,cy,type,chroma} = props; const hexChroma = toHex(chroma); const fill = type == 'R' ? `#${hexChroma}0000` : type == 'G' ? `#00${hexChroma}00` : `#0000${hexChroma}`; return <g> <rect x={cx} y={cy} height="80px" width="20px" fill={fill} stroke="black"/> <text x={cx} y={cy} fill={'white'}>{type}</text> </g> } export default PrimaryColor;<file_sep># pixelart Draw pixel art from your mobile <file_sep>import React, {Suspense} from 'react'; import ReactDom from 'react-dom'; import Intro from './components/Intro'; const App = React.lazy(() => { return new Promise(resolve => setTimeout(resolve, 1)).then( () => import("./components/App") ); }); ReactDom.render( <Suspense fallback={<Intro/>}> <App/> </Suspense> ,document.getElementById('app'));<file_sep>import React from 'react'; import Spinner from './Spinner'; function Intro(){ const stlDiv = { display: 'grid', width: '100%', height: '100vh', textAlign:'center', backgroundColor: 'lightgray', opacity: '0.7' } const stlSvg = { margin:'auto', transform: 'scale(3)' } const bSize = 20; const mark = bSize * 2 + bSize/10 return <div style={stlDiv}> <svg style={stlSvg} height={mark} width={mark}> <Spinner bSize={bSize}/> </svg> </div>; } export default Intro;<file_sep>import React, {useState, useEffect, useRef} from 'react'; import Rect from './Rect'; function Spinner(props){ const [step, setStep] = useState(0); const countStep = useRef(step); countStep.current = step; let timer = null; useEffect(() => { timer = setInterval(() => setStep(countStep.current == 3 ? 0 : countStep.current + 1),250); return () => clearInterval(timer) },[]); const {bSize} = props; const pos = bSize + bSize/10; const rects = [[0,0],[pos,0],[pos,pos],[0,pos]] return ( <g> {rects.map((b,i) => <Rect key={i} x={b[0]} y={b[1]} active={step == i} bSize={bSize}/>)} </g>); } export default Spinner;<file_sep>import React, {useState,useEffect} from 'react'; function useSize (){ const [size,setSize] = useState(getSize()); useEffect(() => { document.body.onresize = function(e){ setSize(getSize()) } },[]); function getSize(){ return {w:window.innerWidth, h:window.innerHeight}; } return size; } export default useSize;<file_sep>import React,{useState} from 'react'; function Button(props){ const [touch, setTouch] = useState(false); const {name,px,py,icon,dispatch} = props; function start(e){ setTouch(true); dispatch( {type: 'setAction', action: name} ) } function end(e){ setTouch(false); dispatch( {type: 'setAction', action: 'NONE'} ) } const w=60; const h=60; return ( <svg x={px} y={py} width={w} height={h} onClick= {(e) => touch ? end(e) : start(e)} // onTouchStart={start} // onTouchEnd={end} > <g> <circle cx={w/2} cy={w/2} r={w/2 -2} stroke="black" opacity=".8" strokeWidth="3" fill={touch ? 'lightgreen' : 'gray'}/> <image xlinkHref={icon} x={w/2} y={h/2} height={w} width={h} transform={'scale(0.5)'}/> </g> </svg> ); //return <g key={name}><circle cx={px} cy={py} r="30" stroke="black" opacity=".8" strokeWidth="3" fill={touch ? 'green' : 'gray'} ></circle></g> }; export default Button;
17ecc65563751737703c2f9400057599f6b846a4
[ "JavaScript", "Markdown" ]
13
JavaScript
ldoc/pixelart
0472d220827a4bcecc500567c8def61ee6ac5480
1d574aaf781785577854b8689021012782e72d0a
refs/heads/master
<file_sep><?php include_once 'inputs_types_entries.php'; include_once '../wp-content/plugins/sql-entries/backend/php/model/select_parser.php'; class personPartials{ static $group='person'; static $input=''; static $table='wp_person_selects'; public static function systemeintrag(){ $parser=new selectParser(); $options=$parser->getData(__FUNCTION__,personPartials::$table); $inputs=new inputTypes(); $inputs->select('multiselect', __FUNCTION__, __FUNCTION__, personPartials::$group,$options); } public static function eintragName(){ $inputs=new inputTypes(); $inputs->text('text', 'eintragName', 'eintragName', personPartials::$group); } public static function grundung(){ $inputs=new inputTypes(); $inputs->number('number', 'grundung', 'grundung', personPartials::$group,'1800','2500'); } . . . . . } ?> <file_sep>function editRow(element){ // set of functions responsile for editing row elements highlightEditable(element); } function highlightEditable(element){ //Highlight elements and make themm editable //get number of current row var id=element.id; var rowNum=id.match(/([0-9]+)/g); var type=id.match(/([0-9]+)-(.*)/); //grab full row var row=document.querySelector('[data-id^="tr-'+rowNum+'-'+type[2]+'"]'); //w check if that row is being edited atm or not, if yes then revert to non edit if(jQuery(row).attr('data-editable')=='true'){ jQuery(row).css('color','black'); jQuery(row).find('td').find('#valueHolder').each(function(){ jQuery(this).attr('contentEditable','false').removeClass('editableContent'); //show html() value and hide select if(jQuery(this).parent().find('#hiddenSelect')){ jQuery(this).parent().find("#hiddenSelect").css('display','none'); jQuery(this).parent().find("#hiddenSelect").prev().css('display','block'); } }) jQuery(row).attr('data-editable','false'); }else{ jQuery(row).css('color','red'); jQuery(row).find('td').find('#valueHolder').each(function(){ jQuery(this).attr('contentEditable','true').addClass('editableContent'); //hide html() value and show select if(jQuery(this).parent().find('#hiddenSelect')){ jQuery(this).parent().find("#hiddenSelect").css('display','block'); jQuery(this).parent().find("#hiddenSelect").prev().css('display','none'); } }) jQuery(row).attr('data-editable','true'); } } function applyNewValue(element){ //used for selects shown upon edit. It sets up the html value of element that is being hidden and returns on edition cancel var value=jQuery(element).find('option:selected').val(); jQuery(element).parent().find("#hiddenSelect").prev().html(value); } /*------------------------- SAVE ------------------------------*/ . . . . function show1stTab(){ jQuery('.hiddenTab').first().removeClass('hiddenTab'); } function removeSelect(element){ var id=element.id; var value=jQuery(element).prev(); var sql=buildSelectQuery(id,element); ajaxRemoveListElement(sql); location.reload(); } function buildSelectQuery(id,element){ var removed=jQuery(element).data('remove'); //element currently removed var tableDBName=jQuery(element).data('table'); //section name office/person var table=jQuery('[data-id="'+id+'"][data-table="'+tableDBName+'"]'); //tab handler var columnName=jQuery(table).data('column'); var elementsNum=table.find('[data-type^="name"]').length-1; var query=''; var x=0; // build query based on element in table table.find('[data-type^="name"]').each(function(index){ //make sure you skip the removed element if(jQuery(this).html()!=removed){ //two builders in case first/last element if(x<elementsNum){ query+=jQuery(this).html()+'|'; }else{ query+=jQuery(this).html(); } } x++; }); // now just in case check if there is | on end and remove it var lastChar=query.substr(query.length-1); if(lastChar=='|'){ query=query.slice(0,-1); } //create and return sql var sql="UPDATE `"+tableDBName+"` SET `"+columnName+"`='"+query+"'"; return sql; } /* execute */ show1stTab(); <file_sep><?php include_once '../wp-content/plugins/sql-entries/backend/php/model/translate.php'; class tabsSwitch{ var $db=''; var $lang=''; function __construct(){ $this->db= new askDatabase(); $this->lang=new translator(); } public function tab($tabName,$target){ . . . } } ?> <file_sep><?php include_once '../wp-content/plugins/sql-entries/common/databaseConnection.php'; class translator{ var $db=''; function __construct(){ $this->db= new askDatabase(); } public function translate($text=''){ . . . } } ?> <file_sep><?php include_once 'stepsView.php'; include_once 'tabsSwitcher.php'; $step=new steps(); $tab=new tabsSwitch(); #1. Get all types from DB $data=$step->type(); $tab->printTabs($data); #2. Now iterate overall types and add options foreach($data as $id=>$singleCar){ #3. First display type/space information echo '<div id="tab'.$singleCar[0].'"> <h2 style="display:inline;">'.$singleCar[1].'</h2>,'; echo '<h3 style="display:inline;"> Max:'; for($x=1;$x<=$singleCar[2];$x++){ echo '👤'; } echo '</h3>'; #👤🕴🕺👦 #Nest register form beginning $step->registerFormStart($singleCar[0]); #4. Now display options to pick how many ppl gonna ride #5. Pick up the models in that type echo '<legend><span class="number">1</span> Wybierz model </legend>'; $step->model($singleCar[1]); echo '<legend><span class="number">2</span> Podaj ilość podróżników</legend>'; $step->size($singleCar[2]); #4.1 Pick up the date echo '<legend><span class="number">3</span> Podaj datę wyjazdu i powrotu</legend>'; $step->registerFormDates($singleCar[0]); #6. Now the expected price echo '<legend><span class="number">4</span>Przewidywana cena przewozu</legend>'; $step->price($singleCar[0]); #7. Now the additional options echo '<legend><span class="number">5</span>Wybierz dodatkowe wyposazenie</legend>'; $step->additionalSetup($singleCar[0]); echo '<legend><span class="number">6</span>Przewidywana cena dodatkowe sprzętu</legend>'; $step->priceSummary($singleCar[0]); echo '<legend><span class="number">7</span>Kwota całości</legend>'; $step->totalSumUp($singleCar[0]); #8. Add the date $step->callendar(); #9. Register Your travel echo '<legend><span class="number">8</span>Podaj dane osobowe</legend>'; $step->registerForm($singleCar[0]); echo '</div>'; } ?> <file_sep><?php include_once 'inputs_types_entries.php'; include_once '../wp-content/plugins/sql-entries/backend/php/model/select_parser.php'; class officePartials{ public static function schulerlabo(){ officePartials::multiselect(__FUNCTION__); } public static function schulerlabortyp(){ officePartials::multiselect(__FUNCTION__); } public static function schulzeit(){ officePartials::multiselect(__FUNCTION__); } public static function schulerlaborIst(){ officePartials::multiselect(__FUNCTION__); } public static function kaoa(){ officePartials::multiselect(__FUNCTION__); } . . . . private function multiselect($name){ $parser=new selectParser(); $options=$parser->getData($name,officePartials::$table); $inputs=new inputTypes(); $inputs->select('multiselect', $name, $name, officePartials::$group,$options); } } ?> <file_sep><?php include_once '../../../common/databaseConnection.php'; class entriesEdit{ public function save($sql,$table){ $db= new askDatabase(); $db->modifyDataInDatabase($sql); } public function remove($table){ } public function removeSelect($sql){ . . . } } ?> <file_sep><?php include_once '../wp-content/plugins/sql-entries/backend/php/model/select_parser.php'; include_once '../wp-content/plugins/sql-entries/backend/php/view/print_selects.php'; class Selects{ . . . . } ?> <file_sep># Wordpress SQL manager Plugin for adding data into random wprdpress database tables. On output it generates virtual wordpress pages with customized theme, and json file which work with another JS plugin via API (mapping). Can't provide full source code as it was made on demand for. ![alt text](https://github.com/Volmarg/Wordpress-SQL-manager/blob/master/screenshot-1.png?raw=true) ![alt text](https://github.com/Volmarg/Wordpress-SQL-manager/blob/master/screenshot.png?raw=true) <file_sep><?php include_once 'panels_actions.php'; $do=new backendDataManage($_POST); if($_GET['action']=='addOffice'){ $do->addOffice($_GET['table']); }elseif($_GET['action']=='addPerson'){ $do->addPerson($_GET['table']); }elseif($_GET['action']=='addSelect'){ $do->addSelect($_GET['table'],$_GET['column'],$_GET['id']); } ?> <file_sep><?php include_once 'php/view/panels_display.php'; include_once 'php/view/tabsSwitching.php'; include_once 'php/model/translate.php'; function load_plugin_backend(){ #initialize classes instances $panels = new panels; $tabs=new tabsSwitch; $lang=new translator; . . . #display form for Person Entries echo '<section class="hiddenTab" id="personFormEntries" data-function="tabs-switchers">'; echo '<h1> '.$lang->translate('Person entry form').' </h1>'; $panels->addPersonEntry(); echo '</section>'; #display office entries from database echo '<section class="hiddenTab" id="officeExistingEntries" data-function="tabs-switchers">'; echo '<h1> '.$lang->translate('Office entries in database').' </h1>'; $panels->listOfOfficeEntries(); echo '</section>'; . . . . #edit list of options for peron echo '<section class="hiddenTab" id="personSelectsList" data-function="tabs-switchers">'; echo '<h1> '.$lang->translate('Selects for Person form ').'</h1>'; $panels->personSelectsList(); echo '</section>'; } ?> <file_sep><?php include_once '../wp-content/plugins/sql-entries/common/databaseConnection.php'; include_once 'office_entry_partials.php'; include_once 'person_entry_partials.php'; include_once 'selects.php'; include_once '../wp-content/plugins/sql-entries/backend/php/model/sql_entries_data.php'; include_once '../wp-content/plugins/sql-entries/backend/php/model/translate.php'; class panels{ var $path='../wp-content/plugins/register-car/backend/'; var $lang=''; public function __construct(){ $this->lang=new translator(); } public function listOfOfficeEntries(){ $db=new getSQLEntriesdata(); $db->getEntriesData('wp_office_entries','officeEntries'); } public function addOfficeEntry(){ echo '<form class="form-control" action="../wp-content/plugins/sql-entries/backend/php/controller/panels_actions_execute.php?action=addOffice&table=wp_office_entries" method="POST" id="office-form"/>'; echo '<div class="row">'; #start 1st row echo '<div class="form-group col-md-3">'; officePartials::systemeintrag(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::eintragName(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::grundung(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::ansprechpartner(); echo '</div>'; echo '</div>'; #end 1st row echo '<div class="row">'; #start 2nd row echo '<div class="form-group col-md-3">'; officePartials::schule(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::strase(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::plz(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::stadt(); echo '</div>'; echo '</div>'; #end 2 row echo '<div class="row">'; #start 3 row echo '<div class="form-group col-md-3">'; officePartials::bezirk(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::latitude(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::longitude(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::website(); echo '</div>'; echo '</div>'; #end 3 row echo '<div class="row">'; #start 4 row echo '<div class="form-group col-md-3">'; officePartials::telefon(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::aktiveFachbereiche(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::formaFirmy(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::angebote(); echo '</div>'; echo '</div>'; #end 4 row echo '<div class="row">'; #start 4 row echo '<div class="form-group col-md-3">'; officePartials::beschreibung(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::arbeitsschwerpunkte(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::schulerlabo(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::schulerlabortyp(); echo '</div>'; echo '</div>'; #end 4 row echo '<div class="row">'; #start 5 row echo '<div class="form-group col-md-3">'; officePartials::schulzeit(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::schulerlaborIst(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::kaoa(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::einzugsgebiet(); echo '</div>'; echo '</div>'; #end 5 row echo '<div class="row">'; #start 6 row echo '<div class="form-group col-md-3">'; officePartials::fortbildung(); echo '</div>'; echo '<div class="form-group col-md-3">'; officePartials::vorbereitung(); echo '</div>'; echo '<div class="form-group col-md-3">'; echo '<input type="submit" name="submit-office" value="'.$this->lang->translate("Dodaj wpis").'" class="btn btn-large btn-warning"/>'; echo '</div>'; echo '<div class="form-group col-md-3">'; echo '</div>'; echo '</div>'; #end 6 row echo '</form>' ; } . . . . } ?> <file_sep><?php include_once '../wp-content/plugins/sql-entries/common/databaseConnection.php'; include_once 'translate.php'; include_once 'select_parser.php'; class getSQLEntriesdata{ var $lang=''; var $db=''; var $parser=''; var $inpute=''; function __construct(){ $this->lang=new translator(); $this->db=new askDatabase(); $this->parser=new selectParser(); $this->input=new inputTypes(); } function getEntriesData($table,$name){ $sql="SELECT * FROM `$table`"; $fetched=$this->db->getDataFromDatabase($sql); $entries=$fetched[0]; $tableNames=$fetched[1]; $this->printEntriesData($entries,$name,$tableNames); } private function printEntriesData($entries,$name,$tableNames){ #print view of table with user inputs/entries echo '<table class="table table-striped" id="'.$name.'">'; . . . echo '<tbody>'; echo '</table>'; } private function isSelect($name,$table){ if($name!='id'){ #get all columNames in correspoing table that is currently edited $sql="SELECT `$name` FROM `$table`"; $fetched=$this->db->getDataFromDatabase($sql); $tableNames=$fetched[1][0]; $returnable=false; if($tableNames==$name){ $returnable=true; }else { $returnable=false; } } return $returnable; } private function createSelect($column,$table){ $options=$this->parser->getData($column,$table); #get data $this->input->select('multiselect', $column, $column, '',$options); #build select } } ?> <file_sep><?php include_once '../wp-content/plugins/sql-entries/backend/php/model/translate.php'; class selectsPrint{ public function printer($options,$type){ $lang=new translator; foreach($options[0] as $num=>$row){ if($num!=0){#skip first since it's id echo '<h5>'.$lang->translate($options[1][$num]).'</h5>'; echo '<table class="table table-striped" data-id="'.$num.'" data-column="'.$options[1][$num].'" data-table="'.$type.'">'; echo '<thead>'; echo '<tr>'; echo '<th>Select</th>'; echo '<th>Remove</th>'; echo '</tr>'; echo '</thead>'; echo '</tbody>'; foreach($row as $option){ echo '<tr>'; echo '<td data-type="name">'.$option.'</td>'; echo '<td data-remove="'.$option.'" class="removeSingleSelect" onclick="removeSelect(this)" id="'.$num.'" data-table="'.$type.'">✖</td>'; echo '</tr>'; } echo '<tbody>'; echo '</table>'; #input field echo '<form method="POST" action="../wp-content/plugins/sql-entries/backend/php/controller/panels_actions_execute.php?table='.$type.'&id='.$num.'&action=addSelect&column='.$options[1][$num].'">'; echo '<div class="form-group" style="display:flex;"/>'; echo '<input type="text" name="new-option" placeholder="" class="form-control" style="margin:5px;"/>'; echo '<input type="submit" value="'.$lang->translate("Add option").'" class="btn btn-xs btn-default" style="margin:5px;"/>'; echo '</div>'; echo '</form>'; } } } } ?> <file_sep><?php include_once '../wp-content/plugins/sql-entries/backend/php/model/select_parser.php'; include_once '../wp-content/plugins/sql-entries/backend/php/model/translate.php'; class inputTypes{ public function select($class,$id,$name,$group,$options){ $language=new translator(); echo "<label for='$id' ><b>".$language->translate($name)."</b></label>"; echo "<select class='$class' id='$id' name='$name' $required>"; foreach($options as $oneOption){ echo '<option> '.$oneOption.' </option>'; } echo '</select>'; } public function text($class,$id,$name,$group){ #is long ? . . . } public function number($class,$id,$name,$group,$min='',$max='',$required='',$filter=''){ #add limiter for how many can be numbers can be added | add . . . } } ?> <file_sep><?php class hooks{ public function entriesPages($dir) #generate virual pages { if(preg_match('#'.'entry-([a-zA-Z]+)-([0-9]+)'.'#',$_SERVER["REQUEST_URI"],$id)){ #if this url is fine then load theme $content=$this->sql($id[2],$id[1]); #get data to include $domain=$_SERVER['REQUEST_URI']; $linkToJson='json-'.$id[1].'-'.$id[2]; include($dir."/sql-entry-plugin-page.php"); #getTpl die(); } } public function entriesJsons() #genertae virutal json files { if(preg_match('#'.'json-([a-zA-Z]+)-([0-9]+).json'.'#',$_SERVER["REQUEST_URI"],$id)){ #if this url is fine then load theme $json=new toJava(); $content=$this->sql($id[2],$id[1]); #get data to include $jsonString=$json->buildObject($content[1],$content[0],''); echo '<pre>'; $json_array = json_decode($jsonString, JSON_PRETTY_PRINT); echo json_encode($json_array,JSON_PRETTY_PRINT); echo '</pre>'; die(); } } private function sql($id,$entry){ if(strstr($entry,'person')){ . . . . . return $returnable; } } ?> <file_sep><?php include_once 'ajax.php'; $ajax = new entriesEdit(); #save data upon table of entries edit if(@$_GET['action']=='saveEntryEdit'){ $ajax->save($_GET['sql'],$_GET['table']); }elseif(@$_GET['action']=='removeEntryEdit'){ $ajax->remove($_GET['sql'],$_GET['table']); }elseif(@$_GET['action']=='removeSelect'){ $ajax->removeSelect($_GET['sql'],$_GET['table']); } ?> <file_sep><?php /* Plugin Name: Wpisy SQL Description: SQL entries manager Author: <a href="------">------</a> Version: 1.0 */ include_once 'common/databaseConnection.php'; include_once 'common/databaseTableToJson.php'; include_once 'hooks.php'; #Plugin hook to admin Panel if(is_admin()){ #checks if thats admin panel include_once 'backend/index.php'; #include scripts wp_enqueue_script('bootstrapBundle', plugin_dir_url(__FILE__) . 'common/bootstrap/js/bootstrap.bundle.js','','',true); #true moves to footer wp_enqueue_script('bootstrap', plugin_dir_url(__FILE__) . 'common/bootstrap/js/bootstrap.js','','',true); #true moves to footer wp_enqueue_script('interface', plugin_dir_url(__FILE__) . 'backend/js/interface.js','','',true); #true moves to footer wp_enqueue_script('ajax', plugin_dir_url(__FILE__) . 'backend/js/ajax.js','','',true); #true moves to footer wp_enqueue_script('validations', plugin_dir_url(__FILE__) . 'backend/js/validations.js','','',true); #true moves to footer #include styles wp_enqueue_style( 'boostrap', plugin_dir_url(__FILE__) . 'common/bootstrap/css/bootstrap.css', '', '', 'all' ); wp_enqueue_style( 'panelsBack', plugin_dir_url(__FILE__) . 'backend/css/panels.css', '', '', 'all' ); }#include styles and sripts if it's front end else{ wp_enqueue_script('ajaxFront', plugin_dir_url(__FILE__) . 'frontend/js/ajax.js','','',true); #true moves to footer wp_enqueue_script('interfaceFront', plugin_dir_url(__FILE__) . 'frontend/js/userInterface.js','','',true); #true moves to footer wp_enqueue_script('carManageFront', plugin_dir_url(__FILE__) . 'frontend/js/car-types-tabs.js','','',true); #true moves to footer wp_enqueue_script('jQuery', plugin_dir_url(__FILE__) . 'common/jq.3.3.1.js','',''); wp_enqueue_style( 'registerForm', plugin_dir_url(__FILE__) . 'frontend/css/car-register-form.css', '', '', 'all' ); } #hooks add_action('admin_menu', 'hook_plugin_in_panel'); #add admin menu option add_action( 'wp', 'entriesPages' ); #add handling virutal pages add_action( 'wp', 'entriesJsons' ); #add handling virtualJsonFiles #Functions for hooks function entriesPages(){ $dir = get_template_directory( __FILE__ ); #this variable stores curr theme path $hook=new hooks(); $hook->entriesPages($dir); } function entriesJsons(){ $hook=new hooks(); $hook->entriesJsons($dir); } function hook_plugin_in_panel(){ #hook options in admin panel add_menu_page( 'Wpisy SQL', 'Wpisy SQL', 'manage_options', 'sql-entries', 'load_plugin_backend' ); #settings for menu acces } ?> <file_sep><?php include_once '../wp-content/plugins/sql-entries/common/databaseConnection.php'; class selectParser{ public function getData($column,$table){ $db= new askDatabase(); $sql="SELECT $column FROM `$table`"; $fetched=$db->getDataFromDatabase($sql); $values=array(); $options=array(); #for sselect all so it can iterate over each rows . . . return $options; } private function split($data,$type){ $arrayOfOptions=array(); . . . return $arrayOfOptions; } } ?> <file_sep><?php include_once '../../../common/databaseConnection.php'; class backendDataManage{ var $data=''; function __construct($data){ $this->data=$data; } private function redirect(){ $redirect=$_SERVER['HTTP_REFERER']; header('Location:'.$redirect); } public function addOffice($table){ $sql='INSERT INTO `'.$table.'` VALUES ("", "'.$this->data['systemeintrag'].'", "'.$this->data['eintragName'].'", . . . "'.$this->data['beschreibung'].'", "'.$this->data['arbeitsschwerpunkte'].'", "'.$this->data['schulerlabo'].'", "'.$this->data['schulzeit'].'" )'; $db= new askDatabase(); $db->modifyDataInDatabase($sql); $this->redirect(); } public function addPerson($table){ $sql='INSERT INTO `'.$table.'` VALUES ("", "'.$this->data['systemeintrag'].'", "'.$this->data['eintragName'].'", . . . . "'.$this->data['thematischeSchwerpunkte'].'", "'.$this->data['zielsetzung'].'" )'; echo $this->data['beschreibung']; $db= new askDatabase(); $db->modifyDataInDatabase($sql); $this->redirect(); } public function addSelect($table,$column,$id){ $db= new askDatabase(); #get selects from table $sql="SELECT `$column` FROM `$table` WHERE `id`=1"; $fetched=$db->getDataFromDatabase($sql); $values=$fetched[0][0][0]; $column=$fetched[1][0]; #and just add one more on end $newValues=$values.'|'.$_POST['new-option']; #now update table $sql="UPDATE `$table` SET `$column`='$newValues' WHERE `id`=1;"; $db->modifyDataInDatabase($sql); $this->redirect(); } } ?>
8b3929a4c81942059b9d25a2ce72e4aed212c68a
[ "JavaScript", "Markdown", "PHP" ]
20
PHP
Volmarg/Wordpress-SQL-manager
5ba30dc288d030e7e67fb4eae91ac9d5c5621a9e
4a190f3c74bdbec03b1e04878c779d6d082ad572
refs/heads/master
<file_sep>import Button from 'react-bootstrap/Button'; import Navbar from 'react-bootstrap/Navbar'; import Nav from 'react-bootstrap/Nav'; import Map from 'ol/Map'; import View from 'ol/View'; import Overlay from 'ol/Overlay'; import Graticule from 'ol/layer/Graticule'; import Stroke from 'ol/style/Stroke'; import { useState, useEffect } from 'react'; import Config from './config.json'; import { OSM as OSMSource, Stamen as StamenSource, XYZ as XYZSource, ImageWMS as ImageWMSSource, Vector as VectorSource } from 'ol/source/'; import { Attribution, Control, ScaleLine, ZoomSlider, Zoom, Rotate, MousePosition, OverviewMap, defaults as defaultControls, ZoomToExtent } from 'ol/control'; import { Image as ImageLayer, Group as LayerGroup, Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'; import { GeoJSON, XYZ } from 'ol/format'; import { Style, Fill as FillStyle, RegularShape as RegularShapeStyle, Stroke as StrokeStyle, Circle as CircleStyle } from 'ol/style'; import Circle from 'ol/geom/Circle'; import Feature from 'ol/Feature'; import Draw, { createBox, createRegularPolygon, } from 'ol/interaction/Draw'; import DragBox from 'ol/interaction/DragBox'; import { LineString, Polygon, MultiPolygon } from 'ol/geom'; import { getArea, getLength } from 'ol/sphere'; import { unByKey } from 'ol/Observable'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import { PDFDownloadLink, PDFViewer } from '@react-pdf/renderer'; import NewPDFPages from './NewPDFPages'; import Alert from 'react-bootstrap/Alert'; import Form from 'react-bootstrap/Form'; import domtoimage from 'dom-to-image'; //import html2canvas from 'html2canvas'; export default function Mapviewer(props) { const gcolor1 = '#82D7F3'; const gcolor2 = '#0D2DC3'; const i_basemap = 0; const i_graticule = 1; const i_highlight = 2; const i_measurement = 3; const i_magic = 4; const i_bbox = 5; const i_country = 6; const i_group = 7; var idx = -1; var measuring = false; var identifying = false; var drawing = false; const [peta, setPeta] = useState(null); const [identify, setIdentify] = useState(false); const [alertIdentify, setAlertIdentify] = useState(false); const [measurement, setMeasurement] = useState(false); const [drawingO, setDrawingO] = useState(false); const [pointColor, setPointColor] = useState("#FF0000"); const [strokeColor, setStrokeColor] = useState('#EEFF00'); const [strokeWidth, setStrokeWidth] = useState(1); const [fillColor, setFillColor] = useState('#FFFFFF'); const [fillColorAlpha, setFillColorAlpha] = useState(1.0); const [title, setTitle] = useState('map title'); const [description, setDescription] = useState('map description'); const [legend, setLegend] = useState(false); const [size, setSize] = useState('A4'); const [orientation, setOrientation] = useState('landscape');//landscape const [height, setHeight] = useState('500'); const [clegend, setCLegend] = useState("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaQAAADwCAMAAAB4+uBSAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAADZQTFRF////x8fHxMTEzs7O0tLS2tra5+fn8fHxycnJ5ubm9/f3/Pz819fX4+Pj7e3t7OzszMzMvb29Tvoc/QAADfJJREFUeJztnYl2<KEY>); const [capture, setCapture] = useState("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAaQAAADwCAMAAAB4+<KEY>); var draw; // global so we can remove it later var sketch; var helpTooltip; var helpTooltipElement; var measureTooltip; var measureTooltipElement; var continuePolygonMsg = 'Click to continue drawing the polygon, Double click to finish'; var continueLineMsg = 'Click to continue drawing the line, Double click to finish'; const url_list_harvesting_bbox = Config.api_domain + "/harvestings/bbox_identifier/"; useEffect(() => { init_map(); }, []) function init_map() { const graticule = new Graticule({ // the style to use for the lines, optional. strokeStyle: new Stroke({ color: gcolor1, //'rgba(255,120,0,0.9)', width: 1, lineDash: [0.5, 4], }), showLabels: true, wrapX: false, }) var overviewMapControl = new OverviewMap({ // see in overviewmap-custom.html to see the custom CSS used className: 'ol-overviewmap ol-custom-overviewmap', layers: [ new TileLayer({ source: new XYZSource({ url: Config.proxy_domain + "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles Imagery © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }) }) ], collapseLabel: '\u00BB', label: '\u00AB', collapsed: true, }); var scaleLine = new ScaleLine({ bar: true, text: true, minWidth: 125 }); const el = document.createElement('div'); el.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="19" height="19" fill="currentColor" class="bi bi-house-fill" viewBox="0 0 16 16">' + '<path fill-rule="evenodd" d="m8 3.293 6 6V13.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 13.5V9.293l6-6zm5-.793V6l-2-2V2.5a.5.5 0 0 1 .5-.5h1a.5.5 0 0 1 .5.5z"/>' + '<path fill-rule="evenodd" d="M7.293 1.5a1 1 0 0 1 1.414 0l6.647 6.646a.5.5 0 0 1-.708.708L8 2.207 1.354 8.854a.5.5 0 1 1-.708-.708L7.293 1.5z"/>' + '</svg>'; var zoomToExtentControl = new ZoomToExtent({ 'tipLabel': 'Zoom to initial extent', 'label': el }) const locate = document.createElement('div'); locate.className = 'ol-control ol-unselectable graticule'; locate.innerHTML = '<button title="Show/Hide Graticule"><i class="fa fa-th"></i></button>'; locate.addEventListener('click', function () { graticule.setVisible(!graticule.getVisible()) }); const gratiControl = new Control({ element: locate }); const measure = document.createElement('div'); measure.className = 'ol-control ol-unselectable measure'; measure.innerHTML = '<button title="Measurement"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-rulers" viewBox="0 0 16 16">' + '<path d="M1 0a1 1 0 0 0-1 1v14a1 1 0 0 0 1 1h5v-1H2v-1h4v-1H4v-1h2v-1H2v-1h4V9H4V8h2V7H2V6h4V2h1v4h1V4h1v2h1V2h1v4h1V4h1v2h1V2h1v4h1V1a1 1 0 0 0-1-1H1z"/>' + '</svg></button>'; measure.addEventListener('click', function () { var cek = document.getElementById("measurement"); cek.classList.contains('show') ? setMeasurement(false) : setMeasurement(true); }); const measureControl = new Control({ element: measure }); const identify = document.createElement('div'); identify.className = 'ol-control ol-unselectable identify'; identify.innerHTML = '<button title="Identify"><i class="fa fa-info-circle"></i></button>'; identify.addEventListener('click', function () { var cek = document.getElementById("identifying"); cek.classList.contains('show') ? setIdentify(false) : setIdentify(true); //setIdentify(true); }); const identifyControl = new Control({ element: identify }); const drawingDiv = document.createElement('div'); drawingDiv.className = 'ol-control ol-unselectable drawing'; drawingDiv.innerHTML = '<button title="Draw"><i class="fa fa-pencil"></i></button>'; drawingDiv.addEventListener('click', function () { var cek = document.getElementById("drawing"); cek.classList.contains('show') ? setDrawingO(false) : setDrawingO(true); //setDrawingO(true) //addInteraction2() }); const drawingControl = new Control({ element: drawingDiv }); var sourceHighlight = new VectorSource({ //features: new GeoJSON().readFeatures(geojsonObject), wrapX: false }); var image = new CircleStyle({ radius: 5, fill: null, stroke: new Stroke({ color: 'red', width: 1 }), }); var styles = { 'Point': new Style({ image: image, }), 'LineString': new Style({ stroke: new Stroke({ color: 'green', width: 1, }), }), 'MultiLineString': new Style({ stroke: new Stroke({ color: 'green', width: 1, }), }), 'MultiPoint': new Style({ image: image, }), 'MultiPolygon': new Style({ stroke: new Stroke({ color: 'yellow', width: 1, }), fill: new FillStyle({ color: 'rgba(255, 255, 0, 0.1)', }), }), 'Polygon': new Style({ stroke: new Stroke({ color: 'blue', lineDash: [4], width: 3, }), fill: new FillStyle({ color: 'rgba(0, 0, 255, 0.1)', }), }), 'GeometryCollection': new Style({ stroke: new Stroke({ color: 'magenta', width: 2, }), fill: new FillStyle({ color: 'magenta', }), image: new CircleStyle({ radius: 10, fill: null, stroke: new Stroke({ color: 'magenta', }), }), }), 'Circle': new Style({ stroke: new Stroke({ color: 'red', width: 2, }), fill: new FillStyle({ color: 'rgba(255,0,0,0.2)', }), }), }; var styleFunction = function (feature) { //console.log(feature) return styles[feature.getGeometry().getType()]; }; //var vectorSource = new VectorSource({ // features: new GeoJSON().readFeatures(geojsonObject), //}); //sourceHighlight.addFeature(new Feature(new Circle([5e6, 7e6], 1e6))); var vectorHighlight = new VectorLayer({ source: sourceHighlight, style: styleFunction, zIndex: 899 }); var sourceMeasurement = new VectorSource(); var vectorMeasurement = new VectorLayer({ source: sourceMeasurement, zIndex: 901, style: new Style({ fill: new FillStyle({ color: 'rgba(255, 255, 255, 0.2)', }), stroke: new StrokeStyle({ color: '#ffcc33', width: 2, }), image: new CircleStyle({ radius: 7, fill: new FillStyle({ color: '#ffcc33', }), }), }), }); var sourceMagic = new VectorSource(); var vectorMagic = new VectorLayer({ source: sourceMagic, zIndex: 901, style: new Style({ fill: new FillStyle({ color: 'rgba(255, 255, 255, 0)', }), stroke: new StrokeStyle({ color: 'rgba(255, 255, 255, 0)', width: 0.5, }) }), }); var bboxFirst = { "type": "FeatureCollection", "features": [ { "type": "Feature", "geometry": { "type": "Polygon", "coordinates": [ [ [ props.bbox[0].toFixed(2), props.bbox[1].toFixed(2) ], [ props.bbox[2].toFixed(2), props.bbox[1].toFixed(2) ], [ props.bbox[2].toFixed(2), props.bbox[3].toFixed(2) ], [ props.bbox[0].toFixed(2), props.bbox[3].toFixed(2) ], [ props.bbox[0].toFixed(2), props.bbox[1].toFixed(2) ] ] ] } } ] } var sourceBbox = new VectorSource({ format: new GeoJSON(), features: new GeoJSON().readFeatures(bboxFirst), wrapX: false }); var sourceCountry = new VectorSource({ format: new GeoJSON(), wrapX: false }); var vectorCountry = new VectorLayer({ source: sourceCountry, zIndex: 899, style: new Style({ fill: new FillStyle({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new StrokeStyle({ color: '#0000ff', width: 1 }), image: new CircleStyle({ radius: 7, fill: new FillStyle({ color: '#ffcc33' }) }) }) }); var vectorBbox = new VectorLayer({ source: sourceBbox, zIndex: 899, visible: props.showBbox, style: new Style({ fill: new FillStyle({ color: 'rgba(255, 255, 255, 0.2)' }), stroke: new StrokeStyle({ color: '#ff00ee', width: 1 }), image: new CircleStyle({ radius: 7, fill: new FillStyle({ color: '#ffcc33' }) }) }) }); /** * Elements that make up the popup. */ var container = document.getElementById('popup'); var content = document.getElementById('popup-content'); var closer = document.getElementById('popup-closer'); /** * Create an overlay to anchor the popup to the map. */ var overlay = new Overlay({ element: container, autoPan: true, autoPanAnimation: { duration: 250, }, }); /** * Add a click handler to hide the popup. * @return {boolean} Don't follow the href. */ closer.addEventListener('click', function () { sourceHighlight.clear(); overlay.setPosition(undefined); closer.blur(); return false; }); var map = new Map({ view: new View({ center: [0, 0], zoom: 1 }), layers: [ new TileLayer({ source: new XYZSource({ url: Config.proxy_domain + "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles Imagery © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }) }), graticule, vectorHighlight, vectorMeasurement, vectorMagic, vectorBbox, vectorCountry, new LayerGroup() ], target: 'map-container', overlays: [overlay], controls: defaultControls().extend([ new Attribution({ collapsed: false }), overviewMapControl, scaleLine, zoomToExtentControl, gratiControl, measureControl, identifyControl, drawingControl //new MousePosition() ]), }); var closePrint = document.getElementById('close_print'); closePrint.addEventListener( 'click', function () { props.setPrinting(false) }, false ); //measurement /** * Format length output. * @param {LineString} line The line. * @return {string} The formatted length. */ var formatLength = function (line) { var length = getLength(line); var output; if (length > 100) { var calculation = Math.round((length / 1000) * 100) / 100 output = calculation.toLocaleString('en-US', { maximumFractionDigits: 2 }) + ' ' + 'km'; } else { var calculation = Math.round(length * 100) / 100 output = calculation.toLocaleString('en-US', { maximumFractionDigits: 2 }) + ' ' + 'm'; } return output; }; /** * Format area output. * @param {Polygon} polygon The polygon. * @return {string} Formatted area. */ var formatArea = function (polygon) { var area = getArea(polygon); var output; if (area > 10000) { var calculation = Math.round((area / 1000000) * 100) / 100 output = calculation.toLocaleString('en-US', { maximumFractionDigits: 2 }) + ' ' + 'km<sup>2</sup>'; } else { var calculation = Math.round(area * 100) / 100 output = calculation.toLocaleString('en-US', { maximumFractionDigits: 2 }) + ' ' + 'm<sup>2</sup>'; } return output; }; /** * Creates a new help tooltip */ function createHelpTooltip() { if (helpTooltipElement) { helpTooltipElement.parentNode.removeChild(helpTooltipElement); } helpTooltipElement = document.createElement('div'); helpTooltipElement.className = 'ol-tooltip hidden'; helpTooltip = new Overlay({ element: helpTooltipElement, offset: [15, 0], positioning: 'center-left', }); map.addOverlay(helpTooltip); } /** * Creates a new measure tooltip */ function createMeasureTooltip() { if (measureTooltipElement) { measureTooltipElement.parentNode.removeChild(measureTooltipElement); } measureTooltipElement = document.createElement('div'); measureTooltipElement.className = 'ol-tooltip ol-tooltip-measure'; measureTooltip = new Overlay({ element: measureTooltipElement, offset: [0, -15], positioning: 'bottom-center', }); map.addOverlay(measureTooltip); } var typeSelect = document.getElementById('type'); typeSelect.onchange = function () { if (measuring) { map.removeInteraction(draw); addInteraction(); } }; function addInteraction() { var type = typeSelect.value == 'area' ? 'Polygon' : 'LineString'; draw = new Draw({ source: sourceMeasurement, type: type, style: new Style({ fill: new FillStyle({ color: 'rgba(255, 255, 255, 0.2)', }), stroke: new StrokeStyle({ color: 'rgba(140, 228, 250, 0.5)', lineDash: [5, 5], width: 2, }), image: new CircleStyle({ radius: 5, stroke: new StrokeStyle({ color: 'rgba(140, 228, 250, 0.7)', }), fill: new FillStyle({ color: 'rgba(255, 255, 255, 0.2)', }), }), }), }); map.addInteraction(draw); createMeasureTooltip(); createHelpTooltip(); var listener; draw.on('drawstart', function (evt) { // set sketch sketch = evt.feature; /** @type {import("../src/ol/coordinate.js").Coordinate|undefined} */ var tooltipCoord = evt.coordinate; listener = sketch.getGeometry().on('change', function (evt) { var geom = evt.target; var output; if (geom instanceof Polygon) { output = formatArea(geom); tooltipCoord = geom.getInteriorPoint().getCoordinates(); } else if (geom instanceof LineString) { output = formatLength(geom); tooltipCoord = geom.getLastCoordinate(); } measureTooltipElement.innerHTML = output; measureTooltip.setPosition(tooltipCoord); }); }); draw.on('drawend', function () { measureTooltipElement.className = 'ol-tooltip ol-tooltip-static'; measureTooltip.setOffset([0, -7]); // unset sketch sketch = null; // unset tooltip so that a new one can be created measureTooltipElement = null; createMeasureTooltip(); unByKey(listener); }); } var closeMeasurement = document.getElementById('close_measurement'); closeMeasurement.addEventListener( 'click', function () { setMeasurement(false) }, false ); var finishMeasurement = document.getElementById('finish_measurement'); finishMeasurement.addEventListener( 'click', function () { if (!measuring) { //peta.getInteractions().pop() measuring = true; map.removeOverlay(helpTooltip) map.removeOverlay(measureTooltip) addInteraction(); finishMeasurement.innerHTML = "Finish Measurement"; } else { measuring = false; map.removeInteraction(draw) map.removeOverlay(helpTooltip) map.removeOverlay(measureTooltip) finishMeasurement.innerHTML = "Start Measurement"; } }, false ); var clearButton = document.getElementById('clear_measurement'); clearButton.addEventListener( 'click', function () { sourceMeasurement.clear(); var elements = document.getElementsByClassName("ol-tooltip-static") //console.log(staticTooltip) while (elements.length > 0) { elements[0].parentNode.removeChild(elements[0]); } }, false ); var closeIdentifying = document.getElementById('close_identifying'); closeIdentifying.addEventListener( 'click', function () { setIdentify(false) }, false ); var closeDrawing = document.getElementById('close_drawing'); closeDrawing.addEventListener( 'click', function () { setDrawingO(false) }, false ); //drawing var typeSelect2 = document.getElementById('type2'); function addInteraction2() { var value = typeSelect2.value; var point_color = document.getElementById("point_color") var stroke_color = document.getElementById("stroke_color") var stroke_width = document.getElementById("stroke_width") var fill_color_rgba = document.getElementById("fill_color_rgba") var sourceDrawing = new VectorSource(); var vectorDrawing = new VectorLayer({ source: sourceDrawing, zIndex: 901, style: new Style({ fill: new FillStyle({ color: fill_color_rgba.innerHTML, }), stroke: new StrokeStyle({ color: stroke_color.value, width: stroke_width.value, }), image: new CircleStyle({ radius: 3, fill: new FillStyle({ color: point_color.value, }), }), }), }); var random = Date.now() vectorDrawing.set('id', 'drawing-' + random) map.addLayer(vectorDrawing); props.setMapLayer(oldArray => [...oldArray, { id: 'drawing-' + random, title: value + "-" + random, server: 'local', tipe: 'geojson', url: '', layer: '', original: '', pdf: '', geojson: '', kml: '', gml: '', shp: '', csv: '', excel: '', metadata: false, table: false, visible: true, opacity: 1 }]); draw = new Draw({ source: sourceDrawing, type: value, }); map.addInteraction(draw); } var finishDrawing = document.getElementById('finish_drawing'); finishDrawing.addEventListener( 'click', function () { if (!drawing) { //peta.getInteractions().pop() drawing = true; //map.removeOverlay(helpTooltip) //map.removeOverlay(measureTooltip) addInteraction2(); finishDrawing.innerHTML = "Finish Drawing"; var point_color = document.getElementById("point_color") var stroke_color = document.getElementById("stroke_color") var stroke_width = document.getElementById("stroke_width") var fill_color = document.getElementById("fill_color") var fill_color_alpha = document.getElementById("fill_color_alpha") point_color.disabled = true; stroke_color.disabled = true; stroke_width.disabled = true; fill_color.disabled = true; fill_color_alpha.disabled = true; typeSelect2.disabled = true; } else { drawing = false; map.removeInteraction(draw) //map.removeOverlay(helpTooltip) //map.removeOverlay(measureTooltip) finishDrawing.innerHTML = "Start Drawing"; var point_color = document.getElementById("point_color") var stroke_color = document.getElementById("stroke_color") var stroke_width = document.getElementById("stroke_width") var fill_color = document.getElementById("fill_color") var fill_color_alpha = document.getElementById("fill_color_alpha") point_color.disabled = false; stroke_color.disabled = false; stroke_width.disabled = false; fill_color.disabled = false; fill_color_alpha.disabled = false; typeSelect2.disabled = false; } }, false ); var finishIdentifying = document.getElementById('finish_identifying'); finishIdentifying.addEventListener( 'click', function () { if (!identifying) { identifying = true; finishIdentifying.innerHTML = "Finish Identifying"; document.body.style.cursor = 'help'; setAlertIdentify(true); } else { identifying = false; setAlertIdentify(false); finishIdentifying.innerHTML = "Start Identifying"; document.body.style.cursor = 'default'; } } , false ); var pointerMoveHandler = function (evt) { if (evt.dragging) { return; } /* if (map) { var pixel = map.getEventPixel(evt.originalEvent); var hit = map.forEachLayerAtPixel(pixel, function () { return true; }); map.getTargetElement().style.cursor = hit ? 'pointer' : ''; } */ //console.log(measuring) if (measuring) { /** @type {string} */ var helpMsg = 'Click to start measuring'; if (sketch) { var geom = sketch.getGeometry(); if (geom instanceof Polygon) { helpMsg = continuePolygonMsg; } else if (geom instanceof LineString) { helpMsg = continueLineMsg; } } if (helpTooltipElement) { helpTooltipElement.innerHTML = helpMsg; helpTooltip.setPosition(evt.coordinate); helpTooltipElement.classList.remove('hidden'); } } }; map.on('pointermove', pointerMoveHandler); //peta.on('rendercomplete', updatePrint(peta)); map.on('singleclick', function (evt) { //document.getElementById('info').innerHTML = ''; if (identifying) { var viewResolution = /** @type {number} **/ (map.getView().getResolution()); //console.log(peta) /* var layers = map.getLayers().getArray() //console.log(layers.length) var layer = layers[layers.length - 1] //console.log(layer) var wmsSource = layer.getSource() console.log(wmsSource) var url = wmsSource.getFeatureInfoUrl( evt.coordinate, viewResolution, 'EPSG:3857', { 'INFO_FORMAT': 'application/json' } //text/html ); */ var wms = map.getLayers(); idx = -1; wms.forEach(function (layer, i) { //var layerid = i; //console.log(layer.getVisible()) if(layer instanceof ImageLayer){ if (layer.getVisible()) { idx = i; } } }); var url; if (idx === -1) { alert("There is no WMS layer visible") } else { //console.log(); var layer = wms.getArray()[idx] //console.log(layer) var wmsSource = layer.getSource() url = wmsSource.getFeatureInfoUrl( evt.coordinate, viewResolution, 'EPSG:3857', { 'INFO_FORMAT': 'application/json' } //text/html ); } if (url) { fetch(url) .then(function (response) { return response.text(); }) .then(function (html) { //document.getElementById('info').innerHTML = html; var data = JSON.parse(html); //console.log(html) var feature = data.features[0] //html; overlay.setPosition(); sourceHighlight.clear(); if (feature) { console.log(feature) //console.log(feature.geometry.coordinates[0]) var transform = true; if (feature.geometry.type === "MultiPolygon") { var koordinat = feature.geometry.coordinates[0][0][0][0] //console.log(koordinat) if (koordinat > 180 || koordinat < -180) transform = false; //console.log(cek_koordinat); } else { } console.log(transform) if (transform) { //console.log(new GeoJSON().readFeature(feature, {featureProjection: 'EPSG:3857'})) sourceHighlight.addFeature(new GeoJSON().readFeature(feature, { featureProjection: 'EPSG:3857' })) } else { sourceHighlight.addFeature(new GeoJSON().readFeature(feature)) } /* console.log(feature.geometry) var src = 'EPSG:3857' var dest = 'EPSG:4326' var geomnya; if (feature.geometry.type === "MultiPolygon") { geomnya = new MultiPolygon(feature.geometry.coordinates) console.log(geomnya) } sourceHighlight.addFeature(feature) /* const featurenya = new Feature({ geometry: Polygon([[[8623931.28, 1449016.75], [8624007.72, 1458265.63], [8629358.31, 1458571.37], [8628441.06, 1455284.58], [8625765.77, 1449781.12], [8630275.55, 1453450.09], [8629281.88, 1452456.42], [8627294.51, 1451080.54], [8625765.76, 1449781.11], [8623931.28, 1449016.75]]] ) }); //source.addFeature(feature); sourceHighlight.addFeature(feature) */ /* var featurenya = new Feature({ geometry: geomnya, name: 'highlighted' }) //console.log(featurenya) console.log(featurenya.getGeometry()) //feature.getGeometry().transform(src, dest).transform(src, dest) /* sourceHighlight.addFeature(featurenya) //peta.getView().fit(featurenya.getGeometry()) //console.log(sourceHighlight) */ if (feature.hasOwnProperty("properties")) { //console.log(data.features[0].properties) var tabel = '<p>Layer: ' + layer.get('title') + '</p>'; tabel = tabel + '<div style="max-height:250px;overflow:auto;"><table class="table table-strip font-11">'; //tabel += '<tr><td>ID</td><td style="max-width:200px;overflow-wrap: break-word;"> ' + data.features[0].id + '</td></tr>' for (var prop in feature.properties) { //console.log(prop) //console.log(feature.properties[prop]) tabel += '<tr><td>' + prop + '</td><td style="max-width:200px;overflow-wrap: break-word;">' + feature.properties[prop] + '</td></tr>' } //feature.properties.forEach(element => { // console.log(element); // }); tabel += "</table></div>" content.innerHTML = tabel; overlay.setPosition(evt.coordinate); } } }); } } }); setPeta(map); } useEffect(() => { if (peta) { //alert(props.provider) switch_basemap() } }, [props.provider]) useEffect(() => { if (props.printing) { //alert(props.printing) updatePrint() } }, [props.printing]) useEffect(() => { if (peta) { var renderComplete = function (evt) { /* var wms = peta.getLayers().getArray(); //console.log(wms) idx = -1; wms[i_group].getLayers().forEach(function (layer, i) { //var layerid = i; //console.log(layer.getVisible()) if (layer.getVisible()) { idx = i; } }); */ var wms = peta.getLayers(); //console.log(wms) idx = -1; wms.forEach(function (layer, i) { //var layerid = i; //console.log(layer.getVisible()) if(layer instanceof ImageLayer){ if (layer.getVisible()) { idx = i; } } }); var name_layer = document.getElementById('name_layer'); if (idx === -1) { name_layer.innerHTML = "None"; } else { //console.log(); // name_layer.innerHTML = wms[i_group].getLayers().getArray()[idx].get('title'); name_layer.innerHTML = wms.getArray()[idx].get('title'); } //console.log(idx) } peta.on('rendercomplete', renderComplete); var exportButton = document.getElementById('export-pdf'); exportButton.addEventListener( 'click', function () { //alert('clicked') //exportButton.disabled = true; document.body.style.cursor = 'progress'; updatePrint() }, false ); } }, [peta]) useEffect(() => { if (peta) { if (props.buffer.length > 0) { console.log(props.buffer) //console.log(props.buffer[0]) //console.log(props.buffer[0].data) if (props.buffer[0].data.features.length > 0) { var shapeSource = new VectorSource({ features: new GeoJSON().readFeatures(props.buffer[0].data, { featureProjection: 'EPSG:3857' }), wrapX: false }) var shapeLayer = new VectorLayer({ source: shapeSource, zIndex: 899, }); shapeLayer.set('id', 'uploader' + props.buffer[0].data.fileName) peta.addLayer(shapeLayer); props.setMapLayer(oldArray => [...oldArray, { id: 'uploader' + props.buffer[0].data.fileName, title: props.buffer[0].data.fileName, server: 'local', tipe: 'zip', url: '', layer: '', original: '', pdf: '', geojson: '', kml: '', gml: '', shp: '', csv: '', excel: '', metadata: false, table: false, visible: true, opacity: 1 }]); props.setZoomTo('uploader' + props.buffer[0].data.fileName) } else { alert('no features found') } props.setBuffer([]) } } }, [props.buffer]) useEffect(() => { if (peta) { if (props.performZoom) { var layers = peta.getLayers().getArray() //console.log(layers) //console.log(layers[i_bbox].getSource().getFeatures()) //console.log(layers[i_country].getSource().getFeatures()[0].getGeometry()) peta.getView().fit(layers[i_bbox].getSource().getFeatures()[0].getGeometry()) props.setPerformZoom(false) // map.getView().animate({zoom: map.getView().getZoom() - 0.5}); } } }, [props.performZoom]) useEffect(() => { if (peta) { if (props.zoomTo) { //alert(props.zoomTo) if (props.zoomTo.includes("upload")) { var candidate; peta.getLayers().forEach(function (layer, i) { //alert('ya') //console.log(layer.getKeys()) if (layer.getKeys().includes("id")) { //console.log(layer); //alert('wow') if (layer.get("id") === props.zoomTo) { //alert('oi') candidate = layer; } } /* if (layer.get("id") !== undefined && layer.get("id") === props.identifierDelete) { } */ }); //console.log(candidate.getSource().getExtent()) //console.log(candidate.getExtent()) peta.getView().fit(candidate.getSource().getExtent()) props.setZoomTo() } else if (props.zoomTo.includes("drawing")) { var candidate; peta.getLayers().forEach(function (layer, i) { //alert('ya') //console.log(layer.getKeys()) if (layer.getKeys().includes("id")) { //console.log(layer); //alert('wow') if (layer.get("id") === props.zoomTo) { //alert('oi') candidate = layer; } } /* if (layer.get("id") !== undefined && layer.get("id") === props.identifierDelete) { } */ }); //console.log(candidate.getSource().getExtent()) //console.log(candidate.getExtent()) //console.log(candidate) peta.getView().fit(candidate.getSource().getExtent(), peta.getSize()) props.setZoomTo() } else { const requestOptions = { method: 'GET' }; fetch(url_list_harvesting_bbox + props.zoomTo, requestOptions).then(res => res.json()).then(data => { //console.log(data.message.bbox); var bbox = JSON.parse(data.message.bbox); //console.log(bbox) //setZoomTo(bbox) var feature = new Feature({ geometry: new Polygon(bbox.coordinates), name: 'country' }) //console.log(feature) peta.getView().fit(feature.getGeometry()) props.setZoomTo() }) } /* console.log(props.zoomTo) //map.getView().fit(props.zoomTo) var feature = new Feature({ geometry: new Polygon(props.zoomTo.coordinates), name: 'country' }) console.log(feature) map.getView().fit(feature.getGeometry()) */ // map.getView().animate({zoom: map.getView().getZoom() - 0.5}); } } }, [props.zoomTo]) useEffect(() => { if (peta) { //load_wms() if (props.mapLayer.length > 0) { //console.log(props.mapLayer[props.mapLayer.length - 1]) //var row = props.mapLayer[props.mapLayer.length - 1] //console.log(row) //console.log(row.layer) props.mapLayer.forEach(function (l, y) { //console.log(l) var check = false peta.getLayers().forEach(function (layer, i) { if (layer.get('id') === l.id) { layer.setVisible(l.visible) layer.setOpacity(parseFloat(l.opacity)) //console.log(l.opacity) check = true } }) if (!check) { // alert('oi') if (l.tipe === "wms") { //alert(main) var wmsSource = new ImageWMSSource({ url: Config.proxy_domain + l.url, params: { 'LAYERS': l.layer }, ratio: 1, serverType: l.server, crossOrigin: 'anonymous' }); var wmsLayer = new ImageLayer({ source: wmsSource }) wmsLayer.set('id', l.id) wmsLayer.set('title', l.title) //console.log(map.getLayerGroup()) //var group = map.getLayerGroup() //var layers = peta.getLayers().getArray(); //var group = layers[i_group].getLayers().getArray() //console.log(layers) //group.push(wmsLayer) //console.log(layers) peta.addLayer(wmsLayer) } } }) /* if (row.tipe === "wms") { var check = false map.getLayers().forEach(function (layer, i) { //console.log(layer); //console.log(layer.get('id')); if (layer.get('id') === row.id) { layer.setVisible(row.visible) check = true alert('visible') } }); } */ } } }, [props.mapLayer]) useEffect(() => { //alert(props.showBbox) if (peta) { var layers = peta.getLayers().getArray() //console.log(layers) //alert(props.showBbox) layers[i_bbox].setVisible(props.showBbox) } }, [props.showBbox]) useEffect(() => { //alert(props.showBbox) if (peta) { var layers = peta.getLayers().getArray() //console.log(layers) layers[i_country].setVisible(props.showArea) } }, [props.showArea]) useEffect(() => { //alert(props.showBbox) if (peta) { //var layers = map.getLayers().getArray() //console.log(layers) //console.log(props.identifierDelete) //alert(props.identifierDelete) if (props.identifierDelete) { // alert('ok') //console.log(map.getLayers().getArray().length) var candidate; peta.getLayers().forEach(function (layer, i) { //alert('ya') //console.log(layer.getKeys()) if (layer.getKeys().includes("id")) { //console.log(layer); //alert('wow') if (layer.get("id") === props.identifierDelete) { //alert('oi') candidate = layer; } } /* if (layer.get("id") !== undefined && layer.get("id") === props.identifierDelete) { } */ }); if (candidate) { peta.removeLayer(candidate) } props.setIdentifierDelete('') } //layers[2].setVisible(props.showArea) } }, [props.identifierDelete]) /* useEffect(() => { //alert(props.showBbox) if (map) { //var layers = map.getLayers().getArray() //console.log(layers) console.log(props.identifierVisible) props.setIdentifierVisible('') map.getLayers().forEach(function (layer, i) { //console.log(layer); //console.log(layer.get('id')); if (layer.get('id') === props.identifierVisible) { //map.removeLayer(layer) //console.log(layer) console.log(layer.getVisible()) layer.setVisible(!layer.getVisible()) } }); } }, [props.identifierVisible]) */ useEffect(() => { if (peta) { //sourceBbox.clear() var wms = peta.getLayers().getArray(); //console.log(wms) var _source = wms[i_bbox].getSource() // console.log(_source) //console.log(props.bbox) _source.clear(); var feature = new Feature({ geometry: new Polygon([ [ [ props.bbox[0].toFixed(2), props.bbox[1].toFixed(2) ], [ props.bbox[2].toFixed(2), props.bbox[1].toFixed(2) ], [ props.bbox[2].toFixed(2), props.bbox[3].toFixed(2) ], [ props.bbox[0].toFixed(2), props.bbox[3].toFixed(2) ], [ props.bbox[0].toFixed(2), props.bbox[1].toFixed(2) ] ] ]), name: 'Bbox' }); //vectorSource.addFeature(); _source.addFeature(feature) //peta.getView().fit(feature.getGeometry()) //map.getView().animate({zoom: map.getView().getZoom() - 0.5}); } }, [props.bbox]) useEffect(() => { if (peta) { var wms = peta.getLayers().getArray(); //console.log(wms) var _sourceCountry = wms[i_country].getSource() _sourceCountry.clear() //console.log(props.country) if (props.country) { var feature = new Feature({ geometry: new MultiPolygon(props.country.coordinates), name: 'country' }) //console.log(feature) _sourceCountry.addFeature(feature) } //map.getView().fit(feature.getGeometry()) //map.getView().animate({zoom: map.getView().getZoom() - 0.5}); } }, [props.country]) useEffect(() => { if (peta) { //alert(props.drawBbox) //props.setDrawBbox(props.drawBbox) //alert(draw) if (props.drawBbox) { var dragBox = new DragBox({ //condition: platformModifierKeyOnly, }); peta.addInteraction(dragBox); // clear selection when drawing a new box and when clicking on the map var wms = peta.getLayers().getArray(); //console.log(wms) var _sourceBbox = wms[i_bbox].getSource() var _sourceCountry = wms[i_country].getSource() dragBox.on('boxstart', function () { _sourceCountry.clear(); _sourceBbox.clear(); }); dragBox.on('boxend', function () { // features that intersect the box geometry are added to the // collection of selected features // if the view is not obliquely rotated the box geometry and // its extent are equalivalent so intersecting features can // be added directly to the collection //var rotation = map.getView().getRotation(); //var oblique = rotation % (Math.PI / 2) !== 0; //var candidateFeatures = oblique ? [] : selectedFeatures; var bbox = dragBox.getGeometry().getExtent(); //map.getView().fit(bbox) //map.getView().animate({zoom: map.getView().getZoom() - 0.5}); props.setAreaName('User Drawing Bbox') props.setBbox([bbox[0], bbox[1], bbox[2], bbox[3]]) props.setBboxLabel('[' + bbox[0].toFixed(2) + ', ' + bbox[1].toFixed(2) + ', ' + bbox[2].toFixed(2) + ', ' + bbox[3].toFixed(2) + ']') props.setDrawBbox(false) props.setShowBbox(true) //vectorSource.forEachFeatureIntersectingExtent(extent, function (feature) { //candidateFeatures.push(feature); //}); // when the view is obliquely rotated the box extent will // exceed its geometry so both the box and the candidate // feature geometries are rotated around a common anchor // to confirm that, with the box geometry aligned with its // extent, the geometries intersect }); } else { peta.getInteractions().pop() } } }, [props.drawBbox, draw]) function updatePrint() { //console.log('aaaaa') if (peta) { var exportOptions = { filter: function (element) { var className = element.className || ''; return ( className.indexOf('ol-control') === -1 || className.indexOf('ol-scale') > -1 || (className.indexOf('ol-attribution') > -1 && className.indexOf('ol-uncollapsible')) ); }, }; var obj = peta.getTargetElement() exportOptions.width = obj.clientWidth; exportOptions.height = obj.clientHeight; //peta.once('rendercomplete', function () { var wms = peta.getLayers().getArray(); var _source = wms[i_magic].getSource(); _source.clear(); //console.log(_source) var bbox = peta.getView().calculateExtent(peta.getSize()); //console.log(bbox) var feature = new Feature({ geometry: new Polygon([ [ [ bbox[0], bbox[1] ], [ bbox[2], bbox[1] ], [ bbox[2], bbox[3] ], [ bbox[0], bbox[3] ], [ bbox[0], bbox[1] ] ] ]), name: 'BboxMagic' }); //vectorSource.addFeature(); _source.addFeature(feature) domtoimage.toPng(obj, exportOptions) .then(function (dataURL) { //var link = document.getElementById('image-download'); //link.href = dataURL; //link.click(); setCapture(dataURL) setHeight(obj.clientHeight); document.body.style.cursor = 'auto'; }); var leg = document.getElementById('preview-legend'); //console.log(leg) //console.log(leg.clientWidth) //console.log(leg.clientHeight) const _a4PageSize = { height: leg.clientHeight, width: 250 } setTimeout(function () { domtoimage .toPng(leg, _a4PageSize) .then(dataUrl => { //console.log(dataUrl) setCLegend(dataUrl); }).catch(err => { console.log(err) }); }, 800); } } function switch_basemap() { var _source; var layers = peta.getLayers().getArray() //console.log(map.getControls()) var controllers = peta.getControls().getArray() //console.log(controllers) //console.log(overviewMapControl.getOverviewMap().getLayers().getArray()) //var layers_ = overviewMapControl.getOverviewMap().getLayers().getArray() var layers_ = controllers[4].getOverviewMap().getLayers().getArray() var coloring = gcolor2 switch (props.provider) { case 'osm': _source = new OSMSource() break; case 'gray': _source = new XYZSource({ url: Config.proxy_domain + "https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles World Light Gray © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }) break; case 'ocean': _source = new XYZSource({ url: Config.proxy_domain + "https://server.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles Ocean © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/Ocean_Basemap/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }); break; case 'topography': _source = new XYZSource({ url: Config.proxy_domain + "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles World Topo © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }); break; case 'street': _source = new XYZSource({ url: Config.proxy_domain + "https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles World Street © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }); break; case 'natgeo': _source = new XYZSource({ url: Config.proxy_domain + "https://server.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles NatGeo World © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/NatGeo_World_Map/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }); break; case 'imagery': _source = new XYZSource({ url: Config.proxy_domain + "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles Imagery © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }); coloring = gcolor1; break; case 'stamen': _source = new StamenSource({ layer: 'watercolor', }) break; default: //tileRef.current.setUrl(urlBasemap); //setAttribution(osmContrib); break; } //console.log(layers) //console.log(layers[0]) //peta.getLayers().removeAt(i_graticule) var newGraticule = new Graticule({ // the style to use for the lines, optional. strokeStyle: new Stroke({ color: coloring, //'rgba(255,120,0,0.9)', width: 1, lineDash: [0.5, 4], }), showLabels: true, wrapX: false, }) peta.getLayers().setAt(i_graticule, newGraticule) layers[i_basemap].setSource(_source); //console.log(layers[0]) //console.log(layers_[0]) layers_[i_basemap].setSource(_source); } function load_wms_legend() { if (typeof (props.mapLayer) !== 'undefined') { //var items=props.presensiDataLast.data; if (props.mapLayer !== null) { if (props.mapLayer.length > 0) { return props.mapLayer.map((row, index) => { //console.log(row) //console.log(row.layer) var wmsSource = new ImageWMSSource({ url: Config.proxy_domain + row.url, params: { 'LAYERS': row.layer }, ratio: 1, serverType: row.server, crossOrigin: 'Anonymous' }); //var resolution = peta.getView().getResolution(); //console.log(resolution) var graphicUrl = wmsSource.getLegendUrl(props.resolution); //console.log(graphicUrl) if (row.layer) { //<img src={main + "?" + request} alt="alt" /> return <Row className="mr-0" key={index}> <Col xs={10} className="ml-2 mt-1 font-11"><b>{row.title}</b> <br /> <img crossOrigin="Anonymous" referrerPolicy="origin" src={graphicUrl} alt={row.title} onLoad={() => { console.log(this) }} /> </Col> </Row> } else { if (row.tipe === 'zip') { return <Row className="mr-0" key={index}> <Col xs={10} className="ml-2 mt-1 font-11"><b>{row.title}</b> <br /> <div className="border bg-light border-primary" style={{ width: "20px", height: "20px" }}> </div> </Col> </Row> } else { return null } } }) } else { return <p className="pl-2 font-11">no legend</p> } } else { return <p className="pl-2 font-11">no legend</p> } } else { return <p className="pl-2 font-11">no legend</p> } } function handlingLegend() { setLegend(!legend) var leg = document.getElementById('preview-legend'); console.log(leg) //console.log(leg.clientWidth) //console.log(leg.clientHeight) const _a4PageSize = { height: 300, width: 250 } setTimeout(function () { domtoimage .toPng(leg, _a4PageSize) .then(dataUrl => { //console.log(dataUrl) setCLegend(dataUrl); }).catch(err => { console.log(err) }); }, 800); } function handleFillColor(val) { setFillColor(val) var r = parseInt(val.substr(1, 2), 16) var g = parseInt(val.substr(3, 2), 16) var b = parseInt(val.substr(5, 2), 16) var fill_color_rgba = document.getElementById('fill_color_rgba'); var a = document.getElementById('fill_color_alpha'); fill_color_rgba.innerHTML = "rgba(" + r + ", " + g + ", " + b + ", " + a.value + ")"; } function handleFillColorAlpha(val) { setFillColorAlpha(val) var fill_color = document.getElementById('fill_color'); var rgb = fill_color.value; var r = parseInt(rgb.substr(1, 2), 16) var g = parseInt(rgb.substr(3, 2), 16) var b = parseInt(rgb.substr(5, 2), 16) var fill_color_rgba = document.getElementById('fill_color_rgba'); fill_color_rgba.innerHTML = "rgba(" + r + ", " + g + ", " + b + ", " + val + ")"; } var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; function handleMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: //setPos3(e.clientX); //setPos4(e.clientY); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = handleMouseUp; // call a function whenever the cursor moves: document.onmousemove = handleMouseMove; //console.log(e) } function handleMouseMove(e) { //const { isDragging } = this.state; /* if (!isDragging) { return; } //event.persist(); console.log(event); */ e = e || window.event; e.preventDefault(); // calculate the new cursor position: //var p1 = pos3 - e.clientX; //var p2 = pos4 - e.clientY; //setPos3(e.clientX); //setPos4(e.clientY); // set the element's new position: //elmnt.style.top = (elmnt.offsetTop - p2) + "px"; //elmnt.style.left = (elmnt.offsetLeft - p1) + "px"; pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: var elmnt = e.target.parentNode; //alert('handleMouseMove') //console.log(elmnt.id); if (elmnt.id === "print") { if ((elmnt.offsetTop - pos2) > 0) elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; //if(elmnt.top === "0px") // elmnt.style.top = "10px"; if ((elmnt.offsetLeft - pos1) > 0) elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } } function handleMouseUp() { //window.removeEventListener('mousemove', handleMouseMove); //window.removeEventListener('mouseup', handleMouseUp); document.onmouseup = null; document.onmousemove = null; } return ( <> <div id='map-container' className="map" /> <div id="measurement" className={measurement ? 'show' : 'hide'} > <div className="bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Measurement<button type="button" className="close" id="close_measurement"><span aria-hidden="true" className="text-secondary">×</span><span className="sr-only">Close</span></button></div> <Row className="mx-3 my-3"> <Col className="px-1 font-11"> <form className="form-inline"> <label htmlFor="type">Measurement type &nbsp;</label> <select id="type"> <option value="length">Length (LineString)</option> <option value="area">Area (Polygon)</option> </select> </form> </Col> </Row> <Row className='show px-1 pt-2'> <Col className=""> <Button size="sm" variant="secondary" className="py-0 font-11" block id="finish_measurement">Start Measurement</Button> <Button size="sm" variant="secondary" className="py-0 font-11" block id="clear_measurement">Clear Measurement</Button> </Col> </Row> </div> <div id="identifying" className={identify ? 'show' : 'hide'} > <div className="bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Identify<button type="button" className="close" id="close_identifying"><span aria-hidden="true" className="text-secondary">×</span><span className="sr-only">Close</span></button></div> <Row className="mx-2 mt-2"> <Col className="px-1 font-11"> {alertIdentify ? <Button variant="outline-success" className="py-0 font-11 mb-2" disabled><b>Feature Identification is ACTIVE</b></Button> : <Button variant="outline-danger" className="py-0 font-11 mb-2" disabled><b>Feature Identification is NOT ACTIVE</b></Button>} <span>Layer (Top-Visible): <br /><b><span id="name_layer">None</span></b></span> <Button size="sm" variant="secondary" className="py-0 font-11 mt-2" block id="finish_identifying">Start Identifying</Button> </Col> </Row> </div> <div id="drawing" className={drawingO ? 'show' : 'hide'} > <div className="bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Drawing<button type="button" className="close" id="close_drawing"><span aria-hidden="true" className="text-secondary">×</span><span className="sr-only">Close</span></button></div> <Row className="mx-3 my-3"> <Col className="px-1 font-11"> <form className="form-inline"> <label htmlFor="type2">Geometry type: &nbsp;</label> <select id="type2"> <option value="Point">Point</option> <option value="LineString">LineString</option> <option value="Polygon">Polygon</option> </select> </form> </Col> </Row> <Row className="mx-3 my-3"> <Col className="px-1 font-11"> <span><b>Styling Symbology</b></span> <form className="form"> <label htmlFor="point_color">Point Color: &nbsp; </label> <input type="color" id="point_color" name="point_color" value={pointColor} onChange={(e) => setPointColor(e.target.value)} /> <br /> <label htmlFor="stroke_color">Stroke Color: &nbsp;</label> <input type="color" id="stroke_color" name="stroke_color" value={strokeColor} onChange={(e) => setStrokeColor(e.target.value)} /> <br /> <label htmlFor="stroke_width">Stroke Width: &nbsp;</label> <select id="stroke_width" value={strokeWidth} onChange={(e) => setStrokeWidth(e.target.value)}> <option value="0.5">0.5</option> <option value="1">1</option> <option value="1.5">1.5</option> <option value="2">2</option> <option value="2.5">2.5</option> </select> <br /> <label htmlFor="fill_color">Fill Color: &nbsp; <span id="fill_color_rgba">rgba(255, 255, 255, 1)</span></label> <br /> <input type="color" id="fill_color" name="fill_color" value="#ffffff" value={fillColor} onChange={(e) => handleFillColor(e.target.value)} /> <input className="ml-2" type="range" min="0" max="1" step="0.01" id="fill_color_alpha" value={fillColorAlpha} onChange={(e) => handleFillColorAlpha(e.target.value)} /> </form> </Col> </Row> <Row className='show px-1 pt-2'> <Col className=""> <Button size="sm" variant="secondary" className="py-0 font-11" block id="finish_drawing">Start Drawing</Button> </Col> </Row> </div> <div id="popup" className="ol-popup"> <a href="#" id="popup-closer" className="ol-popup-closer"></a> <div id="popup-content" ></div> </div> <div id="print" className={props.printing ? 'show' : 'hide'} > <div onMouseDown={handleMouseDown} className="move-cursor bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Print<button type="button" className="close" id="close_print"><span aria-hidden="true" className="text-secondary">×</span><span className="sr-only">Close</span></button></div> <Row className="px-3"> <Col className="pt-1 px-1" id="attribute-content"> <Form.Control type="text" size="sm" placeholder="Title" className="font-11" value={title} onChange={(e) => setTitle(e.target.value)}></Form.Control> </Col> </Row> <Row className="px-3"> <Col lg={9} className="pt-1 px-1"> <img id="preview" width="100%" style={{ border: "solid 1px #000", maxHeight: "250px" }} src={capture} alt="preview" /> </Col> <Col lg={3} className="pt-1 px-1"> <p className="font-11 mb-1">Legend</p> <div id="preview-legend" style={{ maxWidth: "200px", overflowX: "hidden", maxHeight: "220px", overflowY: "hidden" }} > { legend ? load_wms_legend() : "" } </div> </Col> </Row> <Row className="px-3"> <Col lg={3} className="pt-1 px-1" id="attribute-content"> <Form.Group controlId="formBasicCheckbox" className="pl-1"> <Form.Check type="checkbox" label="Legend" checked={legend} onChange={() => handlingLegend()} /> </Form.Group> <Form.Control as="select" size="sm" className="mt-2 font-11" value={size} onChange={(e) => setSize(e.target.value)}> <option value="A4">A4</option> </Form.Control> <Form.Control as="select" size="sm" className="mt-2 font-11" value={orientation} onChange={(e) => setOrientation(e.target.value)}> <option value="landscape">Landscape</option> </Form.Control> </Col> <Col lg={6} className="pt-1 px-1" id="attribute-content"> <Form.Control as="textarea" rows={5} placeholder="Description" className="font-11" value={description} onChange={(e) => setDescription(e.target.value)}></Form.Control> </Col> <Col lg={3} className="pt-2 px-1" id="attribute-content"> <Button size="sm" variant="secondary" block className="font-11 py-0" id="export-pdf">Recapture Map</Button> <PDFDownloadLink document={<NewPDFPages mapLayer={props.mapLayer} height={height} legend={legend} size={size} orientation={orientation} data={capture} dataClegend={clegend} title={title} description={description} />} fileName="CiforMap.pdf" className="font-11 py-0 btn btn-secondary btn-block btn-sm"> {({ blob, url, loading, error }) => loading ? 'updating document..' : 'Download pdf' } </PDFDownloadLink> <Button size="sm" variant="secondary" block className="font-11 py-0" onClick={() => props.setPrinting(false)}>Cancel</Button> </Col> </Row> </div> </> ) }<file_sep> import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import logo_cifor from './logo/CIFOR_green_vlr.png'; import logo_fta from './logo/logo-cgiarfta.png'; export default function Copyright(props) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; function handleMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: //setPos3(e.clientX); //setPos4(e.clientY); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = handleMouseUp; // call a function whenever the cursor moves: document.onmousemove = handleMouseMove; //console.log(e) } function handleMouseMove(e) { //const { isDragging } = this.state; /* if (!isDragging) { return; } //event.persist(); console.log(event); */ e = e || window.event; e.preventDefault(); // calculate the new cursor position: //var p1 = pos3 - e.clientX; //var p2 = pos4 - e.clientY; //setPos3(e.clientX); //setPos4(e.clientY); // set the element's new position: //elmnt.style.top = (elmnt.offsetTop - p2) + "px"; //elmnt.style.left = (elmnt.offsetLeft - p1) + "px"; pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: var elmnt = e.target.parentNode; //alert('handleMouseMove') //console.log(elmnt.id); if (elmnt.id === "copyright") { if ((elmnt.offsetTop - pos2) > 0) elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; //if(elmnt.top === "0px") // elmnt.style.top = "10px"; if ((elmnt.offsetLeft - pos1) > 0) elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } } function handleMouseUp() { //window.removeEventListener('mousemove', handleMouseMove); //window.removeEventListener('mouseup', handleMouseUp); document.onmouseup = null; document.onmousemove = null; } return ( <div id="copyright" className={props.copyright ? 'show' : 'hide'} > <div onMouseDown={handleMouseDown} className="move-cursor bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Copyright<button type="button" className="close" onClick={() => props.setCopyright(false)}><span aria-hidden="true" className="text-secondary">×</span><span className="sr-only">Close</span></button></div> <Row className="mx-3 my-3"> <Col xs={3} className="pt-2 px-1" id="attribute-content"> <img src={logo_cifor} alt="cifor logo" width="40px" className="pt-1 logo_cifor unselectable" /> <br /><br /> <img src={logo_fta} alt="fta logo" width="120px" className="unselectable" /> </Col> <Col xs={9} className="pt-1 px-1" id="attribute-content"> <p className="text-secondary font-11"> The CGIAR Research Program on Forests, Trees and Agroforestry (FTA) is the world's largest research for development program to enhance the role of forests, trees and agroforestry in sustainable development and food security and to address climate change. CIFOR leads FTA in partnership with ICRAF, the Alliance of Bioversity International and CIAT, CATIE, CIRAD, INBAR and TBI </p> </Col> </Row> <p className="text-center text-secondary font-11"> © 2021 @ CGIAR Research Program - Forests, Trees and Agroforestry </p> </div> ); }<file_sep>import 'ol/ol.css'; import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css' import { useState, useEffect } from 'react' import Zoom from 'react-reveal/Zoom' import Slide from 'react-reveal/Slide' import Fade from 'react-reveal/Fade' import Container from 'react-bootstrap/Container' import Row from 'react-bootstrap/Row' import Col from 'react-bootstrap/Col' import TopMenu from './TopMenu' import Mapviewer from './Mapviewer' import Sidebar from './Sidebar' import Footer from './Footer' import Copyright from './windows/Copyright' import Area from './windows/Area' import Basemap from './windows/Basemap' import Browse from './windows/Browse' import Upload from './windows/Upload.js'; import Legend from './windows/Legend.js'; import Theme from './windows/Theme.js'; import TableAttribute from './windows/TableAttribute.js'; import Metadata from './windows/MetadataFrontend.js'; import Config from './config.json'; function App() { const url_list_harvesting = Config.api_domain + "/harvestings/bbox/"; // var url = 'http://localhost:8004/geoportal/api/harvestings/bbox/-133044556.246885/-20037508.342789/133044555.799350/20037508.342789' const [copyright, setCopyright] = useState(false); const [area, setArea] = useState(false); const [drawBbox, setDrawBbox] = useState(false); const [basemap, setBasemap] = useState(false); const [provider, setProvider] = useState('imagery'); const [legend, setLegend] = useState(false); const [upload, setUpload] = useState(false); const [printing, setPrinting] = useState(false); const [mapLayer, setMapLayer] = useState([]); const [browse, setBrowse] = useState(false); const [bbox, setBbox] = useState([-133044556.24688484, -20037508.342789244, 133044555.79934952, 20037508.342789244]); const [bboxLabel, setBboxLabel] = useState('[' + bbox[0].toFixed(2) + ', ' + bbox[1].toFixed(2) + ', ' + bbox[2].toFixed(2) + ', ' + bbox[3].toFixed(2) + ']'); const [areaName, setAreaName] = useState('All Continents'); const [resolution, setResolution] = useState(); const [country, setCountry] = useState(); const [theme, setTheme] = useState(true); const [buffer, setBuffer] = useState([]); const [zoomTo, setZoomTo] = useState(); const [showBbox, setShowBbox] = useState(false); const [showArea, setShowArea] = useState(false); const [performZoom, setPerformZoom] = useState(false); const [showTable, setShowTable] = useState(false); const [showMetadata, setShowMetadata] = useState(false); const [identifierMetadata, setIdentifierMetadata] = useState(""); const [identifierAttribute, setIdentifierAttribute] = useState(""); const [identifierDelete, setIdentifierDelete] = useState(""); const [identifierVisible, setIdentifierVisible] = useState(""); const [dataAll, setDataAll] = useState(); /* const response = await fetch(url); const total = Number(response.headers.get('content-length')); const reader = response.body.getReader(); let bytesReceived = 0; while (true) { const result = await reader.read(); if (result.done) { console.log('Fetch complete'); break; } bytesReceived += result.value.length; console.log('Received', bytesReceived, 'bytes of data so far'); } */ /* async function f() { return Promise.resolve(1); } f().then(alert) async function f() { /* let promise = new Promise((resolve, reject) => { setTimeout(() => resolve("done!"), 1000) }); / const response = await fetch(url) let result = await response; // wait until the promise resolves (*) //alert(result); // "done!" console.log(result); } f(); */ useEffect(() => { async function loadDataset() { /* const requestOptions = { method: 'GET', headers: { 'Content-Type': 'application/json', 'Authorization': token } }; */ const response = await fetch(url_list_harvesting + bbox[0].toFixed(6) + "/" + bbox[1].toFixed(6) + "/" + bbox[2].toFixed(6) + "/" + bbox[3].toFixed(6)) var json = await response.json(); if (response.status === 200) { //console.log(json.data) setDataAll(json.data);//.sort((a, b) => (a.title > b.title) ? 1 : -1)); const ele = document.getElementById('ipl-progress-indicator') if (ele) { // fade out ele.classList.add('available') setTimeout(() => { // remove from DOM ele.outerHTML = '' }, 1000) } } else { console.log(response.status) } } loadDataset(); }, [url_list_harvesting]); function viewTable(id) { setShowTable(true) setIdentifierAttribute(id) //alert(id) } function viewMetadata(id) { setShowMetadata(true) setIdentifierMetadata(id) //alert(id) } function zoomToMap(id) { //setShowMetadata(true) //setIdentifierMetadata(id) //alert(id); setZoomTo(id); } function handlingUnduhKML(e, url) { window.open(url) //window.location.href = url; return } function deleteDataset(id) { //setDataset(oldArray => [...oldArray, newElement]); //console.log(dataset); const layers = mapLayer.slice(); console.log(id); //console.log(map) //map.eachLayer(function(layer){ //if(layer.options.id === id) //map.removeLayer(layer) //}); //var index = mapLayer.findIndex(x => x.id === id); //setDataset(mapLayer.slice(index, 1)); //console.log(typeof(id)) //console.log(typeof(dataset.slice()[0].id)) //console.log(dataset.filter(item => item.id !== id)) setMapLayer(mapLayer.filter(item => item.id !== id)); setIdentifierDelete(id) } function handleVisible(id) { //setIdentifierVisible(id); const data = mapLayer.slice(); //console.log(data[0]); var index = mapLayer.findIndex(x => x.id === id); //console.log(index); data[index].visible = !data[index].visible setMapLayer(data); } function handleOpacity(id, val) { //setIdentifierVisible(id); const data = mapLayer.slice(); //console.log(data[0]); var index = mapLayer.findIndex(x => x.id === id); //console.log(index); data[index].opacity = val setMapLayer(data); } // setPerformZoom={(e) => setPerformZoom(e)} setCountry={(e) => setCountry(e)} setWaiter={(e) => setWaiter(e)} // setBbox={(e) => setBbox(e)} setBboxLabel={(e) => setBboxLabel(e)} setAreaName={(e) => setAreaName(e)} setShowArea={(e) => setShowArea(e)} // <Legend legend={legend} resolution={resolution} mapLayer={mapLayer} setLegend={(e) => setLegend(e)} /> // <Browse viewMetadata={(e) => viewMetadata(e)} setWaiter={(e) => setWaiter(e)} bbox={bbox} browse={browse} setBrowse={(e) => setBrowse(e)} setArea={(e) => setArea(e)} areaName={areaName} setMapLayer={(e) => setMapLayer(e)} zoomToMap={(e) => zoomToMap(e)} /> // <Upload upload={upload} setUpload={(e) => setUpload(e)} setBuffer={(e) => setBuffer(e)} /> /* <Browse viewMetadata={(e) => viewMetadata(e)} zoomToMap={(e) => zoomToMap(e)} /> */ return ( <Container fluid className="bg-white"> <Copyright copyright={copyright} setCopyright={(e) => setCopyright(e)} /> <Area setPerformZoom={(e) => setPerformZoom(e)} setCountry={(e) => setCountry(e)} area={area} setArea={(e) => setArea(e)} setBbox={(e) => setBbox(e)} setBboxLabel={(e) => setBboxLabel(e)} setAreaName={(e) => setAreaName(e)} setShowArea={(e) => setShowArea(e)} /> <Basemap basemap={basemap} setBasemap={(e) => setBasemap(e)} provider={provider} setProvider={(e) => setProvider(e)} /> <Browse areaName={areaName} bbox={bbox} browse={browse} dataAll={dataAll} setBrowse={(e) => setBrowse(e)} setArea={(e) => setArea(e)} setMapLayer={(e) => setMapLayer(e)} viewMetadata={(e) => viewMetadata(e)} zoomToMap={(e) => zoomToMap(e)} /> <Upload upload={upload} setUpload={(e) => setUpload(e)} setBuffer={(e) => setBuffer(e)} /> <Legend legend={legend} resolution={resolution} mapLayer={mapLayer} setLegend={(e) => setLegend(e)} /> <Theme theme={theme} setTheme={(e) => setTheme(e)} /> <TableAttribute identifierAttribute={identifierAttribute} showTable={showTable} setShowTable={(e) => setShowTable(e)} /> <Metadata identifierMetadata={identifierMetadata} showMetadata={showMetadata} setShowMetadata={(e) => setShowMetadata(e)} /> <Fade top delay={1500} duration={2000}> <TopMenu /> </Fade> <Row className="main"> <Col lg={10} className="p-0" style={{ overFlowX: "hidden" }}> <Zoom duration={3000}> <Mapviewer provider={provider} printing={printing} setPrinting={(e) => setPrinting(e)} buffer={buffer} bbox={bbox} setBbox={(e) => setBbox(e)} setBuffer={(e) => setBuffer(e)} mapLayer={mapLayer} setMapLayer={(e) => setMapLayer(e)} zoomTo={zoomTo} setZoomTo={(e) => setZoomTo(e)} setShowBbox={(e) => setShowBbox(e)} showArea={showArea} setShowArea={(e) => setShowArea(e)} showBbox={showBbox} country={country} performZoom={performZoom} setPerformZoom={(e) => setPerformZoom(e)} drawBbox={drawBbox} setDrawBbox={(e) => setDrawBbox(e)} setBboxLabel={(e) => setBboxLabel(e)} setAreaName={(e) => setAreaName(e)} setResolution={(e) => setResolution(e)} identifierDelete={identifierDelete} identifierVisible={identifierVisible} setIdentifierDelete={(e) => setIdentifierDelete(e)} setIdentifierVisible={(e) => setIdentifierVisible(e)} /> </Zoom> </Col> <Col lg={2}> <Fade right delay={2000}> <Sidebar areaName={areaName} bboxLabel={bboxLabel} mapLayer={mapLayer} setArea={(e) => setArea(e)} setBasemap={(e) => setBasemap(e)} setLegend={(e) => setLegend(e)} setPrinting={(e) => setPrinting(e)} setBrowse={(e) => setBrowse(e)} setUpload={(e) => setUpload(e)} setTheme={(e) => setTheme(e)} handlingUnduhKML={(e, b) => handlingUnduhKML(e, b)} viewTable={(e) => viewTable(e)} viewMetadata={(e) => viewMetadata(e)} zoomToMap={(e) => zoomToMap(e)} deleteDataset={(e) => deleteDataset(e)} handleVisible={(e) => handleVisible(e)} handleOpacity={(e,b) => handleOpacity(e, b)} showBbox={showBbox} setShowBbox={(e) => setShowBbox(e)} showArea={showArea} setShowArea={(e) => setShowArea(e)} country={country} performZoom={performZoom} setPerformZoom={(e) => setPerformZoom(e)} drawBbox={drawBbox} setDrawBbox={(e) => setDrawBbox(e)} /> </Fade> </Col> </Row> <Fade delay={3500}> <Footer setCopyright={(e) => setCopyright(e)} /> </Fade> </Container> ); } export default App; <file_sep>import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import Button from 'react-bootstrap/Button'; import { useState, useMemo, useEffect, useCallback, useRef } from 'react'; import { Trash, PieChart, Table, Eye, EyeSlash } from 'react-bootstrap-icons'; import Analysis from './Analysis.js'; import TableView from './Table.js'; import { Map, View } from 'ol'; import { Image as ImageLayer, Tile as TileLayer, Vector as VectorLayer } from 'ol/layer'; import { OSM as OSMSource, ImageArcGISRest, TileArcGISRest, Stamen as StamenSource, XYZ as XYZSource, ImageWMS as ImageWMSSource, Vector as VectorSource } from 'ol/source/'; import { fromLonLat } from 'ol/proj'; import { Attribution, Control, ScaleLine, ZoomSlider, Zoom, Rotate, MousePosition, OverviewMap, defaults as defaultControls, ZoomToExtent } from 'ol/control' export default function Theme(props) { const center = [-2, 106] const zoom = 8 const urlBasemap = "https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}"; const osmContrib = 'ArcGIS World Topo Map'; const [title, setTitle] = useState('title'); const [analysis, setAnalysis] = useState(false); const [table, setTable] = useState(false); const [layer1, setLayer1] = useState(true); const [layer2, setLayer2] = useState(true); const [layer3, setLayer3] = useState(true); const [layer4, setLayer4] = useState(true); const [layer5, setLayer5] = useState(true); const [layer6, setLayer6] = useState(true); const [layer7, setLayer7] = useState(true); const urlCanopyTile = 'https://forests2020.ipb.ac.id/arcgis/rest/services/Ecosystem_CanopyCover/IndonesiaCanopyCover2018/MapServer' const urlPaddyTile = 'https://forests2020.ipb.ac.id/arcgis/rest/services/Ecosystem_CommodityDistribution/Paddy_Distribution_2019/MapServer' const urlCoffeeDistributionTile = 'https://forests2020.ipb.ac.id/arcgis/rest/services/Ecosystem_CommodityDistribution/Coffe_Distribution_2019/MapServer' const urlShake = 'https://gis.bmkg.go.id/arcgis/rest/services/Shakemap/Shakemap_20170424010111/MapServer' const urlForest = 'https://forests2020.ipb.ac.id/arcgis/rest/services/Ecosystem_Forest_KLHK/Primary_Swamp_Forest/MapServer' const oilPalm = 'https://forests2020.ipb.ac.id/arcgis/rest/services/UNDP/OilPalmAustin/MapServer' const alertDevegetation = 'https://forests2020.ipb.ac.id/arcgis/rest/services/Ecosystem_Devegetation/Devegetation_2019/MapServer' const tileRef = useRef(); //<TileLayer ref={tileRef} url={urlBasemap} attribution={attribution} /> const [map, setMap] = useState(null); /* const displayMap2 = useMemo( () => ( <div id='map-thematic' /> ), [] ) */ useEffect(() => { init_map(); props.setTheme(false) const requestOptions = { method: 'GET' }; fetch(urlCanopyTile + "/legend?f=json", requestOptions).then(res => res.json()).then(data => { //console.log(data) //console.log(data.layers) //console.log(data.layers[0]) //console.log(data.layers[0].legend[0]) //console.log('data:'+data.layers[0].legend[0].contentType+';base64,'+data.layers[0].legend[0].imageData) var div = document.getElementById('canopy_legend'); for (var l in data.layers) { //console.log(data.layers[l]) for (var y in data.layers[l].legend) { //console.log(data.layers[l].legend[y]) var img = document.createElement('img'); img.src = 'data:' + data.layers[l].legend[y].contentType + ';base64,' + data.layers[l].legend[y].imageData; img.width = data.layers[l].legend[y].width; img.height = data.layers[l].legend[y].height; var div2 = document.createElement('div'); var span = document.createElement('span'); span.innerHTML = data.layers[l].legend[y].label; div2.appendChild(img); div2.appendChild(span); div.append(div2) } } }) // fetch(urlPaddyTile + "/legend?f=json", requestOptions).then(res => res.json()).then(data => { //console.log(data) //console.log(data.layers) //console.log(data.layers[0]) //console.log(data.layers[0].legend[0]) //console.log('data:'+data.layers[0].legend[0].contentType+';base64,'+data.layers[0].legend[0].imageData) var div = document.getElementById('paddy_legend'); for (var l in data.layers) { //console.log(data.layers[l]) for (var y in data.layers[l].legend) { //console.log(data.layers[l].legend[y]) var img = document.createElement('img'); img.src = 'data:' + data.layers[l].legend[y].contentType + ';base64,' + data.layers[l].legend[y].imageData; img.width = data.layers[l].legend[y].width; img.height = data.layers[l].legend[y].height; var div2 = document.createElement('div'); var span = document.createElement('span'); span.innerHTML = data.layers[l].legend[y].label; div2.appendChild(img); div2.appendChild(span); div.append(div2) } } }) fetch(urlCoffeeDistributionTile + "/legend?f=json", requestOptions).then(res => res.json()).then(data => { //console.log(data) //console.log(data.layers) //console.log(data.layers[0]) //console.log(data.layers[0].legend[0]) //console.log('data:'+data.layers[0].legend[0].contentType+';base64,'+data.layers[0].legend[0].imageData) var div = document.getElementById('coffee_legend'); for (var l in data.layers) { //console.log(data.layers[l]) for (var y in data.layers[l].legend) { //console.log(data.layers[l].legend[y]) var img = document.createElement('img'); img.src = 'data:' + data.layers[l].legend[y].contentType + ';base64,' + data.layers[l].legend[y].imageData; img.width = data.layers[l].legend[y].width; img.height = data.layers[l].legend[y].height; var div2 = document.createElement('div'); var span = document.createElement('span'); span.innerHTML = data.layers[l].legend[y].label; div2.appendChild(img); div2.appendChild(span); div.append(div2) } } }) fetch(urlShake + "/legend?f=json", requestOptions).then(res => res.json()).then(data => { //console.log(data) //console.log(data.layers) //console.log(data.layers[0]) //console.log(data.layers[0].legend[0]) //console.log('data:'+data.layers[0].legend[0].contentType+';base64,'+data.layers[0].legend[0].imageData) var div = document.getElementById('bmkg_legend'); for (var l in data.layers) { //console.log(data.layers[l]) for (var y in data.layers[l].legend) { //console.log(data.layers[l].legend[y]) var img = document.createElement('img'); img.src = 'data:' + data.layers[l].legend[y].contentType + ';base64,' + data.layers[l].legend[y].imageData; img.width = data.layers[l].legend[y].width; img.height = data.layers[l].legend[y].height; var div2 = document.createElement('div'); var span = document.createElement('span'); span.innerHTML = data.layers[l].legend[y].label; div2.appendChild(img); div2.appendChild(span); div.append(div2) } } }) fetch(urlForest + "/legend?f=json", requestOptions).then(res => res.json()).then(data => { //console.log(data) //console.log(data.layers) //console.log(data.layers[0]) //console.log(data.layers[0].legend[0]) //console.log('data:'+data.layers[0].legend[0].contentType+';base64,'+data.layers[0].legend[0].imageData) var div = document.getElementById('forest_legend'); for (var l in data.layers) { //console.log(data.layers[l]) if (l == 0) { for (var y in data.layers[l].legend) { //console.log(data.layers[l].legend[y]) var img = document.createElement('img'); img.src = 'data:' + data.layers[l].legend[y].contentType + ';base64,' + data.layers[l].legend[y].imageData; img.width = data.layers[l].legend[y].width; img.height = data.layers[l].legend[y].height; var div2 = document.createElement('div'); var span = document.createElement('span'); span.innerHTML = data.layers[l].legend[y].label; div2.appendChild(img); div2.appendChild(span); div.append(div2) } } } }) fetch(oilPalm + "/legend?f=json", requestOptions).then(res => res.json()).then(data => { //console.log(data) //console.log(data.layers) //console.log(data.layers[0]) //console.log(data.layers[0].legend[0]) //console.log('data:'+data.layers[0].legend[0].contentType+';base64,'+data.layers[0].legend[0].imageData) var div = document.getElementById('oil_legend'); for (var l in data.layers) { //console.log(data.layers[l]) for (var y in data.layers[l].legend) { //console.log(data.layers[l].legend[y]) var img = document.createElement('img'); img.src = 'data:' + data.layers[l].legend[y].contentType + ';base64,' + data.layers[l].legend[y].imageData; img.width = data.layers[l].legend[y].width; img.height = data.layers[l].legend[y].height; var div2 = document.createElement('div'); var span = document.createElement('span'); span.innerHTML = data.layers[l].legend[y].label; div2.appendChild(img); div2.appendChild(span); div.append(div2) } } }) fetch(alertDevegetation + "/legend?f=json", requestOptions).then(res => res.json()).then(data => { //console.log(data) //console.log(data.layers) //console.log(data.layers[0]) //console.log(data.layers[0].legend[0]) //console.log('data:'+data.layers[0].legend[0].contentType+';base64,'+data.layers[0].legend[0].imageData) var div = document.getElementById('devegetation_legend'); for (var l in data.layers) { //console.log(data.layers[l]) if (l == 0) { for (var y in data.layers[l].legend) { //console.log(data.layers[l].legend[y]) var img = document.createElement('img'); img.src = 'data:' + data.layers[l].legend[y].contentType + ';base64,' + data.layers[l].legend[y].imageData; img.width = data.layers[l].legend[y].width; img.height = data.layers[l].legend[y].height; var div2 = document.createElement('div'); var span = document.createElement('span'); span.innerHTML = data.layers[l].legend[y].label; div2.appendChild(img); div2.appendChild(span); div.append(div2) } } } }) }, []) var tile = new XYZSource({ url: "https://server.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}", attributions: 'Tiles Imagery © <a target="_blank" href="https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer">ArcGIS</a>', crossOrigin: "Anonymous" }); function init_map() { const peta = new Map({ target: 'map-thematic', layers: [ new TileLayer({ source: tile }), ], overlays: [], view: new View({ center: fromLonLat([117, -1]), zoom: 5 }), controls: defaultControls().extend([ new Attribution({ collapsed: false }), ]), }) /* tile.on('imageloadstart', function () { //progress.addLoading(); alert('processing') }); tile.on('imageloadend', function () { alert('loaded') }); tile.on('imageloaderror', function () { alert('error') }); */ var wmsCanopySource = new XYZSource({ url: urlCanopyTile + "/tile/{z}/{y}/{x}", crossOrigin: "Anonymous" }); var canopyLayer = new TileLayer({ source: wmsCanopySource, }) peta.addLayer(canopyLayer) var wmsPaddySource = new XYZSource({ url: urlPaddyTile + "/tile/{z}/{y}/{x}", crossOrigin: "Anonymous" }); var paddyLayer = new TileLayer({ source: wmsPaddySource, }) peta.addLayer(paddyLayer) var wmsCoffeeSource = new XYZSource({ url: urlCoffeeDistributionTile + "/tile/{z}/{y}/{x}", crossOrigin: "Anonymous" }); var coffeeLayer = new TileLayer({ source: wmsCoffeeSource, }) peta.addLayer(coffeeLayer) /* var wmsThematic2Source = new TileArcGISRest({ ratio: 1, params: {}, url: urlThematicTile, crossOrigin: 'anonymous' }) */ var wmsShakeSource = new ImageArcGISRest({ ratio: 1, params: {}, url: urlShake, crossOrigin: 'anonymous' }) var shakeLayer = new ImageLayer({ source: wmsShakeSource, }) peta.addLayer(shakeLayer) /* var wmsCoffeeSource = new ImageArcGISRest({ ratio: 1, params: {}, url: urlCoffee, crossOrigin: 'anonymous' }) var coffeeLayer = new ImageLayer({ source: wmsCoffeeSource, }) peta.addLayer(coffeeLayer) */ var wmsForestSource = new ImageArcGISRest({ ratio: 1, params: {}, url: urlForest, crossOrigin: 'anonymous' }) var forestLayer = new ImageLayer({ source: wmsForestSource, }) peta.addLayer(forestLayer) var wmsOilSource = new ImageArcGISRest({ ratio: 1, params: {}, url: oilPalm, crossOrigin: 'anonymous' }) var oilLayer = new ImageLayer({ source: wmsOilSource, }) peta.addLayer(oilLayer) var wmsDevegetationSource = new ImageArcGISRest({ ratio: 1, params: {}, url: alertDevegetation, crossOrigin: 'anonymous' }) var devegetationLayer = new ImageLayer({ source: wmsDevegetationSource, }) peta.addLayer(devegetationLayer) setMap(peta) } function openAnalysis(title) { setTitle(title) setAnalysis(true) } function openTable(title) { setTitle(title) setTable(true) } var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; function handleMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: //setPos3(e.clientX); //setPos4(e.clientY); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = handleMouseUp; // call a function whenever the cursor moves: document.onmousemove = handleMouseMove; //console.log(e) } function handleMouseMove(e) { //const { isDragging } = this.state; /* if (!isDragging) { return; } //event.persist(); console.log(event); */ e = e || window.event; e.preventDefault(); // calculate the new cursor position: //var p1 = pos3 - e.clientX; //var p2 = pos4 - e.clientY; //setPos3(e.clientX); //setPos4(e.clientY); // set the element's new position: //elmnt.style.top = (elmnt.offsetTop - p2) + "px"; //elmnt.style.left = (elmnt.offsetLeft - p1) + "px"; pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: var elmnt = e.target.parentNode; //alert('handleMouseMove') //console.log(elmnt.id); if (elmnt.id === "thematic") { //console.log('yes') if ((elmnt.offsetTop - pos2) > 0) elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; //if(elmnt.top === "0px") // elmnt.style.top = "10px"; if ((elmnt.offsetLeft - pos1) > 0) elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } } function handleMouseUp() { //window.removeEventListener('mousemove', handleMouseMove); //window.removeEventListener('mouseup', handleMouseUp); document.onmouseup = null; document.onmousemove = null; } function showHide(id){ //console.log(map.getLayers()) var layers = map.getLayers().getArray() if(id == 1){ setLayer1(!layers[id].getVisible()) } if(id == 2){ setLayer2(!layers[id].getVisible()) } if(id == 3){ setLayer3(!layers[id].getVisible()) } if(id == 4){ setLayer4(!layers[id].getVisible()) } if(id == 5){ setLayer5(!layers[id].getVisible()) } if(id == 6){ setLayer6(!layers[id].getVisible()) } layers[id].setVisible(!layers[id].getVisible()) } return ( <div id="thematic" className={props.theme ? 'show' : 'hide'} > <Analysis title={title} analysis={analysis} setAnalysis={(e) => setAnalysis(e)} /> <TableView title={title} table={table} setTable={(e) => setTable(e)} /> <div onMouseDown={handleMouseDown} className="move-cursor bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Thematic<button type="button" className="close" onClick={() => props.setTheme(false)}><span aria-hidden="true">×</span><span className="sr-only">Close</span></button></div> <Row className="px-3"> <Col className="py-2 pl-3 font-13 font-weight-bold"> Forecasting land cover and decision tool </Col> </Row> <Row className="px-3"> <Col lg={6} className="pt-1 px-1 font-11" style={{ maxHeight: "320px", overflowY: "auto", overflowX: "hidden" }} > <Row className="px-3 "> <Col lg={3} className="p-2 border bg-light">Data Source</Col> <Col lg={3} className="p-2 border bg-light">Data Name</Col> <Col lg={3} className="p-2 border bg-light">Legend</Col> <Col lg={3} className="p-2 border bg-light">Action</Col> </Row> <Row className="px-3"> <Col lg={3} className="p-2 border">IPB</Col> <Col lg={3} className="p-2 border">Canopy Cover</Col> <Col lg={3} className="p-2 border"><div id="canopy_legend"></div></Col> <Col lg={3} className="p-2 border"><Button variant="outline-secondary" onClick={() => showHide(1)} size="sm" className="px-1 py-0" >{layer1?<Eye size={12} />: <EyeSlash size={12} />}</Button></Col> </Row> <Row className="px-3"> <Col lg={3} className="p-2 border">IPB</Col> <Col lg={3} className="p-2 border">Paddy Field Distribution 2019</Col> <Col lg={3} className="p-2 border"><div id="paddy_legend"></div></Col> <Col lg={3} className="p-2 border"><Button variant="outline-secondary" onClick={() => showHide(2)} size="sm" className="px-1 py-0" >{layer2?<Eye size={12} />: <EyeSlash size={12} />}</Button> <Button variant="outline-secondary" onClick={() => openAnalysis('IPB - Paddy Field')} size="sm" className="px-1 py-0" ><PieChart size={12} /></Button> <Button variant="outline-secondary" onClick={() => openTable('IPB - Paddy Field')} size="sm" className="px-1 py-0"><Table size={12} /></Button></Col> </Row> <Row className="px-3"> <Col lg={3} className="p-2 border">IPB</Col> <Col lg={3} className="p-2 border">Coffee Distribution</Col> <Col lg={3} className="p-2 border"><div id="coffee_legend"></div></Col> <Col lg={3} className="p-2 border"><Button variant="outline-secondary" onClick={() => showHide(3)} size="sm" className="px-1 py-0" >{layer3?<Eye size={12} />: <EyeSlash size={12} />}</Button></Col> </Row> <Row className="px-3"> <Col lg={3} className="p-2 border">BMKG</Col> <Col lg={3} className="p-2 border">Shake Analysis</Col> <Col lg={3} className="p-2 border"><div id="bmkg_legend"></div></Col> <Col lg={3} className="p-2 border"><Button variant="outline-secondary" onClick={() => showHide(4)} size="sm" className="px-1 py-0" >{layer4?<Eye size={12} />: <EyeSlash size={12} />}</Button></Col> </Row> <Row className="px-3"> <Col lg={3} className="p-2 border">KLHK</Col> <Col lg={3} className="p-2 border">Primary Swamp Forest</Col> <Col lg={3} className="p-2 border"><div id="forest_legend"></div></Col> <Col lg={3} className="p-2 border"><Button variant="outline-secondary" onClick={() => showHide(5)} size="sm" className="px-1 py-0" >{layer5?<Eye size={12} />: <EyeSlash size={12} />}</Button></Col> </Row> <Row className="px-3"> <Col lg={3} className="p-2 border">Austin</Col> <Col lg={3} className="p-2 border">Oil Palm Distribution</Col> <Col lg={3} className="p-2 border"><div id="oil_legend"></div></Col> <Col lg={3} className="p-2 border"><Button variant="outline-secondary" onClick={() => showHide(6)} size="sm" className="px-1 py-0" >{layer6?<Eye size={12} />: <EyeSlash size={12} />}</Button></Col> </Row> <Row className="px-3"> <Col lg={3} className="p-2 border">IPB</Col> <Col lg={3} className="p-2 border">Devegetation Alert</Col> <Col lg={3} className="p-2 border"><div id="devegetation_legend"></div></Col> <Col lg={3} className="p-2 border"><Button variant="outline-secondary" onClick={() => showHide(7)} size="sm" className="px-1 py-0" >{layer7?<Eye size={12} />: <EyeSlash size={12} />}</Button></Col> </Row> </Col> <Col lg={6} className="pt-1 px-1" > <div id='map-thematic' /> </Col> </Row> </div> ); }<file_sep>import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import img_topo from './thumbs/topo.png'; import img_street from './thumbs/street.png'; import img_natgeo from './thumbs/natgeo.png'; import img_ocean from './thumbs/ocean.png'; import img_gray from './thumbs/gray.png'; import img_osm from './thumbs/osm.png'; import img_imagery from './thumbs/imagery.png'; import img_stamen from './thumbs/stamen.png'; export default function Basemap(props) { var base = "px-2 py-1 border pointer text-center small"; var base_left = base + " " var active = " border-dark bg-fta font-weight-bold"; var osm = props.provider === 'osm' ? base_left + active : base_left; var gray = props.provider === 'gray' ? base + active : base; var ocean = props.provider === 'ocean' ? base_left + active : base_left; var natgeo = props.provider === 'natgeo' ? base + active : base; var street = props.provider === 'street' ? base_left + active : base_left; var topography = props.provider === 'topography' ? base + active : base; var imagery = props.provider === 'imagery' ? base + active : base; var stamen = props.provider === 'stamen' ? base + active : base; var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; function handleMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: //setPos3(e.clientX); //setPos4(e.clientY); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = handleMouseUp; // call a function whenever the cursor moves: document.onmousemove = handleMouseMove; //console.log(e) } function handleMouseMove(e) { //const { isDragging } = this.state; /* if (!isDragging) { return; } //event.persist(); console.log(event); */ e = e || window.event; e.preventDefault(); // calculate the new cursor position: //var p1 = pos3 - e.clientX; //var p2 = pos4 - e.clientY; //setPos3(e.clientX); //setPos4(e.clientY); // set the element's new position: //elmnt.style.top = (elmnt.offsetTop - p2) + "px"; //elmnt.style.left = (elmnt.offsetLeft - p1) + "px"; pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: var elmnt = e.target.parentNode; //alert('handleMouseMove') //console.log(elmnt.id); if (elmnt.id === "basemap") { if ((elmnt.offsetTop - pos2) > 0) elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; //if(elmnt.top === "0px") // elmnt.style.top = "10px"; if ((elmnt.offsetLeft - pos1) > 0) elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } } function handleMouseUp() { //window.removeEventListener('mousemove', handleMouseMove); //window.removeEventListener('mouseup', handleMouseUp); document.onmouseup = null; document.onmousemove = null; } return ( <div id="basemap" className={props.basemap ? 'show' : 'hide'} > <div onMouseDown={handleMouseDown} className="move-cursor bg-light border-bottom mb-2 py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Select Basemap<button type="button" className="close" onClick={() => props.setBasemap(false)}><span aria-hidden="true">×</span><span className="sr-only">Close</span></button></div> <div style={{maxHeight:"36vh", overflowY:"auto", overflowX:"hidden"}}> <Row className="px-3 font-11"> <Col className={osm} onClick={() => props.setProvider('osm')}> <img alt="osm" src={img_osm} /> <br /> Open Street Map </Col> <Col className={gray} onClick={() => props.setProvider('gray')} > <img alt="gray" src={img_gray} /> <br /> ArcGIS Gray </Col> </Row> <Row className="px-3 font-11"> <Col className={ocean} onClick={() => props.setProvider('ocean')} > <img alt="ocean" src={img_ocean} /> <br /> ArcGIS Ocean </Col> <Col className={natgeo} onClick={() => props.setProvider('natgeo')} > <img alt="natgeo" src={img_natgeo} /> <br /> ArcGIS National Geographic </Col> </Row> <Row className="px-3 font-11"> <Col className={street} onClick={() => props.setProvider('street')} > <img alt="street" src={img_street} /> <br /> ArcGIS Street </Col> <Col className={topography} onClick={() => props.setProvider('topography')}> <img alt="topography" src={img_topo} /> <br /> ArcGIS Topography </Col> </Row> <Row className="px-3 font-11"> <Col className={imagery} onClick={() => props.setProvider('imagery')} > <img alt="imagery" src={img_imagery} /> <br /> ArcGIS Imagery </Col> <Col className={stamen} onClick={() => props.setProvider('stamen')} > <img alt="Stamen" src={img_stamen} height="67px" /> <br /> Stamen </Col> </Row> </div> </div> ); }<file_sep>import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import Button from 'react-bootstrap/Button'; import Config from '../config.json'; import { useState, useEffect } from 'react'; export default function Metadata(props) { const url_list_harvesting = Config.api_domain + "/harvestings/identifier/"; const [data, setData] = useState(); var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; function handleMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: //setPos3(e.clientX); //setPos4(e.clientY); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = handleMouseUp; // call a function whenever the cursor moves: document.onmousemove = handleMouseMove; //console.log(e) } function handleMouseMove(e) { //const { isDragging } = this.state; /* if (!isDragging) { return; } //event.persist(); console.log(event); */ e = e || window.event; e.preventDefault(); // calculate the new cursor position: //var p1 = pos3 - e.clientX; //var p2 = pos4 - e.clientY; //setPos3(e.clientX); //setPos4(e.clientY); // set the element's new position: //elmnt.style.top = (elmnt.offsetTop - p2) + "px"; //elmnt.style.left = (elmnt.offsetLeft - p1) + "px"; pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: var elmnt = e.target.parentNode; //alert('handleMouseMove') //console.log(elmnt.id); if (elmnt.id === "metadata") { console.log('yes') if ((elmnt.offsetTop - pos2) > 0) elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; //if(elmnt.top === "0px") // elmnt.style.top = "10px"; if ((elmnt.offsetLeft - pos1) > 0) elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } } function handleMouseUp() { //window.removeEventListener('mousemove', handleMouseMove); //window.removeEventListener('mouseup', handleMouseUp); document.onmouseup = null; document.onmousemove = null; } useEffect(() => { if (props.identifierMetadata) { const requestOptions = { method: 'GET' }; //alert(props.identifierMetadata) fetch(url_list_harvesting + props.identifierMetadata, requestOptions).then(res => res.json()).then(data => { console.log(data); console.log(data.data); setData(data.data) }) } }, [props.identifierMetadata]); function viewSubjects(subjects){ if(subjects){ var s = JSON.parse(subjects); if (s){ var list = [] s.forEach(function(x) { //console.log(x.keywords); x.keywords.forEach(function(y){ list.push(y) }); }); //console.log(s[0].keywords); //console.log(s[0].keywords.join(", ")); //console.log(list) if (list) return list.join(", "); else return ""; } } } function viewReferences(subjects){ if(subjects){ var s = JSON.parse(subjects); if (s){ var list = ""; s.forEach(function(x) { console.log(x); console.log(x.name); if (x.name !== null) list += x.protocol + "<br /><a href='"+ x.url+ "' target='_blank' >" + x.name + "</a><hr />"; //+ <br /> + x.url + <hr /> + <br /> //x.keywords.forEach(function(y){ // list.push(y) //}); }); //console.log(s[0].keywords); //console.log(s[0].keywords.join(", ")); //console.log(list) return <div dangerouslySetInnerHTML={{ __html: list }} /> //return list } } } return ( <div id="metadata" className={props.showMetadata ? 'show' : 'hide'} > <div onMouseDown={handleMouseDown} className="move-cursor bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Metadata<button type="button" className="close" onClick={() => props.setShowMetadata(false)}><span aria-hidden="true">×</span><span className="sr-only">Close</span></button></div> <Row className="mt-1 mx-1 font-11 border-bottom" > <Col lg={3} className="py-2 px-1"> Identifier </Col> <Col lg={9} className="py-2 px-1"> { data ? data.identifier : null } </Col> </Row> <Row className="mx-1 font-11 border-bottom" > <Col lg={3} className="py-2 px-1"> Title </Col> <Col lg={9} className="py-2 px-1"> { data ? data.title : null } </Col> </Row> <Row className="mx-1 font-11 border-bottom" > <Col lg={3} className="py-2 px-1"> Abstract </Col> <Col lg={9} className="pt-2 px-1" style={{maxHeight:"100px", overflowY:"auto"}}> { data ? data.abstract : null } </Col> </Row> <Row className="mx-1 font-11 border-bottom" > <Col lg={3} className="py-2 px-1"> Organization </Col> <Col lg={9} className="pt-2 px-1"> { data ? data.organizations.name : null } </Col> </Row> <Row className="mx-1 font-11 border-bottom" > <Col lg={3} className="py-2 px-1"> Keywords </Col> <Col lg={9} className="pt-2 px-1"> { data ? viewSubjects(data.keywords) : null } </Col> </Row> <Row className="mx-1 font-11 border-bottom" > <Col lg={3} className="py-2 px-1"> Distributions </Col> <Col lg={9} className="pt-2 px-1" style={{maxHeight:"100px", overflowY:"auto"}}> { data ? viewReferences(data.distributions) : null } </Col> </Row> <Row className="mx-1 font-11 border-bottom" > <Col lg={3} className="py-2 px-1"> </Col> <Col lg={9} className="pt-2 px-1"> <Button size="sm" block variant="secondary" className="font-11 pt-0 pb-1 mr-2" onClick={() => window.open(Config.api_domain + "/harvestings/identifier/" + data.identifier)} >URL Metadata</Button> </Col> </Row> </div> ); }<file_sep>import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import Config from '../config.json'; import { useState, useEffect } from 'react'; export default function TableAttribute(props) { const url_list_harvesting = Config.api_domain + "/harvestings/identifier/"; const [data, setData] = useState(); var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; function handleMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: //setPos3(e.clientX); //setPos4(e.clientY); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = handleMouseUp; // call a function whenever the cursor moves: document.onmousemove = handleMouseMove; //console.log(e) } function handleMouseMove(e) { //const { isDragging } = this.state; /* if (!isDragging) { return; } //event.persist(); console.log(event); */ e = e || window.event; e.preventDefault(); // calculate the new cursor position: //var p1 = pos3 - e.clientX; //var p2 = pos4 - e.clientY; //setPos3(e.clientX); //setPos4(e.clientY); // set the element's new position: //elmnt.style.top = (elmnt.offsetTop - p2) + "px"; //elmnt.style.left = (elmnt.offsetLeft - p1) + "px"; pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: var elmnt = e.target.parentNode; //alert('handleMouseMove') //console.log(elmnt.id); if (elmnt.id === "tableAttribute") { //console.log('yes') if ((elmnt.offsetTop - pos2) > 0) elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; //if(elmnt.top === "0px") // elmnt.style.top = "10px"; if ((elmnt.offsetLeft - pos1) > 0) elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } } function handleMouseUp() { //window.removeEventListener('mousemove', handleMouseMove); //window.removeEventListener('mouseup', handleMouseUp); document.onmouseup = null; document.onmousemove = null; } useEffect(() => { if (props.identifierAttribute) { const requestOptions = { method: 'GET' }; fetch(url_list_harvesting + props.identifierAttribute, requestOptions).then(res => res.json()).then(data => { console.log(data.data); setData(data.data) var json_obj = JSON.parse(data.data.references); console.log(json_obj); var ogc = json_obj.filter(p => p.scheme === 'OGC:WFS'); const requestOptions = { method: 'GET' }; if (ogc.length > 0) { console.log(ogc[0].url) //http://sumbarprov.ina-sdi.or.id:8080/geoserver/wfs?SERVICE=WfS&REQUEST=GetFeature&VERSION=2.0.0&typeName=ADMIN:administrasi_ar_250k_130020201203152021&featureID=1&outputFormat=application/json var urlnya = ogc[0].url + "?SERVICE=WfS&REQUEST=GetFeature&VERSION=2.0.0&typeName=" + props.identifierAttribute + "&outputFormat=application/json" console.log(urlnya) fetch(urlnya, requestOptions).then(res => res.json()).then(data => { console.log(data) setData(data.features) }); } }) } }, [props.identifierAttribute]); function getRows() { if (typeof (data) !== 'undefined') { //var items=props.presensiDataLast.data; if (data !== null) { if (data.length > 0) { return data.map((row, index) => { console.log(row) return ( <Row className="px-3 font-11" key={"att" + index}> <Col xs={1} className="px-1 border-bottom">{index + 1}</Col> <Col xs={4} className="px-1 border-bottom">{row.properties.lcode}</Col> <Col xs={4} className="px-1 border-bottom">{row.properties.namobj}</Col> <Col xs={3} className="px-1 border-bottom"></Col> </Row> ) ///cr = cr + 1 //return <tr><td className="p-2">{cr}</td><td className="p-2">{row.name}</td><td className="p-2">{row.sj}</td><td className="p-2">{row.kategori}</td><td className="p-2">{row.katalog}</td><td className="p-2 pointer"> <FileEarmarkText size={14} onClick={() => showMetadata(row)} className="mr-2" /> {' '} {row.viewable === 'true' ? <Eye onClick={() => showView(row)} className="mr-2" size={14} /> : ""} {' '} {row.downloadable === 'true' ? <Download size={12} onClick={() => showDownload(row)} /> : ""} </td></tr> }) } else { return ( <Row className="px-3"> <Col className="px-1 font-11"> No record found</Col> </Row> ) } } else { return ( <Row className="px-3"> <Col className="px-1 font-11"> No record found</Col> </Row> ) } } else { return ( <Row className="px-3"> <Col className="px-1 font-11"> No record found</Col> </Row> ) } } return ( <div id="tableAttribute" className={props.showTable ? 'show' : 'hide'} > <div onMouseDown={handleMouseDown} className="move-cursor bg-light border-bottom py-2 pl-3 pr-2 font-weight-bold text-secondary font-14">Table Attribute<button type="button" className="close" onClick={() => props.setShowTable(false)}><span aria-hidden="true">×</span><span className="sr-only">Close</span></button></div> <Row className="px-3" > <Col className="pt-2 px-1 font-11" > Identifier: { props.identifierAttribute } <div style={{ maxHeight: "200px", overflowY: "auto", overflowX: "hidden" }} className="pointer"> { getRows() } </div> </Col> </Row> </div> ); }
23b749cd5fb31d10c08e29eb818f6de98f70ac55
[ "JavaScript" ]
7
JavaScript
lokahita/geoportal-master
4b31f7286dd4a8fb006317f06b0ff69e18a14fe6
88dcc0ea9599a2f649112e18ba44478a04540576
refs/heads/master
<file_sep>package main import ( "fmt" "github.com/garyburd/redigo/redis" ) func main() { //连接redis conn, err := redis.Dial("tcp", "localhost:6379") if err!=nil{ fmt.Println("conn redis failed", err) return } fmt.Println("conn redis success") defer conn.Close() //redis set操作 _,err=conn.Do("Set","abc", 100) if err!=nil{ fmt.Println(err) return } //redis get操作 r, err:=redis.Int(conn.Do("Get", "abc")) if err!=nil{ fmt.Println("get abc failed,",err) return } fmt.Println(r) //100 //redis 批量set _, err=conn.Do("MSet", "abc", 100, "efg", 300) if err!=nil{ fmt.Println(err) return } //redis 批量get rs, err:=redis.Ints(conn.Do("MGet", "abc", "efg")) if err!=nil{ fmt.Println("get abc failed", err) return } //获取批量的值 //100 //300 for _,v :=range rs{ fmt.Println(v) } //redis设置过期时间 _,err=conn.Do("expire", "abc", 10) if err!=nil{ fmt.Println(err) return } //redis list操作lpush _,err=conn.Do("lpush", "book_list", "a", "b", 100) if err!=nil{ fmt.Println(err) return } //redis list操作lpop list, err:=redis.String(conn.Do("lpop", "book_list")) if err!=nil{ fmt.Println("get abc failed", err) return } fmt.Println(list) //redis操作hash设置 _, err=conn.Do("HSet", "books", "abc", 100) if err!=nil{ fmt.Println(err) return } //redis获取hash的值 books, err:=redis.Int(conn.Do("HGet", "books", "abc")) if err!=nil{ fmt.Println("get abc failed,", err) return } fmt.Println(books) } <file_sep># go-redis go操作redis <file_sep>package main import ( "fmt" "github.com/garyburd/redigo/redis" ) //create redis pool var pool *redis.Pool func init(){ // initial redis pool pool=&redis.Pool{ MaxIdle: 16, //最初的连接数量 MaxActive: 0, //连接池最大连接数量,不确定可以用0(0表示自动定义),按需分配 IdleTimeout: 300, //连接关闭时间 300秒 (300秒不使用自动关闭) Dial: func() (redis.Conn, error) { //要连接的redis数据库 return redis.Dial("tcp", "localhost:6379") }, } } func main() { conn:=pool.Get() //从连接池,取一个连接 defer conn.Close() //函数运行结束 ,把连接放回连接池 _, err:=conn.Do("Set", "abc", 200) if err!=nil{ fmt.Println(err) return } r,err:=redis.Int(conn.Do("Get", "abc")) if err!=nil{ fmt.Println("get abc failed,", err) return } fmt.Println(r) pool.Close() //关闭连接池 }
b34907e7ca3c4ec3b81c6df8233cf6aba09ff097
[ "Markdown", "Go" ]
3
Go
dongruan00/go-redis
75052c77efbe9a6b6e7690859c708bc1ef5b3025
31523da3c13af19043944d61b0bb1d88d2950908
refs/heads/master
<repo_name>BrendaCuichan/Programacion_Grafica_I<file_sep>/src/org/yourorghere/Casa.java package org.yourorghere; import java.awt.event.KeyListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLCapabilities; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import javax.print.DocFlavor; import javax.swing.JFrame; import static javax.swing.JFrame.EXIT_ON_CLOSE; /** * * @author Brenda */ //public class Escena extends JFrame implements KeyListener { public class Casa { Auto auto=new Auto(); private static GL gl ; private static float x ; private static float y ; private static float ancho = 100; private static float alto = 100; private static double Pi = 3.14159265358979323846; public Casa() { } public Casa(GL gl, GLU glu, int x, int y, int ancho, int alto) { this.x = x; this.y = y; } public void setX(float x) { this.x = x; } public void setY(float y) { this.y = y; } public float getX() { return x; } public float getY() { return y; } public void disbujarCasa() { Auto auto=new Auto(); gl=auto.getGl(); //frontal gl.glPushMatrix(); gl.glColor3f(0.2f, 0f, 0f); gl.glBegin(gl.GL_QUADS); gl.glVertex2d(x, y); // Arriba a la izquierda gl.glVertex2d(x + ancho, y); gl.glVertex2d(x + ancho, y + alto); gl.glVertex2d(x, y + alto); gl.glEnd(); gl.glPopMatrix(); //largo gl.glPushMatrix(); gl.glColor3f(1f, 0.5f, 0f); gl.glBegin(gl.GL_QUADS); gl.glVertex2d(x+ancho, y); // Arriba a la izquierda gl.glVertex2d(x + 2*ancho, y+alto/3); gl.glVertex2d(x + 2*ancho, y + 4*alto/3); gl.glVertex2d(x+ancho, y + alto); gl.glEnd(); gl.glPopMatrix(); // triangulo ventana gl.glPushMatrix(); gl.glColor3f(0f, 0f, 1f); gl.glBegin(gl.GL_QUADS); gl.glVertex2d(x+4*ancho/3, y+alto/3); // Arriba a la izquierda gl.glColor3f(0f, 0f, 1f); gl.glVertex2d(x + 2*ancho, y + 8*alto/15); gl.glColor3f(1f,1f, 1f); gl.glVertex2d(x + 2*ancho, y + 4*alto/3); gl.glColor3f(0f, 0f, 1f); gl.glVertex2d(x + 4*ancho/3, y +8*alto/7); gl.glEnd(); gl.glPopMatrix(); // triangulo gl.glPushMatrix(); gl.glColor3f(0.8f, 0.2f, 0f); gl.glBegin(gl.GL_TRIANGLES); gl.glVertex2d(x, y+alto); // Arriba a la izquierda gl.glVertex2d(x + ancho, y+alto); gl.glVertex2d(x + ancho/2, y + 3*alto/2); gl.glEnd(); gl.glPopMatrix(); // triangulo techo gl.glPushMatrix(); gl.glColor3f(0.8f, 0f, 0f); gl.glBegin(gl.GL_QUADS); gl.glVertex2d(x+ancho, y+alto); // Arriba a la izquierda gl.glVertex2d(x + ancho/2, y+3*alto/2); gl.glVertex2d(x + 3*ancho/2, y + 11*alto/6); gl.glVertex2d(x + 2*ancho, y + 4*alto/3); gl.glEnd(); gl.glPopMatrix(); // triangulo puerta gl.glPushMatrix(); gl.glColor3f(0.5f, 0.3f, 0.3f); gl.glBegin(gl.GL_QUADS); gl.glVertex2d(x+ancho/3, y); // Arriba a la izquierda gl.glVertex2d(x + 2*ancho/3, y); gl.glVertex2d(x + 2*ancho/3, y +2*alto/3); gl.glVertex2d(x + ancho/3, y + 2*alto/3); gl.glEnd(); gl.glPopMatrix(); // triangulo ventana gl.glPushMatrix(); gl.glColor3f(0f, 0f, 0f); gl.glBegin(gl.GL_LINES); gl.glVertex2d(x+4*ancho/3, y+4*alto/7); // Arriba a la izquierda gl.glVertex2d(x + 2*ancho, y + 3*alto/4); gl.glEnd(); gl.glPopMatrix(); gl.glPushMatrix(); gl.glColor3f(0f, 0f, 0f); gl.glBegin(gl.GL_LINES); gl.glVertex2d(x+5*ancho/3, y+6*alto/5); // Arriba a la izquierda gl.glVertex2d(x + 5*ancho/3, y + 2*alto/3); gl.glEnd(); gl.glPopMatrix(); } } <file_sep>/src/org/yourorghere/Vias.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 org.yourorghere; import javax.media.opengl.GL; /** * * @author usuario */ public class Vias { GL gl; Cuadrado lineac,paso; public Vias(GL gl) { this.gl = gl; } public void lineaMedia(){ lineac=new Cuadrado(0, -1, -7, 35.8f, 0.1f,1, 1, 1, 1, gl); lineac.displayCuadradov(); } public void lineaMediaV(){ lineac=new Cuadrado(0, -1, -7, 15, 0.02f,1, 1, 1, 1, gl); lineac.displayCuadradov(); } public void pasoCebra(){ } } <file_sep>/src/org/yourorghere/Lineas.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 org.yourorghere; import javax.media.opengl.GL; /** * * @author usuario */ public class Lineas { float x, y, z; float ancho, alto, prof; float r, g, b; float sx, sy, sz; GL gl; // public Piramide(GL gl) { // super(gl); // } public Lineas(float x, float y, float z, float ancho, float alto, float prof, float r, float g, float b, GL gl) { this.x = x; this.y = y; this.z = z; this.ancho = ancho; this.alto = alto; this.prof = prof; this.r = r; this.g = g; this.b = b; this.gl = gl; } public void displayLineaH() { gl.glPushMatrix(); gl.glBegin(GL.GL_LINE_STRIP); // gl.glLineWidth(10); gl.glColor3f(r, g, b); // Set the current drawing color to light blue gl.glVertex3f(x , y +alto , z + prof); // Top Left gl.glVertex3f(x + ancho , y+alto, z + prof); // Top Right // gl.glEnd(); gl.glPopMatrix(); } public void displayLineaV() { gl.glPushMatrix(); gl.glBegin(GL.GL_LINE_STRIP); // gl.glLineWidth(10); gl.glColor3f(r, g, b); // Set the current drawing color to light blue gl.glVertex3f(x , y , z + prof); // Top Left gl.glVertex3f(x , y + alto , z + prof); // Top Right gl.glEnd(); gl.glPopMatrix(); } } <file_sep>/src/org/yourorghere/Lolito.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 org.yourorghere; import com.sun.opengl.util.GLUT; import javax.media.opengl.GL; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; /** * * @author usuario */ public class Lolito { float tx, ty, tz; float rx, ry, rz; float r, g, b; float sx, sy, sz; GL gl; GLU glu; GLUT glut; Cubo piernas; Esfera hombros, cabeza, punto, uniones; Circulo ojos; Cono falda; Torus torus; Cilindro cuerpo, brazos; public Lolito(float tx, float ty, float tz, float rx, float ry, float rz, float sx, float sy, float sz, GL gl) { this.tx = tx; this.ty = ty; this.tz = tz; this.rx = rx; this.ry = ry; this.rz = rz; this.sx = sx; this.sy = sy; this.sz = sz; this.gl = gl; // cabeza=new Esfera( ty, tz, 0, 0,0, 0, 0, 0, 1f, 0, 0, gl, 1, 20, 5); // cuerpo=new Cilindro(gl,tx, ty, tz, 1, 1, 0, 20, 5, 0.1f,0.1f); } public void drawMuñeco(float x, float y, float z) { // gl.glTranslatef(x, y, z); gl.glTranslatef(tx, ty, tz); sombrero(x, y, z); cabeza(x, y, z); bufanda(x, y, z); cuarpo(x, y, z); brazos(x, y, z); piernas(x, y, z); } public void sombrero(float x, float y, float z) { torus=new Torus(gl, 1, 1, 1, 0, 1, 1, 10, 20,0.05, 0.05); //brde de bfanda GLUT glut = new GLUT(); gl.glPushMatrix(); gl.glColor3f(0, 1, 1); gl.glTranslated(x, y + 0.2f, z); gl.glRotated(90, 1, 0, 0); // gl.glRotated(25,0,0,1); // glut.glutSolidTorus(0.05, 0.05, 10, 20); torus.dibujarTorus(); gl.glPopMatrix(); //gorro gl.glPushMatrix(); gl.glColor3f(0, 1, 0); gl.glTranslated(x, y + 0.2f, z); gl.glRotated(-90, 1, 0, 0); // gl.glRotated(25,0,0,1); glut.glutSolidCone(0.1f, 0.2f, 10, 20); gl.glPopMatrix(); //ciculo peliche punto = new Esfera(x, y, z, 0, 0, 0, 0, 0, 0, 1f, 1, 0, gl, 0.000005f, 10, 2); gl.glPushMatrix(); gl.glTranslatef(x, y + 0.4f, z); // gl.glRotatef(-90, 1,0, 0); punto.diplayEsfera(x, y, z, 0.08f); gl.glPopMatrix(); } public void cabeza(float x, float y, float z) { cabeza = new Esfera(x, y, z, 0, 0, 0, 0, 0, 0, 1f, 0, 0, gl, 4f, 20, 8); gl.glPushMatrix(); gl.glTranslatef(x, y + 0.17f, z); // gl.glRotatef(-90, 1,0, 0); cabeza.diplayEsfera(x, y, z, 0.097f); gl.glPopMatrix(); } public void cuarpo(float x, float y, float z) { cuerpo = new Cilindro(gl, x, y, z, 1, 1, 0, 20, 5, 0.09f, 0.1f); gl.glPushMatrix(); gl.glTranslatef(x, y - 0.03f, z); gl.glRotatef(-90, 1, 0, 0); cuerpo.dibujarcilindro(); gl.glPopMatrix(); } public void bufanda(float x, float y, float z) { torus=new Torus(gl, 1, 1, 1, 0, 1, 1, 10, 20,0.04, 0.04); GLUT glut = new GLUT(); gl.glPushMatrix(); gl.glColor3f(0, 1, 0); gl.glTranslated(x, y + 0.07f, z); gl.glRotated(90, 1, 0, 0); // gl.glRotated(25,0,0,1); // glut.glutSolidTorus(0.04, 0.04, 10, 20); torus.dibujarTorus(); gl.glPopMatrix(); } public void brazos(float x, float y, float z) { brazos = new Cilindro(gl, x, y, z, 0, 0, 1, 10, 5, 0.03f, 0.1f); uniones = new Esfera(0, y, 0, 0, 0, 0, 0, 0, 0, 1f, 1, 0, gl, 0, 20, 8); gl.glPushMatrix(); gl.glTranslatef(x - 0.1f, y - 0.05f, z); gl.glRotatef(-90, 1, 0, 0); brazos.dibujarcilindro(); gl.glPushMatrix(); uniones.diplayEsfera(0, 1f, 0, 0.035f); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(0.2f, 0, 0); uniones.diplayEsfera(0, 1f, 0, 0.035f); gl.glPopMatrix(); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(x + 0.1f, y - 0.05f, z); gl.glRotatef(-90, 1, 0, 0); brazos.dibujarcilindro(); gl.glPushMatrix(); gl.glTranslatef(0f, 0.0f, 0.1f); uniones.diplayEsfera(0, 1f, 0, 0.03f); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(-0.2f, 0.0f, 0.1f); uniones.diplayEsfera(0, 1f, 0, 0.03f); gl.glPopMatrix(); gl.glPopMatrix(); } public void falda() { // 0.13f,0.25f,10,5 falda = new Cono(gl, 1, 1, 1, 0, 1, 1, 10, 5, 0.13f, 0.25f); gl.glPushMatrix(); //gl.glColor3d(0,3,0); //gl.glColor3d(0,1,1); gl.glTranslated(0, -0.17, 0); gl.glRotated(270, 1, 0, 0); falda.dibujarCono(); gl.glPopMatrix(); } public void piernas(float x, float y, float z) { brazos = new Cilindro(gl, x, y, z, 0, 0, 1, 10, 5, 0.038f, 0.1f); Esfera union = new Esfera(0, y, 0, 0, 0, 0, 0, 0, 0, 1f, 1, 0, gl, 0, 8, 2); gl.glPushMatrix(); gl.glTranslatef(x - 0.042f, y - 0.15f, z); gl.glRotatef(-90, 1, 0, 0); brazos.dibujarcilindro(); gl.glPushMatrix(); gl.glTranslatef(0f, 0.0f, 0f); union.diplayEsfera(0, 1f, 0, 0.05f); gl.glPopMatrix(); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(x + 0.042f, y - 0.15f, z); gl.glRotatef(-90, 1, 0, 0); brazos.dibujarcilindro(); gl.glPushMatrix(); gl.glTranslatef(0.01f, 0.0f, 0f); union.diplayEsfera(0, 1f, 0, 0.05f); gl.glPopMatrix(); gl.glPopMatrix(); } public void monio(float x, float y, float z) { //brde de bfanda GLUT glut = new GLUT(); gl.glPushMatrix(); gl.glColor3f(0, 1, 1); gl.glTranslated(x, y + 0.21f, z); gl.glRotated(90, 1, 0, 0); // gl.glRotated(25,0,0,1); glut.glutSolidTorus(0.05, 0.05, 10, 20); gl.glPopMatrix(); gl.glPushMatrix(); gl.glColor3f(0, 1, 1); gl.glTranslated(x, y + 0.27f, z); gl.glRotated(90, 1, 0, 0); // gl.glRotated(25,0,0,1); glut.glutSolidTorus(0.023, 0.03, 10, 20); gl.glPopMatrix(); //ciculo peliche punto = new Esfera(x, y, z, 0, 0, 0, 0, 0, 0, 1f, 1, 0, gl, 0.000005f, 10, 2); gl.glPushMatrix(); gl.glTranslatef(x + 0.1f, y + 0.3f, z); // gl.glRotatef(-90, 1,0, 0); punto.diplayEsfera(x, y, z, 0.06f); gl.glPopMatrix(); punto = new Esfera(x, y, z, 0, 0, 0, 0, 0, 0, 1f, 1, 0, gl, 0.000005f, 10, 2); gl.glPushMatrix(); gl.glTranslatef(x - 0.1f, y + 0.3f, z); // gl.glRotatef(-90, 1,0, 0); punto.diplayEsfera(x, y, z, 0.06f); gl.glPopMatrix(); } void dibujarMuñeca(float a, float b, float c) { gl.glPushMatrix(); gl.glTranslatef(tx, ty, tz); gl.glRotatef(ry, 0, 1, 0); gl.glPushMatrix(); gl.glTranslated(a, b, c); monio(0, -0.1f, 0); cabeza(0, -0.095f, 0); bufanda(0, -0.05f, 0); ///falda falda(); piernas(0, -0.1f, 0); brazos(0, -0.08f, 0); gl.glPopMatrix(); gl.glPopMatrix(); } } <file_sep>/README.md # Programacion-Grafica-I<file_sep>/src/org/yourorghere/Icosaedro.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 org.yourorghere; import com.sun.opengl.util.GLUT; import javax.media.opengl.GL; import javax.media.opengl.glu.GLU; import javax.media.opengl.glu.GLUquadric; /** * * @author usuario */ public class Icosaedro { GL gl; float x, y, z; // float w, h, d; // float rx, ry, rz; float r, g, b; int slices, stacks; double rs, ri; public Icosaedro(GL gl, float x, float y, float z,float r, float g, float b, int slices, int stacks, double rs, double ri) { this.gl = gl; this.x = x; this.y = y; this.z = z; this.r = r; this.g = g; this.b = b; this.slices = slices; this.stacks = stacks; this.rs = rs; this.ri = ri; } public void dibujarIcosaedro(){ GLU glu=new GLU(); GLUT glut=new GLUT(); GLUquadric esfer = glu.gluNewQuadric(); //renderizar conos, cilindros, y todo glu.gluQuadricDrawStyle (esfer,GLU.GLU_FILL);//GLU_LINE, GLU_POINT, GLU_SILHOUETTE gl.glPushMatrix(); gl.glColor3f(this.r, this.g, this.b); // gl.glTranslatef(x, y, z); // glut.glutSolidCylinder(rs, ri, slices, stacks); glut.glutSolidIcosahedron(); gl.glPopMatrix(); // gl.glEnd(); } } <file_sep>/src/org/yourorghere/PROYECTO_FINAL.java package org.yourorghere; import com.sun.opengl.util.Animator; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import static java.nio.file.Files.size; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; import java.awt.event.KeyEvent; import javax.media.opengl.GLCapabilities; import javax.swing.JFrame; import static javax.swing.JFrame.EXIT_ON_CLOSE; import java.awt.event.KeyListener; // MouseListener, MouseMotionListener public class PROYECTO_FINAL extends JFrame implements KeyListener { // Objetos cam; float anglex = 0, angley = 0,i,rot; public static int ncam = 1; private float view_rotx = 0.01f; private float view_roty = 0.01f; private int oldMousex; private int oldMousey; boolean[] keys = new boolean[256]; private static final float X_POSITION = 0f; private static final float Y_POSITION = 0f; private static final float Z_POSITION = 0f; // private static float trasladaX=0; // private static float trasladaY=0; // // private static float escalaX=1; // private static float escalaY=1; // // private static float rotarX=0; // private static float rotarY=0; //////////////////////////////Enviar datos a clases Objetos obj; Arbol arbol; Paisaje paisaje; Esfera sol,cam; Cancha cancha; ParqueRecreativo parque; //// public PROYECTO_FINAL() { // setTitle("Puntos"); setSize(810, 700); setLocation(10, 40); setTitle("Puntos"); setSize(700,700); setLocation(10,40); // Intancia de clase GraphicListener GraphicListener listener = new GraphicListener(); GLCanvas canvas= new GLCanvas(new GLCapabilities()); canvas.addGLEventListener(listener); getContentPane().add(canvas); Animator animator = new Animator(canvas); animator.start(); addKeyListener(this); // Para que canvas reconozca las pulsaciones del teclado } public static void main(String[] args) { PROYECTO_FINAL frame = new PROYECTO_FINAL(); frame.setVisible(true); frame.setDefaultCloseOperation(EXIT_ON_CLOSE); } public void keyReleased(KeyEvent e) { } public class GraphicListener implements GLEventListener { public void init(GLAutoDrawable drawable) { // Use debug pipeline // drawable.setGL(new DebugGL(drawable.getGL())); GL gl = drawable.getGL(); System.err.println("INIT GL IS: " + gl.getClass().getName()); // Enable VSync gl.setSwapInterval(1); // Setup the drawing area and shading mode gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); gl.glShadeModel(GL.GL_SMOOTH); // try setting this to GL_FLAT and see what happens. gl.glEnable(GL.GL_DEPTH_TEST); obj=new Objetos( 0, 0, -1, 1, 1, 1, 1, 0, 0, gl); //para girar parque=new ParqueRecreativo(0, 0, -1, 1, 1, 1, 1, 0, 0, gl); // obj = new Objetos(0, 0, 0, 0, 0, 0, 0, 1, 0, gl); //cualquieea arbol = new Arbol(-0.1f, 0.1f, -2, 0.2f, 0.5f, 0.5f, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, gl); sol = new Esfera(3.4f, 2.7f, -8, 1, 1, 1, 1, 1, 1, 1, 1, 0, gl, .3f, 20, 10); paisaje = new Paisaje(gl); cancha = new Cancha(gl, 3, -1f, -3, 1, 1, 1, 0, 90, 0, 1, 1, 1); cam=new Esfera(0.5f, -0f, -3,1,1,1,1,1,1,1,1,1,gl,.5f,7,7); } //cambia los prev public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL gl = drawable.getGL(); GLU glu = new GLU(); if (height <= 0) { // avoid a divide by zero error! height = 1; } final float h = (float) width / (float) height; gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); glu.gluPerspective(45.0f, h, 1.0, 20.0); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); } //dibuja public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); // GLU glu = new GLU(); // glut=new GLUT(); // Borrar el área de dibujo gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); // Restablecer la matriz actual a la "identidad" gl.glLoadIdentity(); GLU glu= new GLU (); // paisaje.dibujarPaisaje(); // // sol.display1(); // gl.glLoadIdentity(); if(ncam==1){ glu.gluLookAt(sol.x,sol.y,-15,obj.tx,0,0,0,1,0);} if(ncam==2){ glu.gluLookAt(sol.x,sol.y,-16,obj.tx,obj.ty,-10,0,1,0);} if(ncam==3){ cam.x=(float) Math.cos(i)*4; cam.y=(float) Math.sin(i)*4; // obj.ry+=.02f; i+=.01f; // cam.x=-6.7f; glu.gluLookAt(obj.rx,obj.ry,0,obj.tx,0,-5,0,1,0);} //// casa en la casas del fondo // ________ SECION CASAS_________________ //derecho gl.glPushMatrix(); gl.glTranslatef(15, 0,-6); // gl.glRotatef(20f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(10, 0,-6); // gl.glRotatef(20f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(5, 0,-6); // gl.glRotatef(20f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); //izqueir gl.glPushMatrix(); gl.glTranslatef(0, 0,-6); // gl.glRotatef(20f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(-5, 0,-6); // gl.glRotatef(20f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(-10, 0,-6); // gl.glRotatef(20f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); // casa lado izquier gl.glPushMatrix(); gl.glTranslatef(14, 0,-6); gl.glRotatef(-90f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); gl.glPushMatrix(); gl.glTranslatef(-8, 0,-5); gl.glRotatef(90f, 0, 1, 0); obj.displayCasa(0.5f, -0.5f, -5); gl.glPopMatrix(); // //_____________SECION DEL PARQUE___________ parque.displayParque(3f, -0.5f, -3f); arbol.dibujarArbol(-1,-0.5f,-5); // // cancha.dibujarcancha(); gl.glFlush(); } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } } public void keyTyped(KeyEvent e) { if (e.getKeyChar() == '1') { PROYECTO_FINAL.ncam = 1; } if (e.getKeyChar() == '2') { PROYECTO_FINAL.ncam = 2; } if (e.getKeyChar() == '3') { PROYECTO_FINAL.ncam = 3; } if (e.getKeyChar() == '4') { PROYECTO_FINAL.ncam = 4; } if (e.getKeyChar() == '5') { PROYECTO_FINAL.ncam = 5; } if (e.getKeyChar() == '6') { PROYECTO_FINAL.ncam = 6; } } public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_RIGHT) { obj.tx += 0.1; System.out.println("Valor en la traslacion de X: " + obj.tx); } if (e.getKeyCode() == KeyEvent.VK_LEFT) { obj.tx -= 0.1; System.out.println("Valor en la traslacion de X: " + obj.tx); } if (e.getKeyCode() == KeyEvent.VK_UP) { obj.ty += 0.1; System.out.println("Valor en la traslacion de Y: " + obj.ty); } if (e.getKeyCode() == KeyEvent.VK_DOWN) { obj.ty -= 0.1; System.out.println("Valor en la traslacion de Y: " + obj.ty); } if (e.getKeyCode() == KeyEvent.VK_D) { obj.sx += 1f; System.out.println("Valor en la escalacion de x: " + obj.sx); } if (e.getKeyCode() == KeyEvent.VK_A) { obj.sx -= 1f; System.out.println("Valor en la escalacion de x: " + obj.sx); } if (e.getKeyCode() == KeyEvent.VK_W) { obj.sy += 1f; System.out.println("Valor en la escalacion de y: " + obj.sy); } if (e.getKeyCode() == KeyEvent.VK_S) { obj.sy -= 1f; System.out.println("Valor en la escalacion de y: " + obj.sy); } if (e.getKeyCode() == KeyEvent.VK_R) { obj.rx += 1f; System.out.println("Valor en la rotacion de x: " + obj.rx); } if (e.getKeyCode() == KeyEvent.VK_T) { obj.rx -= 1f; System.out.println("Valor en la rotacion de x: " + obj.rx); } if (e.getKeyCode() == KeyEvent.VK_Y) { obj.ry += 1f; System.out.println("Valor en la rotacion de y: " + obj.ry); } if (e.getKeyCode() == KeyEvent.VK_U) { obj.ry -= 1f; System.out.println("Valor en la rotacion de y: " + obj.ry); } if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { obj.tx = 0; obj.ty = 0; obj.sx = 1; obj.sy = 1; obj.rx = 0; obj.ry = 0; } } // public void keyReleased(KeyEvent e) { // } // // public void mouseClicked(MouseEvent e) { // // } // // public void mousePressed(MouseEvent e) { // oldMousex = e.getX(); // oldMousey = e.getY(); // } // // public void mouseReleased(MouseEvent e) { // // } // // public void mouseEntered(MouseEvent e) { // // } // // public void mouseExited(MouseEvent e) { // // } // // public void mouseDragged(MouseEvent e) { // int x = e.getX(); // int y = e.getY(); // Dimension size = e.getComponent().getSize(); // float thetaX = 360.0f * ((float) (x - oldMousex) / (float) size.width); // float thetaY = 360.0f * ((float) (oldMousey - y) / (float) size.width); // oldMousex = x; // oldMousey = y; //// obj.ry += thetaX; //// obj.ry+= thetaY; // view_rotx += thetaX; // view_roty += thetaY; // System.out.println( view_rotx); // System.out.println( view_roty); // } // // public void mouseMoved(MouseEvent e) { // // } }
3dca0a846d60ade7f2d4eec93e0551e9c72f08f8
[ "Markdown", "Java" ]
7
Java
BrendaCuichan/Programacion_Grafica_I
63dac0a13ae12dce6627c2c70760b9efa9150a2a
9977a7d2154ece6aa5bd2e1015306e5970246dfa
refs/heads/master
<file_sep>import React, { PureComponent } from "react"; import SpreadsheetHeader from "./SpreadsheetHeader.jsx"; import SpreadsheetBody from "./SpreadsheetBody.jsx"; const COLS = ["A", "B", "C", "D", "E"]; const ROWS = [1, 2, 3, 4, 5]; export default class Spreadsheet extends PureComponent { render() { return ( <SpreadsheetTable> <SpreadsheetHeader cols={COLS} /> <SpreadsheetBody rows={ROWS} cols={COLS} {...this.props} /> </SpreadsheetTable> ); } } const SpreadsheetTable = ({ children }) => ( <table> <tbody>{children}</tbody> </table> ); <file_sep>import React, { PureComponent } from "react"; import PropTypes from "prop-types"; export default class SpreadsheetHeader extends PureComponent { static propTypes = { cols: PropTypes.arrayOf(PropTypes.string).isRequired }; render() { return ( <tr> <th /> {this.props.cols.map(col => ( <th key={col}>{col}</th> ))} </tr> ); } } <file_sep>## 🔢 A simple React spreadsheet ### Why? I created this as part of a "Introduction to React" workshop I gave at [UNIFEI](https://unifei.edu.br/), in March 2019. ### How to run? 1. First run `yarn && yarn start` inside the `backend` folder. 2. Then run `yarn && yarn start` inside the `frontend` folder. 3. Open `localhost:3000` in your browser. ### Next improvements (AKA homework) - A button to clear the spreadsheet data - Move state to Redux - Refactor to use CSS-in-JS (eg. Emotion) - Keyboard support (up/down arrows, esc, enter) - Persist data to an actual database - Switch formula evaluation to something safer than `eval` - Deploy project to a server in the cloud (eg. Firebase) ### Credits The spreadsheet calculation code was inspired on <NAME>'s [Tiny Excel-like app in vanilla JS](http://jsfiddle.net/ondras/hYfN3/). <file_sep>import React, { PureComponent } from "react"; import calculator from "../lib/calculator.js"; import Spreadsheet from "./Spreadsheet.jsx"; export default class SpreadsheetContainer extends PureComponent { state = { formulas: {}, cells: {} }; componentDidMount() { fetch("/cells") .then(data => data.json()) .then(data => this.refreshData(data)); } refreshData(data) { const formulas = data.data; this.setState({ formulas: formulas, cells: calculator(formulas) }); } updateData(cell, value) { fetch(`/cells/${cell}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ value: value }) }) .then(data => data.json()) .then(data => { const formulas = data.data; const cells = calculator(formulas); this.setState(state => { return { formulas: { ...state.formulas, [cell]: value }, cells: { ...state.cells, [cell]: cells[cell] } }; }); }); } handleChange(event) { const target = event.target; this.setState(state => { const cells = { ...state.cells }; cells[target.id] = target.value; return { cells }; }); } handleFocus(event) { const target = event.target; this.setState(state => { const cells = { ...state.cells }; // creates a shallow copy of the object cells[target.id] = state.formulas[target.id] || ""; // default to "" return { cells }; }); } handleBlur(event) { const target = event.target; this.updateData(target.id, target.value); } render() { return ( <div className="App"> <Spreadsheet cells={this.state.cells} onCellChange={this.handleChange.bind(this)} onCellFocus={this.handleFocus.bind(this)} onCellBlur={this.handleBlur.bind(this)} /> </div> ); } } <file_sep>/** * Evaluates a matrix of formulas and returns a matrix of results. * * Warning: this uses `eval` for formula evaluation, therefore introducing the possibility of * malicious code injection. * * Inspired by http://jsfiddle.net/ondras/hYfN3/. * @param formulas Map of formulas, indexed by cell name (A1, A2, etc.). * @returns Map of resulting cell values after formula evaluation. */ export default function calculator(formulas) { const cells = {}; const evaluableFormulas = createEvaluableFormulas(formulas); Object.keys(formulas).forEach(key => { try { cells[key] = evaluableFormulas[key]; } catch (e) { // circular reference } }); return cells; } function createEvaluableFormulas(formulas) { const map = {}; Object.keys(formulas).forEach(key => { Object.defineProperty(map, key, { get: function() { let formula = formulas[key] || ""; if (formula.charAt(0) === "=") { formula = formula.substring(1).replace(/(([A-Z])+\d+)/g, "map.$1"); // eslint-disable-next-line return eval(formula); // as a rule of thumb you should NOT use eval in a production application } else { return isNaN(parseFloat(formula)) ? formula : parseFloat(formula); } } }); }); return map; } <file_sep>var express = require("express"); var router = express.Router(); var database = require("../lib/database.js"); /* GET sells listing. */ router.get("/", function(req, res, next) { res.send({ data: database.cells.list() }); }); router.put("/:cell", function(req, res, next) { database.cells.set(req.params.cell, req.body.value); res.send({ data: database.cells.list() }); }); module.exports = router; <file_sep>import React, { PureComponent } from "react"; import PropTypes from "prop-types"; export default class SpreadsheetBody extends PureComponent { static propTypes = { col: PropTypes.string.isRequired, row: PropTypes.number.isRequired, cells: PropTypes.object.isRequired, onCellChange: PropTypes.func.isRequired, onCellFocus: PropTypes.func.isRequired, onCellBlur: PropTypes.func.isRequired }; render() { return ( <td> <input id={`${this.props.col}${this.props.row}`} name={`cell${this.props.col}${this.props.row}`} onChange={this.props.onCellChange} onFocus={this.props.onCellFocus} onBlur={this.props.onCellBlur} value={this.props.cells[`${this.props.col}${this.props.row}`] || ""} autoComplete="off" /> </td> ); } }
7efa0128ff76c004e4789ef9b735aa804760f466
[ "JavaScript", "Markdown" ]
7
JavaScript
dooart/react-spreadsheet
6c976e07da1928e3a43884d48d436ca7d0667083
28e5819fdfd44ed0233d98231452cb35835a0bc5
refs/heads/master
<repo_name>amaxilat/JAMAiCA<file_sep>/javamltests/src/test/java/com/amaxilatis/javaml/test/TestB.java package com.amaxilatis.javaml.test; import libsvm.LibSVM; import net.sf.javaml.core.DefaultDataset; import net.sf.javaml.core.Instance; import net.sf.javaml.core.SparseInstance; import net.sparkworks.cs.client.impl.DataClientImpl; import net.sparkworks.cs.client.impl.ResourceClientImpl; import net.sparkworks.cs.common.dto.Granularity; import net.sparkworks.cs.common.dto.QueryTimeRangeResourceDataCriteriaDTO; import net.sparkworks.cs.common.dto.QueryTimeRangeResourceDataDTO; import net.sparkworks.cs.common.dto.QueryTimeRangeResourceDataResultDTO; import net.sparkworks.cs.common.dto.ResourceDTO; import net.sparkworks.cs.common.dto.ResourceDataDTO; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.Properties; import java.util.Random; import static com.amaxilatis.javaml.test.Constants.GRANT_TYPE; import static com.amaxilatis.javaml.test.Constants.SCOPE; import static com.amaxilatis.javaml.test.Constants.SERVER_URL; import static com.amaxilatis.javaml.test.Constants.TOKEN_URL; public class TestB { private static final String EXTREME = "extreme"; private static final String COMFORTABLE = "comfortable"; private static final String RECOMMENDED = "recommended"; private static final String HIGH = "high"; static Map<String, Integer> map = new HashMap<>(); static Map<String, Integer> map2 = new HashMap<>(); private static LibSVM knn2; private static ResourceClientImpl rClient; private static DataClientImpl dataClient; public static void main(String[] args) throws IOException { new TestB(); } public TestB() throws IOException { Properties properties = new Properties(); properties.load(this.getClass().getClassLoader().getResourceAsStream("connection.properties")); final String clientId = properties.getProperty("clientId"); final String clientSecret = properties.getProperty("clientSecret"); final String username = properties.getProperty("username"); final String password = properties.getProperty("password"); final String[] resHumidityIds = properties.getProperty("resHumidityIds").split(","); map.put(EXTREME, 0); map.put(COMFORTABLE, 0); map.put(RECOMMENDED, 0); map.put(HIGH, 0); map2.put(EXTREME, 0); map2.put(COMFORTABLE, 0); map2.put(RECOMMENDED, 0); map2.put(HIGH, 0); final Collection<Instance> trainData2 = new ArrayList<>(); { Random rand = new Random(); { for (int i = 0; i < 50; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(30)); instance.setClassValue("extreeme"); trainData2.add(instance); } for (int i = 0; i < 50; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(20) + 80); instance.setClassValue("extreeme"); trainData2.add(instance); } } { for (int i = 0; i < 70; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(15) + 30); instance.setClassValue("comfortable"); trainData2.add(instance); } for (int i = 0; i < 30; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(5) + 55); instance.setClassValue("comfortable"); trainData2.add(instance); } } { for (int i = 0; i < 100; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(10) + 45); instance.setClassValue("recommended"); trainData2.add(instance); } } { for (int i = 0; i < 100; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(20) + 60); instance.setClassValue("high"); trainData2.add(instance); } } } knn2 = new LibSVM(); knn2.buildClassifier(new DefaultDataset(trainData2)); rClient = new ResourceClientImpl(SERVER_URL, clientId, clientSecret, username, password, TOKEN_URL, GRANT_TYPE, SCOPE); dataClient = new DataClientImpl(SERVER_URL, clientId, clientSecret, username, password, TOKEN_URL, GRANT_TYPE, SCOPE); long from = 1517040396000L; long to = 1527408397000L; for (String resLuminosityId : resHumidityIds) { annotateData(from, to, rClient.get(Long.valueOf(resLuminosityId))); } System.out.println(map2.toString()); System.out.println(map.toString()); } private static void annotateData(long from, long to, Optional<ResourceDTO> resourceDTO) { ArrayList<Double> data = getData(from, to, resourceDTO.get().getResourceId()); for (Double datum : data) { String res = classify2(datum); map2.put(res, map2.get(res) + 1); } ArrayList<Double> dataOfficeHours = getDataOfficeHours(from, to, resourceDTO.get().getResourceId()); for (Double datum : dataOfficeHours) { String res = classify2(datum); map.put(res, map.get(res) + 1); } } private static String classify2(final double d) { System.out.println(d); final SparseInstance instance = new SparseInstance(); instance.put(0, d); return (String) knn2.classify(instance); } private static ArrayList<Double> getData(long from, long to, long id) { ArrayList<Double> dataList = new ArrayList<>(); QueryTimeRangeResourceDataDTO dto = new QueryTimeRangeResourceDataDTO(); dto.setQueries(new ArrayList<>()); QueryTimeRangeResourceDataCriteriaDTO cDto = new QueryTimeRangeResourceDataCriteriaDTO(); cDto.setFrom(from); cDto.setTo(to); cDto.setGranularity(Granularity.HOUR); cDto.setResultLimit(1000000); cDto.setResourceID(id); dto.getQueries().add(cDto); QueryTimeRangeResourceDataResultDTO res1 = dataClient.queryTimeRangeResourcesData(dto).get(); for (QueryTimeRangeResourceDataCriteriaDTO s : res1.getResults().keySet()) { for (ResourceDataDTO resourceDataDTO : res1.getResults().get(s).getData()) { if (resourceDataDTO.getReading() > 0) { dataList.add(resourceDataDTO.getReading()); } } } return dataList; } private static ArrayList<Double> getDataOfficeHours(long from, long to, long id) { ArrayList<Double> dataList = new ArrayList<>(); QueryTimeRangeResourceDataDTO dto = new QueryTimeRangeResourceDataDTO(); dto.setQueries(new ArrayList<>()); QueryTimeRangeResourceDataCriteriaDTO cDto = new QueryTimeRangeResourceDataCriteriaDTO(); cDto.setFrom(from); cDto.setTo(to); cDto.setGranularity(Granularity.HOUR); cDto.setResultLimit(1000000); cDto.setResourceID(id); dto.getQueries().add(cDto); QueryTimeRangeResourceDataResultDTO res1 = dataClient.queryTimeRangeResourcesData(dto).get(); for (QueryTimeRangeResourceDataCriteriaDTO s : res1.getResults().keySet()) { for (ResourceDataDTO resourceDataDTO : res1.getResults().get(s).getData()) { int hour = new Date(resourceDataDTO.getTimestamp()).getHours(); if (hour < 18 && hour > 10) { if (resourceDataDTO.getReading() > 0) { dataList.add(resourceDataDTO.getReading()); } } } } return dataList; } } <file_sep>/javamltests/pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>eu.organicity.annotation.jamaica</groupId> <artifactId>javamltests</artifactId> <version>1.0-SNAPSHOT</version> <packaging>jar</packaging> <name>JavaML tests</name> <properties> <build.plugins.plugin.version>3.1</build.plugins.plugin.version> <spring.boot.version>1.5.7.RELEASE</spring.boot.version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> <java.version>1.8</java.version> </properties> <repositories> <repository> <id>sparkworks</id> <url>http://nexus.sparkworks.net/nexus/content/repositories/snapshots</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>onejar-maven-plugin.googlecode.com</id> <url>http://onejar-maven-plugin.googlecode.com/svn/mavenrepo</url> </pluginRepository> </pluginRepositories> <dependencies> <dependency> <groupId>eu.organicity.annotation.jamaica</groupId> <artifactId>javaml</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.20</version> </dependency> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20131018</version> </dependency> <dependency> <groupId>net.sparkworks.cs</groupId> <artifactId>cs-client</artifactId> <version>1.0.0-SNAPSHOT</version> </dependency> <!--#################################################################################################--> <!--ApacheStatistics--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-math</artifactId> <version>2.2</version> </dependency> </dependencies> <build> <testSourceDirectory>src/test/java</testSourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project> <file_sep>/javamltests/src/test/java/com/amaxilatis/javaml/test/TestA.java package com.amaxilatis.javaml.test; import libsvm.LibSVM; import net.sf.javaml.core.DefaultDataset; import net.sf.javaml.core.Instance; import net.sf.javaml.core.SparseInstance; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Random; public class TestA { static Map<String, Integer> map = new HashMap<>(); static Map<String, Integer> map2 = new HashMap<>(); static Map<String, Integer> mapOriginal = new HashMap<>(); private static LibSVM knn; private static LibSVM knn2; public static void main(String[] args) { new TestA(); } public TestA() { map.put("low", 0); map.put("normal", 0); map.put("congestion", 0); map2.put("low", 0); map2.put("normal", 0); map2.put("congestion", 0); mapOriginal.put("low", 0); mapOriginal.put("normal", 0); mapOriginal.put("congestion", 0); final Collection<Instance> trainData = new ArrayList<>(); final Collection<Instance> trainData2 = new ArrayList<>(); { { final SparseInstance instance = new SparseInstance(); instance.put(0, Double.parseDouble("0.0")); instance.setClassValue("low"); trainData.add(instance); } { final SparseInstance instance = new SparseInstance(); instance.put(0, Double.parseDouble("30")); instance.setClassValue("normal"); trainData.add(instance); } { final SparseInstance instance = new SparseInstance(); instance.put(0, Double.parseDouble("80")); instance.setClassValue("congestion"); trainData.add(instance); } } { Random rand = new Random(); { for (int i = 0; i < 100; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(15)); instance.setClassValue("low"); trainData2.add(instance); } } { for (int i = 0; i < 100; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(40) + 15); instance.setClassValue("normal"); trainData2.add(instance); } } { for (int i = 0; i < 100; i++) { final SparseInstance instance = new SparseInstance(); instance.put(0, (double) rand.nextInt(45) + 55); instance.setClassValue("congestion"); trainData2.add(instance); } } } knn = new LibSVM(); knn2 = new LibSVM(); knn.buildClassifier(new DefaultDataset(trainData)); knn2.buildClassifier(new DefaultDataset(trainData2)); try (BufferedReader br = new BufferedReader(new FileReader(this.getClass().getClassLoader().getResource("results-12.csv").getFile()))) { for (String line; (line = br.readLine()) != null; ) { // process the line. String value = line.split(",")[2]; if (value.equals("value")) { System.out.println("ERROR:" + value); continue; } String result = line.split(",")[3].replaceAll("urn:oc:tagDomain:TrafficLevel:", ""); String res = classify(Double.parseDouble(value)); String res2 = classify2(Double.parseDouble(value)); map.put(res, map.get(res) + 1); map2.put(res2, map2.get(res2) + 1); if (res2.equals("congestion") && !res.equals("congestion")) { System.out.println("val:" + value); } if (res.equals("congestion") && !res2.equals("congestion")) { System.out.println("val:" + value); } mapOriginal.put(result, mapOriginal.get(result) + 1); // System.out.println(res + " VS " + result); } // line is not visible here. } catch (Exception e) { e.printStackTrace(); } System.out.println(map.toString()); System.out.println(map2.toString()); // System.out.println(mapOriginal.toString()); } private static String classify(final double d) { final SparseInstance instance = new SparseInstance(); instance.put(0, d); return (String) knn.classify(instance); } private static String classify2(final double d) { final SparseInstance instance = new SparseInstance(); instance.put(0, d); return (String) knn2.classify(instance); } }
f8f19f0cf3cbefe30f837b69f9e8758aa4c4d500
[ "Java", "Maven POM" ]
3
Java
amaxilat/JAMAiCA
c74ec9869ab82f140532e9fa2ed9b85914b73ec7
a246ba60d1aaaaf4ee074316f384787eda066b50
refs/heads/master
<repo_name>enthusiastick/korning<file_sep>/db/migrate/20131216184809_seed_customers.rb class SeedCustomers < ActiveRecord::Migration def change Sale.all.each do |sale| Customer.find_or_create_by account_number: sale.customer_and_account_no.split[1].delete('(').delete(')') do |customer| customer.name = sale.customer_and_account_no.split[0] customer.account_number = sale.customer_and_account_no.split[1].delete('(').delete(')') customer.save end end end end <file_sep>/db/migrate/20131216175334_normalize_sales1.rb class NormalizeSales1 < ActiveRecord::Migration def change add_column :sales, :employee_id, :integer Sale.reset_column_information Sale.all.each do |sale| id_number = Employee.select(:id).where('email = ?', sale.employee.split[2].delete('(').delete(')')).pluck(:id)[0] sale.employee_id = id_number sale.save end end end <file_sep>/db/migrate/20131216195648_remove_columns_from_sales.rb class RemoveColumnsFromSales < ActiveRecord::Migration def change remove_column :sales, :employee, :string remove_column :sales, :customer_and_account_no, :string remove_column :sales, :product_name, :string end end <file_sep>/db/migrate/20131216193740_normalize_sales3.rb class NormalizeSales3 < ActiveRecord::Migration def change add_column :sales, :product_id, :integer Sale.reset_column_information Sale.all.each do |sale| id_number = Product.select(:id).where('name = ?', sale.product_name).pluck(:id)[0] sale.product_id = id_number sale.save end end end <file_sep>/app/models/sale.rb class Sale < ActiveRecord::Base belongs_to :employee belongs_to :product belongs_to :customer def last_thirteen_months? require 'date' date = Date.today - 395 sale_date > date end def self.limited results = [] self.all.order(:sale_date).each do |sale| results << sale if sale.last_thirteen_months? end results end def invoice_amount if self.invoice_frequency == 'Monthly' invoice_amount_rough = self.sale_amount / 12 invoice_amount = "%.2f" % invoice_amount_rough elsif self.invoice_frequency = '' invoice_amount_rough = self.sale_amount / 4 invoice_amount = "%.2f" % invoice_amount_rough elsif self.invoice_frequency = '' invoice_amount = self.sale_amount end invoice_amount end def price_per_unit ppu_rough = self.sale_amount / self.units_sold price_per_unit = "%.2f" % ppu_rough end end <file_sep>/db/migrate/20131216191326_normalize_sales2.rb class NormalizeSales2 < ActiveRecord::Migration def change add_column :sales, :customer_id, :integer Sale.reset_column_information Sale.all.each do |sale| id_number = Customer.select(:id).where('account_number = ?', sale.customer_and_account_no.split[1].delete('(').delete(')')).pluck(:id)[0] sale.customer_id = id_number sale.save end end end <file_sep>/db/migrate/20131216192645_seed_products.rb class SeedProducts < ActiveRecord::Migration def change Sale.all.each do |sale| Product.find_or_create_by name: sale.product_name do |product| product.name = sale.product_name product.save end end end end <file_sep>/db/migrate/20131216163657_seed_employees.rb class SeedEmployees < ActiveRecord::Migration def change Sale.all.each do |sale| Employee.find_or_create_by email: sale.employee.split[2].delete('(').delete(')') do |employee| employee.email = sale.employee.split[2].delete('(').delete(')') employee.firstname = sale.employee.split[0] employee.lastname = sale.employee.split[1] employee.save end end end end <file_sep>/reset.sh #!/bin/sh git checkout master rake db:drop db:create db:migrate db:seed git checkout ebens_work <file_sep>/db/migrate/20131216190216_customers_websites.rb class CustomersWebsites < ActiveRecord::Migration def change lg = Customer.where(name: 'LG').first lg.website_url = 'www.lg.com' lg.save htc = Customer.where(name: 'HTC').first htc.website_url = 'www.htc.com/us' htc.save nokia = Customer.where(name: 'Nokia').first nokia.website_url = 'www.nokia.com' nokia.save samsung = Customer.where(name: 'Samsung').first samsung.website_url = 'www.samsung.com' samsung.save motorola = Customer.where(name: 'Motorola').first motorola.website_url = 'www.motorola.com' motorola.save apple = Customer.where(name: 'Apple').first apple.website_url = 'www.apple.com' apple.save end end
3db649216ed569e61eecfe4eb11f8041192707bd
[ "Ruby", "Shell" ]
10
Ruby
enthusiastick/korning
3d5adc2f113773210e7d75010b8e8c9303270ad5
7e19f65a7568e78c748618d17de6ea0f83ce569f
refs/heads/main
<repo_name>Sujan-Murugesh/file-image-crud-spring-boot<file_sep>/README.md # file-image-crud-spring-boot This is Spring Boot Full-Stack project. <file_sep>/src/main/java/com/sujan/file/ImageGalleryRepository.java package com.sujan.file; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ImageGalleryRepository extends JpaRepository<ImageGallery,Long> { }
595fc0d8b19d9c1dc894f5be97a92796a2fe7692
[ "Markdown", "Java" ]
2
Markdown
Sujan-Murugesh/file-image-crud-spring-boot
98745c6b11271e91aca0c3a30e890fd8dfc0f82b
a5d0209313823b0fa47588c65886c9753104c8ae
refs/heads/master
<repo_name>andyreesecups/jQuery-Calculator<file_sep>/logic.js $(document).ready(function() { //Variables var firstNumber = ""; var secondNumber = ""; var operator = ""; var result = 0; var hasNumber = false; var firstNumberComplete = false; var lockButtons = false; //Check if any button is clicked... $(document).on("click", "button", function() { // Checks if it's a number and that it's not the end of the calculation ("!lockButtons") if ($(this).hasClass("number") && !lockButtons) { //We will then set out "hasNumber" variable to true to indicate that we can proceed in selecting an operator. hasNumber = true; //if we haven't received an operator yet.... if (firstNumberComplete === false) { // Then grab the number of the value clicked and build a string with it firstNumber += $(this).attr("value"); // Print it to the div $("#first-number").html(firstNumber); // if we've already received an operator } else { // grab the number of the value clicked and build a string with it secondNumber += $(this).attr("value"); // print the number to the firstPage console.log(secondNumber); //print it to the div $("#second-number").html(secondNumber); } } // checks if it's an operator (but not "=") if ($(this).hasClass("operator") && hasNumber && !lockButtons) { firstNumberComplete = true; // set the visual to show the operator's symbol $("#operator").html("<h1>" + $(this).text() + "</h1>"); operator = $(this).attr("value"); } // Checks if the equal button has been pressed. If so... if ($(this).hasClass("equal")) { // lock the keyboard from being clicked lockButtons = true; // Convert the numbers into integers firstNumber = parseInt(firstNumber); secondNumber = parseInt(secondNumber); // Then figure out which operator was clicked and perform the necessary functions // Then show the result in the HTML if (operator === "plus") { result = firstNumber + secondNumber; } if (operator === "minus") { result = firstNumber - secondNumber; } if (operator === "times") { result = firstNumber * secondNumber; } if (operator === "divide") { result = firstNumber / secondNumber; } if (operator === "power") { result = Math.pow(firstNumber, secondNumber); } $("#result").html(result); } // If clear is selected then wipe away all of the content from the screen and unlock the buttons. if ($(this).hasClass("clear")) { firstNumber = ""; secondNumber = ""; operator = ""; result = 0; hasNumber = false; firstNumberComplete = false; lockButtons = false; $("#first-number, #second-number, #operator, #result").empty(); } }); // Closes my onclick code }); // Closes the ready code
d5e487a775dfd904697bcf3cb29214862c38ef32
[ "JavaScript" ]
1
JavaScript
andyreesecups/jQuery-Calculator
631e8788f0ed965d8fbaa143210b548a44913422
ecd10a6317d20f99e52da10cc680ba7dfb6bf931
refs/heads/master
<repo_name>ERA-URBAN/wrfpy<file_sep>/wrfpy/wrfda.py #!/usr/bin/env python ''' description: WRFDA part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' import os import f90nml import subprocess import shutil from wrfpy import utils from wrfpy.config import config from datetime import datetime import time class wrfda(config): ''' description ''' def __init__(self, datestart, low_only=False): config.__init__(self) # load config self.low_only = low_only self.datestart = datestart self.rundir = self.config['filesystem']['wrf_run_dir'] self.wrfda_workdir = os.path.join(self.config['filesystem']['work_dir'], 'wrfda') self.max_dom = utils.get_max_dom(self.config['options_wrf']['namelist.input']) # copy default 3dvar obsproc namelist to namelist.obsproc self.obsproc_dir = os.path.join(self.config['filesystem']['wrfda_dir'], 'var/obsproc') # get dictionary with workdir/obs filename per domain self.obs = self.get_obsproc_dirs() def run(self, datestart): ''' Run all WRFDA steps ''' self.datestart = datestart self.obsproc_init(datestart) # initialize obsrproc work directory self.obsproc_run() # run obsproc.exe self.prepare_updatebc(datestart) # prepares for updating low bc for domain in range(1, self.max_dom+1): self.updatebc_run(domain) # run da_updatebc.exe self.prepare_wrfda() # prepare for running da_wrfvar.exe for domain in range(1, self.max_dom+1): self.wrfvar_run(domain) # run da_wrfvar.exe # prepare for updating lateral bc self.prepare_updatebc_type('lateral', datestart, 1) self.updatebc_run(1) # run da_updatebc.exe self.wrfda_post(datestart) # copy files over to WRF run_dir def obsproc_init(self, datestart): ''' Sync obsproc namelist with WRF namelist.input ''' from datetime import timedelta from datetime import datetime # convert to unique list obslist = list(set(self.obs.values())) # read WRF namelist in WRF work_dir wrf_nml = f90nml.read(self.config['options_wrf']['namelist.input']) for obs in obslist: # read obsproc namelist obsproc_nml = f90nml.read(os.path.join (self.obsproc_dir, 'namelist.obsproc.3dvar.wrfvar-tut')) # create obsproc workdir self.create_obsproc_dir(obs[0]) # copy observation in LITTLE_R format to obsproc_dir shutil.copyfile(os.path.join( self.config['filesystem']['obs_dir'], obs[1]), os.path.join(obs[0], obs[1])) # sync obsproc namelist variables with wrf namelist.input obsproc_nml['record1']['obs_gts_filename'] = obs[1] obsproc_nml['record8']['nesti'] = (wrf_nml['domains'][ 'i_parent_start']) obsproc_nml['record8']['nestj'] = (wrf_nml['domains'][ 'j_parent_start']) obsproc_nml['record8']['nestix'] = wrf_nml['domains']['e_we'] obsproc_nml['record8']['nestjx'] = wrf_nml['domains']['e_sn'] obsproc_nml['record8']['numc'] = wrf_nml['domains']['parent_id'] obsproc_nml['record8']['dis'] = wrf_nml['domains']['dx'] obsproc_nml['record8']['maxnes'] = wrf_nml['domains']['max_dom'] # set time_analysis, time_window_min, time_window_max # check if both datestart and dateend are a datetime instance if not isinstance(datestart, datetime): raise TypeError("datestart must be an instance of datetime") obsproc_nml['record2'][ 'time_analysis'] = datetime.strftime(datestart, '%Y-%m-%d_%H:%M:%S') obsproc_nml['record2']['time_window_min'] = datetime.strftime( datestart - timedelta(minutes=15), '%Y-%m-%d_%H:%M:%S') obsproc_nml['record2']['time_window_max'] = datetime.strftime( datestart + timedelta(minutes=15), '%Y-%m-%d_%H:%M:%S') # save obsproc_nml utils.silentremove(os.path.join(obs[0], 'namelist.obsproc')) obsproc_nml.write(os.path.join(obs[0], 'namelist.obsproc')) def get_obsproc_dirs(self): ''' get list of observation names and workdirs for obsproc ''' # initialize variables obsnames, obsproc_workdirs = [], [] for dom in range(1, self.max_dom + 1): try: obsname = self.config['filesystem']['obs_filename_d' + str(dom)] obsnames.append(obsname) obsproc_workdirs.append(os.path.join( self.config['filesystem']['work_dir'], 'obsproc', obsname)) except KeyError: obsname = self.config['filesystem']['obs_filename'] obsnames.append(obsname) obsproc_workdirs.append(os.path.join( self.config['filesystem']['work_dir'], 'obsproc', obsname)) # merge everything into a dict # domain: (workdir, obsname) obs = dict(zip(range(1, self.max_dom + 1), zip(obsproc_workdirs, obsnames))) return obs def create_obsproc_dir(self, workdir): ''' symlink all files required to run obsproc.exe into obsproc workdir ''' # cleanup utils.silentremove(workdir) # create work directory utils._create_directory(workdir) # symlink error files files = ['DIR.txt', 'HEIGHT.txt', 'PRES.txt', 'RH.txt', 'TEMP.txt', 'UV.txt', 'obserr.txt'] for fl in files: os.symlink(os.path.join(self.obsproc_dir, fl), os.path.join(workdir, fl)) # symlink obsproc.exe os.symlink(os.path.join(self.obsproc_dir, 'src', 'obsproc.exe'), os.path.join(workdir, 'obsproc.exe')) def obsproc_run(self): ''' run obsproc.exe ''' obslist = list(set(self.obs.values())) obsproc_dir = obslist[0][0] # TODO: check if output is file is created and no errors have occurred j_id = None if len(self.config['options_slurm']['slurm_obsproc.exe']): # run using slurm if j_id: mid = "--dependency=afterok:%d" % j_id obsproc_command = ['sbatch', mid, self.config['options_slurm']['slurm_obsproc.exe']] else: obsproc_command = ['sbatch', self.config['options_slurm']['slurm_obsproc.exe']] utils.check_file_exists(obsproc_command[-1]) try: res = subprocess.check_output(obsproc_command, cwd=obsproc_dir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('Obsproc failed %s:' % obsproc_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: # run locally subprocess.check_call(os.path.join(obsproc_dir, 'obsproc.exe'), cwd=obsproc_dir, stdout=utils.devnull(), stderr=utils.devnull()) return None def prepare_symlink_files(self, domain): ''' prepare WRFDA directory ''' # set domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) # read obsproc namelist obsproc_nml = f90nml.read(os.path.join(self.obs[domain][0], 'namelist.obsproc')) # symlink da_wrfvar.exe, LANDUSE.TBL, be.dat.cv3 os.symlink(os.path.join( self.config['filesystem']['wrfda_dir'], 'var/da/da_wrfvar.exe' ), os.path.join(wrfda_workdir, 'da_wrfvar.exe')) if self.check_cv5_cv7(): # symlink the correct be.dat from the list os.symlink(self.wrfda_be_dat, os.path.join(wrfda_workdir, 'be.dat')) else: # cv3 os.symlink(os.path.join( self.config['filesystem']['wrfda_dir'], 'var/run/be.dat.cv3' ), os.path.join(wrfda_workdir, 'be.dat')) os.symlink(os.path.join( self.config['filesystem']['wrfda_dir'], 'run/LANDUSE.TBL' ), os.path.join(wrfda_workdir, 'LANDUSE.TBL')) # symlink output of obsproc os.symlink(os.path.join (self.obs[domain][0], 'obs_gts_' + obsproc_nml['record2']['time_analysis'] + '.3DVAR' ), os.path.join(wrfda_workdir, 'ob.ascii')) def create_parame(self, parame_type, domain): # set domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) filename = os.path.join(wrfda_workdir, 'parame.in') utils.silentremove(filename) # add configuration to parame.in file parame = open(filename, 'w') # open file if parame_type == 'lower': # start config file lower boundary conditions parame.write("""&control_param da_file = './fg' wrf_input = './wrfinput_d01' domain_id = 1 cycling = .true. debug = .true. update_low_bdy = .true. update_lsm = .true. var4d_lbc = .false. iswater = 16 / """) # end config file lower boundary conditions else: # start config file lateral boundary conditions parame.write("""&control_param da_file = '/home/haren/model/WRFV3/run2/wrfinput_d01' wrf_bdy_file = './wrfbdy_d01' domain_id = 1 cycling = .true. debug = .true. update_low_bdy = .false. update_lateral_bdy = .true. update_lsm = .false. var4d_lbc = .false. / """) # end config file lateral boundary conditions parame.close() # close file def prepare_wrfda_namelist(self, domain): # set domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) # read WRFDA namelist, use namelist.wrfda as supplied in config.json # if not supplied, fall back to default from WRFDA if utils.check_file_exists(self.config['options_wrfda'][ 'namelist.wrfda'], boolean=True): wrfda_namelist = self.config['options_wrfda']['namelist.wrfda'] else: wrfda_namelist = os.path.join(self.config['filesystem'][ 'wrfda_dir'], 'var/test/tutorial/namelist.input') wrfda_nml = f90nml.read(wrfda_namelist) # read WRF namelist in WRF work_dir wrf_nml = f90nml.read(os.path.join (self.config['filesystem']['wrf_run_dir'], 'namelist.input')) # set domain specific information in namelist for var in ['e_we', 'e_sn', 'e_vert', 'dx', 'dy']: # get variable from ${RUNDIR}/namelist.input var_value = wrf_nml['domains'][var] # set domain specific variable in WRDFA_WORKDIR/namelist.input wrfda_nml['domains'][var] = var_value[domain - 1] for var in ['mp_physics', 'ra_lw_physics', 'ra_sw_physics', 'radt', 'sf_sfclay_physics', 'sf_surface_physics', 'bl_pbl_physics', 'cu_physics', 'cudt', 'num_soil_layers']: # get variable from ${RUNDIR}/namelist.input var_value = wrf_nml['physics'][var] # set domain specific variable in WRDFA_WORKDIR/namelist.input try: wrfda_nml['physics'][var] = var_value[domain - 1] except TypeError: wrfda_nml['physics'][var] = var_value obsproc_nml = f90nml.read(os.path.join (self.obs[domain][0], 'namelist.obsproc')) # sync wrfda namelist with obsproc namelist wrfda_nml['wrfvar18']['analysis_date'] = (obsproc_nml['record2'][ 'time_analysis']) wrfda_nml['wrfvar21']['time_window_min'] = (obsproc_nml['record2'][ 'time_window_min']) wrfda_nml['wrfvar22']['time_window_max'] = (obsproc_nml['record2'][ 'time_window_max']) if self.check_cv5_cv7(): wrfda_nml['wrfvar7']['cv_options'] = int(self.config[ 'options_wrfda'][ 'cv_type']) wrfda_nml['wrfvar6']['max_ext_its'] = 2 wrfda_nml['wrfvar5']['check_max_iv'] = True else: wrfda_nml['wrfvar7']['cv_options'] = 3 tana = utils.return_validate(obsproc_nml ['record2']['time_analysis'][:-6]) wrfda_nml['time_control']['start_year'] = tana.year wrfda_nml['time_control']['start_month'] = tana.month wrfda_nml['time_control']['start_day'] = tana.day wrfda_nml['time_control']['start_hour'] = tana.hour wrfda_nml['time_control']['end_year'] = tana.year wrfda_nml['time_control']['end_month'] = tana.month wrfda_nml['time_control']['end_day'] = tana.day wrfda_nml['time_control']['end_hour'] = tana.hour # save changes to wrfda_nml utils.silentremove(os.path.join(wrfda_workdir, 'namelist.input')) wrfda_nml.write(os.path.join(wrfda_workdir, 'namelist.input')) def check_cv5_cv7(self): ''' return True if cv_type=5 or cv_type=7 is set and be.dat is defined (and exist on filesystem) for the outer domain in config.json ''' if (int(self.config['options_wrfda']['cv_type']) in [5, 7]): # check if be.dat is a filepath or an array of filepaths if isinstance(self.config['options_wrfda']['be.dat'], str): # option is a filepath self.wrfda_be_dat = self.config['options_wrfda']['be.dat'] elif isinstance(self.config['options_wrfda']['be.dat'], list): if len(self.config['options_wrfda']['be.dat']) == 1: # lenght == 1, so threat the first element as a str case month_idx = 0 elif len(self.config['options_wrfda']['be.dat']) == 12: # there is one be.dat matrix for each month # find month number from self.datestart month_idx = self.datestart.month - 1 else: # list but not of length 1 or 12 raise IOError("config['options_wrfda']['be.dat'] ", "should be a string or a ", "list of length 1 or 12. Found a list of ", "length ", str(len(self.config['options_wrfda'][ 'be.dat']))) self.wrfda_be_dat = self.config[ 'options_wrfda']['be.dat'][month_idx] else: # not a list or str raise TypeError("unkonwn type for be.dat configuration:", type(self.config['options_wrfda']['be.dat'])) return utils.check_file_exists( self.wrfda_be_dat, boolean=True) def prepare_wrfda(self): ''' prepare WRFDA ''' # prepare a WRFDA workdirectory for each domain for domain in range(1, self.max_dom+1): self.prepare_symlink_files(domain) self.prepare_wrfda_namelist(domain) def wrfvar_run(self, domain): ''' run da_wrfvar.exe ''' # set domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) logfile = os.path.join(wrfda_workdir, 'log.wrfda_d' + str(domain)) j_id = None if len(self.config['options_slurm']['slurm_wrfvar.exe']): if j_id: mid = "--dependency=afterok:%d" % j_id wrfvar_command = ['sbatch', mid, self.config['options_slurm']['slurm_wrfvar.exe']] else: wrfvar_command = ['sbatch', self.config['options_slurm']['slurm_wrfvar.exe']] utils.check_file_exists(wrfvar_command[-1]) try: res = subprocess.check_output(wrfvar_command, cwd=wrfda_workdir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('Wrfvar failed %s:' %wrfvar_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: # run locally subprocess.check_call([os.path.join(wrfda_workdir, 'da_wrfvar.exe'), '>&!', logfile], cwd=wrfda_workdir, stdout=utils.devnull(), stderr=utils.devnull()) def prepare_updatebc(self, datestart): # prepare a WRFDA workdirectory for each domain for domain in range(1, self.max_dom+1): # TODO: add check for domain is int # define domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) # general functionality independent of boundary type in parame.in if os.path.exists(wrfda_workdir): shutil.rmtree(wrfda_workdir) # remove wrfda_workdir utils._create_directory(os.path.join(wrfda_workdir, 'var', 'da')) # define parame.in file self.create_parame('lower', domain) # symlink da_update_bc.exe os.symlink(os.path.join( self.config['filesystem']['wrfda_dir'], 'var/da/da_update_bc.exe' ), os.path.join(wrfda_workdir, 'da_update_bc.exe')) # copy wrfbdy_d01 file (lateral boundaries) to WRFDA_WORKDIR shutil.copyfile(os.path.join(self.rundir, 'wrfbdy_d01'), os.path.join(wrfda_workdir, 'wrfbdy_d01')) # set parame.in file for updating lower boundary first self.prepare_updatebc_type('lower', datestart, domain) def prepare_updatebc_type(self, boundary_type, datestart, domain): # set domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) if (boundary_type == 'lower'): # define parame.in file self.create_parame(boundary_type, domain) # copy first guess (wrfout in wrfinput format) for WRFDA first_guess = os.path.join(self.rundir, ('wrfvar_input_d0' + str(domain) + '_' + datetime.strftime (datestart, '%Y-%m-%d_%H:%M:%S'))) try: shutil.copyfile(first_guess, os.path.join(wrfda_workdir, 'fg')) except Exception: shutil.copyfile(os.path.join (self.rundir, 'wrfinput_d0' + str(domain)), os.path.join(wrfda_workdir, 'fg')) # read parame.in file parame = f90nml.read(os.path.join(wrfda_workdir, 'parame.in')) # set domain in parame.in parame['control_param']['domain_id'] = domain # set wrf_input (IC from WPS and WRF real) parame['control_param']['wrf_input'] = str(os.path.join( self.rundir, 'wrfinput_d0' + str(domain))) # save changes to parame.in file utils.silentremove(os.path.join(wrfda_workdir, 'parame.in')) parame.write(os.path.join(wrfda_workdir, 'parame.in')) elif (boundary_type == 'lateral'): # define parame.in file self.create_parame(boundary_type, domain) # read parame.in file parame = f90nml.read(os.path.join(wrfda_workdir, 'parame.in')) # set output from WRFDA parame['control_param']['da_file'] = os.path.join(wrfda_workdir, 'wrfvar_output') # save changes to parame.in file utils.silentremove(os.path.join(wrfda_workdir, 'parame.in')) parame.write(os.path.join(wrfda_workdir, 'parame.in')) else: raise Exception('unknown boundary type') def updatebc_run(self, domain): # set domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) # run da_update_bc.exe j_id = None if len(self.config['options_slurm']['slurm_updatebc.exe']): if j_id: mid = "--dependency=afterok:%d" % j_id updatebc_command = ['sbatch', mid, self.config[ 'options_slurm']['slurm_updatebc.exe']] else: updatebc_command = ['sbatch', self.config[ 'options_slurm']['slurm_updatebc.exe']] try: res = subprocess.check_output(updatebc_command, cwd=wrfda_workdir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('Updatebc failed %s:' % updatebc_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: # run locally subprocess.check_call(os.path.join (wrfda_workdir, 'da_update_bc.exe'), cwd=wrfda_workdir, stdout=utils.devnull(), stderr=utils.devnull()) def wrfda_post(self, datestart): ''' Move files into WRF run dir after all data assimilation steps have completed ''' # prepare a WRFDA workdirectory for each domain for domain in range(1, self.max_dom+1): # set domain specific workdir wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) if (domain == 1): # copy over updated lateral boundary conditions to RUNDIR # only for outer domain utils.silentremove(os.path.join(self.rundir, 'wrfbdy_d01')) shutil.copyfile(os.path.join(wrfda_workdir, 'wrfbdy_d01'), os.path.join(self.rundir, 'wrfbdy_d01')) # copy log files datestr = datetime.strftime(datestart, '%Y-%m-%d_%H:%M:%S') rsl_out_name = 'wrfda_rsl_out_' + datestr statistics_out_name = 'wrfda_statistics_' + datestr try: shutil.copyfile(os.path.join (wrfda_workdir, 'rsl.out.0000'), os.path.join(self.rundir, rsl_out_name)) except IOError: pass try: shutil.copyfile(os.path.join (wrfda_workdir, 'statistics'), os.path.join(self.rundir, statistics_out_name)) except IOError: pass # copy wrfvar_output_d0${domain} to ${RUNDIR}/wrfinput_d0${domain} utils.silentremove(os.path.join (self.rundir, 'wrfinput_d0' + str(domain))) if not self.low_only: shutil.copyfile(os.path.join(wrfda_workdir, 'wrfvar_output'), os.path.join(self.rundir, 'wrfinput_d0' + str(domain))) else: shutil.copyfile(os.path.join(wrfda_workdir, 'fg'), os.path.join(self.rundir, 'wrfinput_d0' + str(domain))) <file_sep>/requirements.txt Jinja2==2.8 MarkupSafe==0.23 PyYAML>=4.2b1 f90nml python-dateutil==2.7.3 astropy==2.0.9 pathos==0.2.2.1 netCDF4 pyOpenSSL <file_sep>/wrfpy/cylc/wps_run.py #!/usr/bin/env python import argparse import datetime import time from wrfpy.wps import wps from wrfpy import utils from dateutil.relativedelta import relativedelta def wps_run(): ''' Initialize WPS timestep ''' WPS = wps() # initialize object WPS._run_geogrid() WPS._run_ungrib() WPS._run_metgrid() def main(): ''' Main function to run wps ''' wps_run() if __name__=="__main__": wps_run() <file_sep>/wrfpy/readObsTemperature.py #!/usr/bin/env python ## from wrfpy.config import config import csv import os import astral from netCDF4 import Dataset from netCDF4 import date2num import numpy as np import bisect from datetime import datetime import glob from pathos.multiprocessing import ProcessPool as Pool class readObsTemperature(config): def __init__(self, dtobj, nstationtypes=None, dstationtypes=None): config.__init__(self) # optional define station types to be used self.nstationtypes = nstationtypes # stationtypes at night self.dstationtypes = dstationtypes # stationtypes during daytime # define datestr datestr = datetime.strftime(dtobj, '%Y-%m-%d_%H:%M:%S') # define name of csv file self.wrf_rundir = self.config['filesystem']['work_dir'] fname = 'obs_stations_' + datestr + '.csv' self.csvfile = os.path.join(self.wrf_rundir, fname) try: # try to read an existing csv file self.read_csv(datestr) except IOError: if self.config['options_urbantemps']['urban_stations']: # reading existing csv file failed, start from scratch self.urbStations = self.config['options_urbantemps']['urban_stations'] self.verify_input() self.obs_temp_p(dtobj) self.write_csv(datestr) else: raise def verify_input(self): ''' verify input and create list of files ''' try: f = Dataset(self.urbStations, 'r') f.close() self.filelist = [self.urbStations] except IOError: # file is not a netcdf file, assuming a txt file containing a # list of netcdf files if os.path.isdir(self.urbStations): # path is actually a directory, not a file self.filelist = glob.glob(os.path.join(self.urbStations, '*nc')) else: # re-raise error raise def obs_temp_p(self, dtobj): ''' get observed temperature in amsterdam parallel ''' self.dtobjP = dtobj pool = Pool() obs = pool.map(self.obs_temp, self.filelist) self.obs = [ob for ob in obs if ob is not None] def obs_temp(self, f): ''' get observed temperature in amsterdam per station ''' try: obs = Dataset(f, 'r') obs_lon = obs.variables['longitude'][0] obs_lat = obs.variables['latitude'][0] elevation = 0 try: stationtype = obs.stationtype except AttributeError: stationtype = None stobs = (obs_lat, obs_lon, elevation, stationtype) use_station = self.filter_stationtype(stobs, self.dtobjP) if use_station: dt = obs.variables['time'] # convert datetime object to dt.units units dtobj_num = date2num(self.dtobjP, units=dt.units, calendar=dt.calendar) # make use of the property that the array is already # sorted to find the closest date try: ind = bisect.bisect_left(dt[:], dtobj_num) except RuntimeError: return if ((ind == 0) or (ind == len(dt))): return None else: am = np.argmin([abs(dt[ind]-dtobj_num), abs(dt[ind-1]-dtobj_num)]) if (am == 0): idx = ind else: idx = ind - 1 if abs((dt[:]-dtobj_num)[idx]) > 900: # ignore observation if time difference # between model and observation is > 15 minutes return None temp = obs.variables['temperature'][idx] sname = f[:] # stationname obs.close() # append results to lists obs_temp = temp obs_stype = stationtype obs_sname= sname except IOError: return None except AttributeError: return None try: return (obs_lat, obs_lon, obs_temp, obs_stype, obs_sname) except UnboundLocalError: return None def filter_stationtype(self, stobs, dtobj): ''' check if it is day or night based on the solar angle construct location ''' lat = stobs[0] lon = stobs[1] elevation = 0 # placeholder loc = astral.Location(info=('name', 'region', lat, lon, 'UTC', elevation)) solar_elevation = loc.solar_elevation(dtobj) # set stime according to day/night based on solar angle if (solar_elevation > 0): stime = 'day' else: stime = 'night' if ((stime == 'day') and self.dstationtypes): try: mask = any([x.lower() in stobs[3].lower() for x in self.dstationtypes]) except AttributeError: mask = False elif ((stime == 'night') and self.nstationtypes): try: mask = any([x.lower() in stobs[3].lower() for x in self.nstationtypes]) except AttributeError: mask = False else: mask = True return mask def write_csv(self, datestr): ''' write output of stations used to csv file ''' with open(self.csvfile, 'wb') as out: csv_out = csv.writer(out) csv_out.writerow(['lat', 'lon', 'temperature', 'stationtype', 'stationname']) for row in self.obs: csv_out.writerow(row) def read_csv(self, datestr): ''' read station temperatures from csv file ''' # initialize variables in csv file obs_lat = [] obs_lon = [] obs_temp = [] obs_stype = [] obs_sname = [] # start reading csv file with open(self.csvfile, 'r') as inp: reader = csv.reader(inp) next(reader) # skip header for row in reader: # append variables obs_lat.append(float(row[0])) obs_lon.append(float(row[1])) obs_temp.append(float(row[2])) obs_stype.append(str(row[3])) obs_sname.append(str(row[4])) # zip variables self.obs = zip(obs_lat, obs_lon, obs_temp, obs_stype, obs_sname) <file_sep>/README.rst .. image:: https://img.shields.io/badge/License-Apache%202.0-blue.svg :target: https://opensource.org/licenses/Apache-2.0 .. image:: https://travis-ci.org/ERA-URBAN/wrfpy.svg?branch=master :target: https://travis-ci.org/ERA-URBAN/wrfpy .. image:: https://zenodo.org/badge/DOI/10.5281/zenodo.1420918.svg :target: https://doi.org/10.5281/zenodo.1420918 .. image:: https://badge.fury.io/py/WRFpy.svg :target: https://badge.fury.io/py/WRFpy WRFpy ===== What is WRFpy: ~~~~~~~~~~~~~~ WRFpy is a python application that provides an easy way to set up, run, and monitor (long) Weather Research and Forecasting (WRF) simulations. It provides a simple user-editable JSON configuration file and integrates with Cylc to access distributed computing and storage resources as well as monitoring. Optionally, WRFpy allows for data assimilation using WRF data assimilation system (WRFDA) and postprocessing of wrfinput files using the NCEP Unified Post Processing System (UPP). Installation ~~~~~~~~~~~~ WRFpy is installable via pip: :: pip install wrfpy Usage ~~~~~ WRFpy provides functionality depending on the used command-line switches: :: usage: wrfpy [-h] [--init] [--create] [--basedir BASEDIR] suitename WRFpy positional arguments: suitename name of suite optional arguments: -h, --help show this help message and exit --init Initialize suite (default: False) --create Create suite config (default: False) --basedir BASEDIR basedir in which suites are installed (default: ${HOME}/cylc-suites) In order to set up a new cylc suite, we first need to initialize one. This is done using the following command: :: wrfpy --init testsuite This creates a configuration file (config.json) that needs to be filled in by the user before continuing. WRFpy points the user to the location of this file. After the configuration file has been filled, it is time to create the actual configuration that will be used by the CYLC workflow engine. To create the CYLC suite, use the following command: :: wrfpy --create testsuite The final configuration lives in a file called suite.rc. If you want to make further (specialized) changes to the workflow by adding/tweaking steps, you can directly edit the suite.rc file with your favorite editor. Now it is time to register the suite with CYLC. CYLC is available at :: https://cylc.github.io/cylc/ and has great documentation. From now on you are using CYLC to control your WRF runs. Please consult the CYLC documentation for the relevant commands. <file_sep>/wrfpy/utils.py #!/usr/bin/env python3 ''' description: Utilities used in wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' import logging import sys import os # define global LOG variables DEFAULT_LOG_LEVEL = 'debug' LOG_LEVELS = {'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL} LOG_LEVELS_LIST = LOG_LEVELS.keys() # LOG_FORMAT = '%(asctime)-15s %(message)s' LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s' DATE_FORMAT = "%Y/%m/%d/%H:%M:%S" logger = None def devnull(): ''' define devnull based on python version ''' if sys.version_info >= (3, 3): from subprocess import DEVNULL as devnull elif sys.version_info >= (2, 4): devnull = open(os.devnull, 'wb') else: assert sys.version_info >= (2, 4) return devnull def silentremove(filename): ''' Remove a file or directory without raising an error if the file or directory does not exist ''' import errno import shutil try: os.remove(filename) except OSError as e: if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory if e.errno == errno.EISDIR: shutil.rmtree(filename) else: raise # re-raise exception if a different error occured def return_validate(date_text, format='%Y-%m-%d_%H'): ''' validate date_text and return datetime.datetime object ''' from datetime import datetime try: date_time = datetime.strptime(date_text, format).replace(tzinfo=None) except ValueError: logger.error('Incorrect date format, should be %s' % format) raise ValueError('Incorrect date format, should be %s' % format) return date_time def check_file_exists(filename, boolean=False): ''' check if file exists and is readable, else raise IOError ''' try: with open(filename): if boolean: return True else: pass # file exists and is readable, nothing else to do except IOError: if boolean: return False else: # file does not exist OR no read permissions logger.error('Unable to open file: %s' % filename) raise # re-raise exception def validate_time_wrfout(wrfout, current_time): ''' Validate if current_time is in wrfout file ''' # get list of timesteps in wrfout file (list of datetime objects) time_steps = timesteps_wrfout(wrfout) # convert current_time to datetime object ctime = return_validate(current_time) if ctime not in time_steps: message = ('Time ' + current_time + 'not found in wrfout file: ' + wrfout) logger.error(message) raise ValueError(message) def timesteps_wrfout(wrfout): ''' return a list of timesteps (as datetime objects) in a wrfout file Input variables: - wrfout: path to a wrfout file ''' from netCDF4 import Dataset as ncdf from datetime import timedelta check_file_exists(wrfout) # check if wrfout file exists # read time information from wrfout file ncfile = ncdf(wrfout, format='NETCDF4') # minutes since start of simulation, rounded to 1 decimal float tvar = [round(nc, 0) for nc in ncfile.variables['XTIME'][:]] ncfile.close() # get start date from wrfout filename time_string = wrfout[-19:-6] start_time = return_validate(time_string) # times in netcdf file time_steps = [start_time + timedelta(minutes=step) for step in tvar] return time_steps def datetime_to_string(dtime, format='%Y-%m-%d_%H'): ''' convert datetime object to string. Standard format is 'YYYY-MM-DD_HH' Input variables: - dtime: datetime object - (optional) format: string format to return ''' from datetime import datetime # check if dtime is of instance datetime if not isinstance(dtime, datetime): message = 'input variable dtime is not of type datetime' logger.error(message) raise IOError(message) # return datetime as a string return dtime.strftime(format) def start_logging(filename, level=DEFAULT_LOG_LEVEL): ''' Start logging with given filename and level. ''' global logger if logger is None: logger = logging.getLogger() else: # wish there was a logger.close() for handler in logger.handlers[:]: # make a copy of the list logger.removeHandler(handler) logger.setLevel(LOG_LEVELS[level]) formatter = logging.Formatter(LOG_FORMAT, datefmt=DATE_FORMAT) fh = logging.FileHandler(filename) fh.setFormatter(formatter) logger.addHandler(fh) return logger def get_logger(): pass def datetime_range(start, end, delta): ''' Return a generator of all timesteps between two datetime.date(time) objects. Time between timesteps is provided by the argument delta. ''' import datetime current = start if not isinstance(delta, datetime.timedelta): try: delta = datetime.timedelta(**delta) except TypeError: message = ('delta argument in utils.datetime_range should be of ', 'a mapping of datetime.timedelta type') logger.error(message) raise TypeError(message) while current < end: yield current current += delta def excepthook(*args): ''' Replace sys.excepthook with custom handler so any uncaught exception gets logged ''' logger.error('Uncaught exception:', exc_info=args) def _create_directory(path): ''' Create a directory if it does not exist yet ''' import errno try: os.makedirs(path) except OSError as e: if e.errno != errno.EEXIST: # directory already exists, no problem raise # re-raise exception if a different error occured def get_wrfpy_path(): ''' get the path of wrfpy installation ''' import wrfpy return os.path.dirname(os.path.realpath(wrfpy.__file__)) def testjob(j_id): import subprocess command = "squeue -j %s" % j_id output = subprocess.check_output(command.split()) try: if j_id == int(output.split()[-8]): return True else: return False except ValueError: return False def testjobsucces(j_id): import subprocess command = "sacct -j %s --format=state" % j_id output = subprocess.check_output(command.split()) if any(x in ['CANCELED', 'FAILED', 'TIMEOUT'] for x in output.split()): raise IOError('slurm command failed') else: return True def waitJobToFinish(j_id): import time while True: time.sleep(1) if not testjob(j_id): testjobsucces(j_id) break def convert_cylc_time(string): import datetime import dateutil.parser try: return datetime.datetime.strptime( string, '%Y%m%dT%H00+01').replace(tzinfo=None) except ValueError: return dateutil.parser.parse(string).replace(tzinfo=None) def get_max_dom(namelist): ''' get maximum domain number from WRF namelist.input ''' import f90nml wrf_nml = f90nml.read(namelist) # maximum domain number return wrf_nml['domains']['max_dom'] def days_hours_minutes_seconds(td): ''' return days, hours, minutes, seconds input: datetime.timedelta ''' return (td.days, td.seconds//3600, (td.seconds//60) % 60, td.seconds % 60) <file_sep>/wrfpy/cylc/wrfda_obsproc_run.py #!/usr/bin/env python import argparse import datetime import time from wrfpy import utils from wrfpy.wrfda import wrfda def obsproc_run(datestart): ''' Initialize WPS timestep ''' WRFDA = wrfda(datestart) # initialize object WRFDA.obsproc_run() def main(datestring): ''' Main function to initialize WPS timestep: - converts cylc timestring to datetime object - calls wps_init() ''' dt = utils.convert_cylc_time(datestring) obsproc_run(dt) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize obsproc.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') # parse arguments args = parser.parse_args() # call main main(args.datestring) <file_sep>/wrfpy/bumpskin.py #!/usr/bin/env python2 from netCDF4 import Dataset import numpy from geopy.distance import vincenty from wrfpy.config import config from wrfpy import utils from wrfpy.readObsTemperature import readObsTemperature import os from datetime import datetime import operator from numpy import unravel_index from numpy import shape as npshape import glob import statsmodels.api as sm import csv import numpy as np import f90nml from scipy import interpolate from astropy.convolution import convolve def return_float_int(value): try: return int(value.strip(',')) except ValueError: return float(value.strip(',')) def convert_to_number(list): if len(list) == 0: return list elif len(list) == 1: return return_float_int(list[0]) elif len(list) > 1: return [return_float_int(value) for value in list] else: return list def reg_m(y, x): ones = numpy.ones(len(x[0])) X = sm.add_constant(numpy.column_stack((x[0], ones))) for ele in x[1:]: X = sm.add_constant(numpy.column_stack((ele, X))) results = sm.OLS(y, X).fit() return results def find_gridpoint(lat_in, lon_in, lat, lon): ''' lat_in, lon_in: lat/lon coordinate of point of interest lat, lon: grid of lat/lon to find closest index of gridpoint ''' # extract window surrounding point lon_window = lon[(lon >= lon_in - 0.10) & (lon <= lon_in + 0.10) & (lat >= lat_in - 0.10) & (lat <= lat_in + 0.10)] lat_window = lat[(lon >= lon_in - 0.10) & (lon <= lon_in + 0.10) & (lat >= lat_in - 0.10) & (lat <= lat_in + 0.10)] lonx = lon_window latx = lat_window # calculate distance to each point in the surrounding window distance = [vincenty((lat_in, lon_in), (latx[idx], lonx[idx])).km for idx in range(0, len(lonx))] # find index of closest reference station to wunderground station try: min_index, min_value = min(enumerate(distance), key=operator.itemgetter(1)) lat_sel = latx[min_index] # indices of gridpoint latidx = lat.reshape(-1).tolist().index(lat_sel) (lat_idx, lon_idx) = unravel_index(latidx, npshape(lon)) return lat_idx, lon_idx except ValueError: return None, None class urbparm(config): def __init__(self, dtobj, infile): config.__init__(self) if self.config['options_urbantemps']['ah.csv']: ahcsv = self.config['options_urbantemps']['ah.csv'] self.read_ah_csv(ahcsv, dtobj) self.options = self.read_tbl(infile) self.change_AH() self.write_tbl() def read_ah_csv(self, ahcsv, dtobj): ''' read anthropogenic heat from csv file columns are: yr, month, ah, alh alh column is optional ''' # initialize variables in csv file yr = [] mnth = [] ah = [] alh = [] # optional # start reading csv file with open(ahcsv, 'r') as inp: reader = csv.reader(inp) next(reader) # skip header for row in reader: # append variables yr.append(int(row[0])) mnth.append(int(row[1])) ah.append(float(row[2])) try: alh.append(float(row[3])) except IndexError: alh.append(None) yr = np.array(yr) mnth = np.array(mnth) ah = np.array(ah) alh = np.array(alh) self.ah = ah[(yr == dtobj.year) & (mnth == dtobj.month)][0] if not float(self.ah) > 0: self.ah = None self.alh = alh[(yr == dtobj.year) & (mnth == dtobj.month)][0] if not float(self.alh) > 0: self.alh = None @staticmethod def read_tbl(tblfile): ''' Read URBPARM.TBL ''' COMMENT_CHAR = '#' OPTION_CHAR = ':' # process GEOGRID.TBL options = {} with open(tblfile) as openfileobject: for line in openfileobject: # First, remove comments: if COMMENT_CHAR in line: # split on comment char, keep only the part before line, comment = line.split(COMMENT_CHAR, 1) # Second, find lines with an option=value: if OPTION_CHAR in line: # split on option char: option, value = line.split(OPTION_CHAR, 1) # strip spaces: option = option.strip() value = convert_to_number(value.strip().split()) # store in dictionary: options[option] = value return options def write_tbl(self): ''' Write URBPARM.TBL to wrf run directory ''' outfile = os.path.join(self.config['filesystem']['wrf_run_dir'], 'URBPARM.TBL') # remove outfile if exists utils.silentremove(outfile) # write new outfile file = open(outfile, 'w') space_sep = ['HSEQUIP', 'AHDIUPRF', 'ALHDIUPRF'] for key in self.options.keys(): if key not in ['STREET PARAMETERS', 'BUILDING HEIGHTS']: try: if key not in space_sep: file.write("{0} : {1}\n".format (key, ", ".join(str(x) for x in self.options.get(key)))) else: file.write("{0} : {1}\n".format (key, " ".join(str(x) for x in self.options.get(key)))) except TypeError: file.write("{0} : {1}\n".format (key, self.options.get(key))) file.close() def change_AH(self): ''' Modify anthropogenic heat with ones in csv file ''' if self.ah: self.options['AH'][-1] = self.ah if self.alh: self.options['ALH'][-1] = self.alh class bumpskin(config): def __init__(self, filename, nstationtypes=None, dstationtypes=None): config.__init__(self) # optional define station types to be used self.nstationtypes = nstationtypes # stationtypes at night self.dstationtypes = dstationtypes # stationtypes during daytime self.wrfda_workdir = os.path.join(self.config ['filesystem']['work_dir'], 'wrfda') self.wrf_rundir = self.config['filesystem']['work_dir'] # verify input self.verify_input(filename) # get number of domains wrf_nml = f90nml.read(self.config['options_wrf']['namelist.input']) ndoms = wrf_nml['domains']['max_dom'] # check if ndoms is an integer and >0 if not (isinstance(ndoms, int) and ndoms > 0): raise ValueError("'domains_max_dom' namelist variable should be an" " integer>0") try: (lat, lon, diffT) = self.findDiffT(1) for domain in range(1, ndoms+1): self.applyToGrid(lat, lon, diffT, domain) except TypeError: pass def verify_input(self, filename): ''' verify input and create list of files ''' try: f = Dataset(filename, 'r') f.close() self.filelist = [filename] except IOError: # file is not a netcdf file, assuming a txt file containing a # list of netcdf files if os.path.isdir(filename): # path is actually a directory, not a file self.filelist = glob.glob(os.path.join(filename, '*nc')) else: # re-raise error raise def get_time(self, wrfinput): ''' get time from wrfinput file ''' wrfinput = Dataset(wrfinput, 'r') # open netcdf file # get datetime string from wrfinput file datestr = ''.join(wrfinput.variables['Times'][0]) # convert to datetime object dtobj = datetime.strptime(datestr, '%Y-%m-%d_%H:%M:%S') wrfinput.close() # close netcdf file return dtobj, datestr @staticmethod def getCoords(wrfinput): ''' Return XLAT,XLONG coordinates from wrfinput file ''' wrfinput = Dataset(wrfinput, 'r') # open netcdf file lat = wrfinput.variables['XLAT'][0, :] lon = wrfinput.variables['XLONG'][0, :] lu_ind = wrfinput.variables['LU_INDEX'][0, :] wrfinput.close() return (lat, lon, lu_ind) @staticmethod def clean_2m_temp(T2, LU_INDEX, iswater, filter=True): ''' Cleanup large spatial 2m temperature fluctuations ''' if filter: # set water points to NaN t2 = T2 t2[LU_INDEX[0, :] == iswater] = np.nan # convolution kernel kernel = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]) # apply convolution kernel T2_filtered = convolve(t2[:], kernel, nan_treatment='interpolate', preserve_nan=True) # handle domain edges T2_filtered[0, :] = T2[0, :] T2_filtered[-1, :] = T2[-1, :] T2_filtered[:, 0] = T2[:, 0] T2_filtered[:, -1] = T2[:, -1] # difference between filtered and original diff = np.abs(T2_filtered - T2) # replace points with large difference # compared to neighboring points T2[diff > 3] = T2_filtered[diff > 3] print('Total points changed in T2 field: ' + str(len(T2[diff > 3]))) print('Average increment: ' + str(np.sum(diff[diff > 3])/len(T2[diff > 3]))) return T2 def get_urban_temp(self, wrfinput, ams): ''' get urban temperature ''' wrfinput = Dataset(wrfinput, 'r') # open netcdf file # get datetime string from wrfinput file LU_IND = wrfinput.variables['LU_INDEX'][0, :] iswater = wrfinput.getncattr('ISWATER') GLW_IND = wrfinput.variables['GLW'][0, :] U10_IND = wrfinput.variables['U10'][0, :] V10_IND = wrfinput.variables['V10'][0, :] UV10_IND = numpy.sqrt(U10_IND**2 + V10_IND**2) lat = wrfinput.variables['XLAT'][0, :] lon = wrfinput.variables['XLONG'][0, :] T2_IND = wrfinput.variables['T2'][0, :] T2_IND = self.clean_2m_temp(T2_IND, LU_IND, iswater, filter=True) T2 = [] U10 = [] V10 = [] GLW = [] LU = [] for point in ams: i_idx, j_idx = find_gridpoint(point[0], point[1], lat, lon) if (i_idx and j_idx): T2.append(T2_IND[i_idx, j_idx]) U10.append(wrfinput.variables['U10'][0, i_idx, j_idx]) V10.append(wrfinput.variables['V10'][0, i_idx, j_idx]) GLW.append(wrfinput.variables['GLW'][0, i_idx, j_idx]) LU.append(wrfinput.variables['LU_INDEX'][0, i_idx, j_idx]) else: T2.append(numpy.nan) U10.append(numpy.nan) V10.append(numpy.nan) GLW.append(numpy.nan) LU.append(numpy.nan) wrfinput.close() UV10 = numpy.sqrt(numpy.array(U10)**2 + numpy.array(V10)**2) return (T2, numpy.array(GLW), UV10, numpy.array(LU), LU_IND, GLW_IND, UV10_IND) def findDiffT(self, domain): ''' calculate increment of urban temperatures and apply increment to wrfinput file in wrfda directory ''' # load netcdf files wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) wrfinput = os.path.join(wrfda_workdir, 'wrfvar_output') # get datetime from wrfinput file dtobj, datestr = self.get_time(wrfinput) # get observed temperatures obs = readObsTemperature(dtobj, nstationtypes=None, dstationtypes=None).obs obs_temp = [obs[idx][2] for idx in range(0, len(obs))] # get modeled temperatures at location of observation stations t_urb, glw, uv10, lu, LU_IND, glw_IND, uv10_IND = self.get_urban_temp( wrfinput, obs) lat, lon, lu_ind = self.getCoords(wrfinput) # get coordinates diffT_station = numpy.array(obs_temp) - numpy.array(t_urb) # calculate median and standard deviation, ignore outliers > 10K # only consider landuse class 1 nanmask = ((~numpy.isnan(diffT_station)) & (lu == 1) & (abs(diffT_station) < 5)) obs = numpy.array(obs) obs = obs[nanmask] diffT_station = diffT_station[nanmask] lu = lu[nanmask] glw = glw[nanmask] uv10 = uv10[nanmask] median = numpy.nanmedian(diffT_station[(abs(diffT_station) < 5)]) std = numpy.nanstd(diffT_station[(abs(diffT_station) < 5)]) print('print diffT station') print(diffT_station[(abs(diffT_station) < 5)]) print('end print diffT station') # depending on the number of observations, calculate the temperature # increment differently if (len(lu) < 3): # no temperature increment for <3 observations print('No temperature increment applied, not enough data.') diffT = numpy.zeros(numpy.shape(glw_IND)) elif ((len(lu) >= 3) & (len(lu) < 5)): # use median if between 3 and 5 observations print('Median temperature increment applied: ' + str(median)) diffT = median * numpy.ones(numpy.shape(glw_IND)) diffT[LU_IND != 1] = 0 else: # fit statistical model # define mask mask = ((diffT_station > median - 2*std) & (diffT_station < median + 2*std) & (lu == 1) & (abs(diffT_station) < 5)) # filter obs obs = obs[mask] # recalculate median median = numpy.nanmedian(diffT_station[mask]) fit = reg_m(diffT_station[mask], [(glw)[mask], uv10[mask]]) # calculate diffT for every gridpoint if fit.f_pvalue <= 0.1: # use fit if significant print('Temperature increment applied from statistical ', + 'fit with values: ' + str(fit.params)) diffT = (fit.params[1] * glw_IND + fit.params[0] * uv10_IND + fit.params[2]) else: # use median print('Median temperature increment applied: ' + str(median)) diffT = median * numpy.ones(numpy.shape(glw_IND)) diffT[LU_IND != 1] = 0 # set to 0 if LU_IND!=1 return (lat, lon, diffT) def applyToGrid(self, lat, lon, diffT, domain): # load netcdf files wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(domain)) wrfinputFile = os.path.join(wrfda_workdir, 'wrfvar_output') lat2, lon2, lu_ind2 = self.getCoords(wrfinputFile) # get datetime from wrfinput file dtobj, datestr = self.get_time(wrfinputFile) # if not ((lat==lat2) and (lon==lon2)) we need to interpolate if not (np.array_equal(lat, lat2) and np.array_equal(lon, lon2)): # do interpolation to get new diffT diffT = interpolate.griddata( (lon.reshape(-1), lat.reshape(-1)), diffT.reshape(-1), (lon2.reshape(-1), lat2.reshape(-1)), method='cubic').reshape(np.shape(lon2)) diffT[lu_ind2 != 1] = 0 # set to 0 if LU_IND!=1 # open wrfvar_output (output after data assimilation) self.wrfinput2 = Dataset(os.path.join(wrfda_workdir, 'wrfvar_output'), 'r+') # open wrfvar_input (input before DA (last step previous run) start_date = utils.return_validate( self.config['options_general']['date_start']) if (dtobj == start_date): # very first timestep self.wrfinput3 = Dataset(os.path.join (self.wrf_rundir, ('wrfinput_d0' + str(domain))), 'r') return else: self.wrfinput3 = Dataset(os.path.join (self.wrf_rundir, ('wrfvar_input_d0' + str(domain) + '_' + datestr)), 'r') # define variables to increment # variables_2d = ['TC_URB', 'TR_URB', 'TB_URB', 'TG_URB', 'TS_URB'] # variables_3d = ['TRL_URB', 'TBL_URB', 'TGL_URB', 'TSLB'] # begin determining multiplying factor rhocp = 1231 uc_urb = self.wrfinput2.variables['UC_URB'][:] lp_urb = self.wrfinput2.variables['BUILD_AREA_FRACTION'][:] hgt_urb = self.wrfinput2.variables['BUILD_HEIGHT'][:] lb_urb = self.wrfinput2.variables['BUILD_SURF_RATIO'][:] frc_urb = self.wrfinput2.variables['FRC_URB2D'][:] chc_urb = self.wrfinput2.variables['CHC_SFCDIF'][:] R = numpy.maximum(numpy.minimum(lp_urb/frc_urb, 0.9), 0.1) RW = 1.0 - R HNORM = 2. * hgt_urb * frc_urb / (lb_urb - lp_urb) HNORM[lb_urb <= lp_urb] = 10.0 ZR = numpy.maximum(numpy.minimum(hgt_urb, 100.0), 3.0) h = ZR / HNORM W = 2 * h # set safety margin on W/RW >=8 or else SLUCM could misbehave # make sure to use the same safety margin in module_sf_urban.F W[(W / RW) > 8.0] = ((8.0 / (W / RW)) * W)[(W / RW) > 8.0] CW = numpy.zeros(numpy.shape(uc_urb)) CW[uc_urb > 5] = 7.51 * uc_urb[uc_urb > 5]**0.78 CW[uc_urb <= 5] = 6.15 + 4.18 * uc_urb[uc_urb <= 5] DTW = diffT * (1 + ((RW * rhocp) / (W + RW)) * (chc_urb/CW)) diffT = DTW # change 09/01/2018 diffT = numpy.nan_to_num(diffT) # replace nan by 0 # apply temperature changes TSK = self.wrfinput2.variables['TSK'] TSK[:] = TSK[:] + diffT TB_URB = self.wrfinput2.variables['TB_URB'] TB_URB[:] = TB_URB[:] + diffT TG_URB = self.wrfinput2.variables['TG_URB'] TG_URB[:] = TG_URB[:] + diffT TS_URB = self.wrfinput2.variables['TS_URB'] TS_URB[:] = TS_URB[:] + diffT TGR_URB = self.wrfinput2.variables['TGR_URB'] TGR_URB[:] = TGR_URB[:] + diffT # wall layer temperature try: TBL_URB_factors = self.config['options_urbantemps']['TBL_URB'] except KeyError: # fallback values if none are defined in config # these may not work correctly for other cities than Amsterdam TBL_URB_factors = [0.823, 0.558, 0.379, 0.257] if not (isinstance(TBL_URB_factors, list) and len(TBL_URB_factors) > 1): TBL_URB_factors = [0.823, 0.558, 0.379, 0.257] TBL_URB = self.wrfinput2.variables['TBL_URB'] levs = numpy.shape(self.wrfinput2.variables['TBL_URB'][:])[1] TBL_URB = self.wrfinput2.variables['TBL_URB'] for lev in range(0, levs): try: TBL_URB[0, lev, :] = (TBL_URB[0, lev, :] + diffT * float(TBL_URB_factors[lev])) except IndexError: # no factor for this layer => no increment pass # road layer temperature try: TGL_URB_factors = self.config['options_urbantemps']['TGL_URB'] except KeyError: # fallback values if none are defined in config # these may not work correctly for other cities than Amsterdam TGL_URB_factors = [0.776, 0.170, 0.004] if not (isinstance(TGL_URB_factors, list) and len(TGL_URB_factors) > 1): TGL_URB_factors = [0.776, 0.170, 0.004] TGL_URB = self.wrfinput2.variables['TGL_URB'] levs = numpy.shape(self.wrfinput2.variables['TGL_URB'][:])[1] TGL_URB = self.wrfinput2.variables['TGL_URB'] for lev in range(0, levs): try: TGL_URB[0, lev, :] = (TGL_URB[0, lev, :] + diffT * float(TGL_URB_factors[lev])) except IndexError: # no factor for this layer => no increment pass # adjustment soil for vegetation fraction urban cell try: TSLB_factors = self.config['options_urbantemps']['TSLB'] except KeyError: # fallback values if none are defined in config # these may not work correctly for other cities than Amsterdam TSLB_factors = [0.507, 0.009] if not (isinstance(TSLB_factors, list) and len(TSLB_factors) > 1): TSLB_factors = [0.507, 0.009] TSLB = self.wrfinput2.variables['TSLB'] # after update_lsm TSLB_in = self.wrfinput3.variables['TSLB'] # before update_lsm levs = numpy.shape(self.wrfinput2.variables['TSLB'][:])[1] for lev in range(0, levs): # reset TSLB for urban cells to value before update_lsm TSLB[0, lev, :][lu_ind2 == 1] = TSLB_in[0, lev, :][lu_ind2 == 1] try: TSLB[0, lev, :] = (TSLB[0, lev, :] + diffT * float(TSLB_factors[lev])) except IndexError: pass # close netcdf file self.wrfinput2.close() self.wrfinput3.close() <file_sep>/wrfpy/scripts/wrfpy #!/usr/bin/env python ''' description: Configuration part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' import os import argparse from wrfpy.configuration import configuration def cli_parser(): ''' parse command line arguments ''' parser = argparse.ArgumentParser( description='WRFpy', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--init', action='store_true', help='Initialize suite') parser.add_argument('--create', action='store_true', help='Create suite config') parser.add_argument('--basedir', type=str, default=os.path.join(os.path.expanduser("~"), 'cylc-suites'), help="basedir in which suites are installed") parser.add_argument('suitename', type=str, help='name of suite') results = vars(parser.parse_args()) # either initialize or create a suite, not both if (results['init'] ^ results['create']): configuration(results) else: # print error message to the user, combiniation of --init and --create # is not allowed print("Only one of '--init' and '--create' is allowed.") exit() if __name__ == "__main__": cli_parser() <file_sep>/CHANGELOG.md # Changelog ### 0.2.1 * Check for geo_em files in wps workdir instead of wps install directory ### 0.2.0 * Second Beta release * Cleanup creation of CYLC suite configuration * General cleanup ### 0.1.0 * Beta release <file_sep>/wrfpy/cylc/wrfda_obs.py #!/usr/bin/env python import argparse import datetime import time import shutil from wrfpy.readObsTemperature import readObsTemperature from wrfpy import utils def main(datestring): dt = utils.convert_cylc_time(datestring) readObsTemperature(dt, dstationtypes=['davis', 'vp2', 'vantage']) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize obsproc.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') # parse arguments args = parser.parse_args() # call main main(args.datestring) <file_sep>/wrfpy/cylc/wrf_init.py #!/usr/bin/env python import argparse import datetime import time from wrfpy.wrf import run_wrf from wrfpy import utils def main(datestring, interval): ''' Main function to initialize WPS timestep: - converts cylc timestring to datetime object - calls wrf.__init() and initialize() ''' dt = utils.convert_cylc_time(datestring) WRF = run_wrf() WRF.initialize(dt, dt + datetime.timedelta(hours=interval)) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize WRF step.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') parser.add_argument('interval', metavar='I', type=int, help='Time interval in hours') # parse arguments args = parser.parse_args() # call main main(args.datestring, args.interval) <file_sep>/wrfpy/upp.py #!/usr/bin/env python ''' description: Unified Post Precession (UPP) part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' from wrfpy import utils import glob import subprocess import os import errno from wrfpy.config import config class upp(config): ''' Runs the Universal Post Processor (UPP) for requested time steps in a wrfout file ''' def __init__(self): config.__init__(self) self._set_variables() self._initialize() self._prepare_post_dir() self._set_environment_variables() def _set_variables(self): ''' Define additional control variables for the unipost.exe tool, inherit from global config. ''' self.crtm_dir = os.path.join(self.config['filesystem']['upp_dir'], 'src/lib/crtm2/src/fix') self.post_dir = os.path.join(self.config['filesystem']['upp_dir'], 'postprd') def _initialize(self): ''' Check if archive dir exists, create if not. The archive dir is used to ... ''' # create archive dir utils._create_directory(self.config['filesystem']['upp_archive_dir']) # create post_dir (remove old one if needed) utils.silentremove(self.post_dir) utils._create_directory(self.post_dir) def _prepare_post_dir(self): ''' Create and prepare post_dir ''' #logger.debug('Preparing postprd directory: %s' %config['post_dir']) # create self.post_dir if it does not exist yet utils._create_directory(self.post_dir) # Link all the relevant files need to compute various diagnostics relpath_to_link = ['EmisCoeff/Big_Endian/EmisCoeff.bin', 'AerosolCoeff/Big_Endian/AerosolCoeff.bin', 'CloudCoeff/Big_Endian/CloudCoeff.bin', 'SpcCoeff/Big_Endian/imgr_g11.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/imgr_g11.TauCoeff.bin', 'SpcCoeff/Big_Endian/imgr_g12.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/imgr_g12.TauCoeff.bin', 'SpcCoeff/Big_Endian/imgr_g13.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/imgr_g13.TauCoeff.bin', 'SpcCoeff/Big_Endian/imgr_g15.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/imgr_g15.TauCoeff.bin', 'SpcCoeff/Big_Endian/imgr_mt1r.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/imgr_mt1r.TauCoeff.bin', 'SpcCoeff/Big_Endian/imgr_mt2.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/imgr_mt2.TauCoeff.bin', 'SpcCoeff/Big_Endian/imgr_insat3d.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/imgr_insat3d.TauCoeff.bin', 'SpcCoeff/Big_Endian/amsre_aqua.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/amsre_aqua.TauCoeff.bin', 'SpcCoeff/Big_Endian/tmi_trmm.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/tmi_trmm.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmi_f13.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmi_f13.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmi_f14.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmi_f14.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmi_f15.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmi_f15.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmis_f16.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmis_f16.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmis_f17.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmis_f17.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmis_f18.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmis_f18.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmis_f19.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmis_f19.TauCoeff.bin', 'SpcCoeff/Big_Endian/ssmis_f20.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/ssmis_f20.TauCoeff.bin', 'SpcCoeff/Big_Endian/seviri_m10.SpcCoeff.bin', 'TauCoeff/ODPS/Big_Endian/seviri_m10.TauCoeff.bin', 'SpcCoeff/Big_Endian/v.seviri_m10.SpcCoeff.bin'] # abspath coefficients for crtm2 (simulated synthetic satellites) abspath_coeff= [os.path.join(self.crtm_dir, relpath) for relpath in relpath_to_link ] # abspath wrf_cntrl param file abspath_pf = os.path.join(self.config['filesystem']['upp_dir'], 'parm', 'wrf_cntrl.parm') # concatenate lists of paths abspath_to_link = abspath_coeff + [abspath_pf] # create a symlink for every file in abspath_to_link for fl in abspath_to_link: utils.check_file_exists(fl) # check if file exist and is readable os.symlink(fl, os.path.join(self.post_dir, os.path.basename(fl))) # symlink wrf_cntrl.parm to config['post_dir']/fort.14 os.symlink(abspath_pf, os.path.join(self.post_dir, 'fort.14')) # symlink microphysic's tables - code used is based on mp_physics option # used in the wrfout file os.symlink(os.path.join(self.config['filesystem']['wrf_run_dir'], 'ETAMPNEW_DATA'), os.path.join(self.post_dir, 'nam_micro_lookup.dat')) os.symlink(os.path.join(self.config['filesystem']['wrf_run_dir'], 'ETAMPNEW_DATA.expanded_rain' ), os.path.join(self.post_dir, 'hires_micro_lookup.dat')) def _set_environment_variables(self): ''' Set environment variables ''' #logger.debug('Enter set_environment_variables') os.environ['MP_SHARED_MEMORY'] = 'yes' os.environ['MP_LABELIO'] = 'yes' os.environ['tmmark'] = 'tm00' #logger.debug('Leave set_environment_variables') def _cleanup_output_files(self): ''' Clean up old output files in post_dir ''' #logger.debug('Enter cleanup_output_files') file_ext = [ '*.out', '*.tm00', 'fort.110', 'itag'] files_found = [ f for files in [ glob.glob(os.path.join(self.post_dir, ext)) for ext in file_ext ] for f in files] # try to remove files, raise exception if needed [ utils.silentremove(fl) for fl in files_found ] #logger.debug('Leave cleanup_output_files') def _write_itag(self, wrfout, current_time): ''' Create input file for unipost --------content itag file --------------------------------------- First line is location of wrfout data Second line is required format Third line is the modeltime to process Fourth line is the model identifier (WRF, NMM) ----------------------------------------------------------------- ''' #logger.debug('Enter write_itag') #logger.debug('Time in itag file is: %s' %current_time) # set itag filename and cleanup filename = os.path.join(self.post_dir, 'itag') utils.silentremove(filename) # template of itag file template = """{wrfout} netcdf {current_time}:00:00 NCAR """ # context variables in template context = { "wrfout":wrfout, "current_time":current_time } # create the itag file and write content to it based on the template try: with open(filename, 'w') as itag: itag.write(template.format(**context)) except IOError as e: #logger.error('Unable to write itag file: %s' %filename) print('Unable to write itag file: %s' %filename) raise e # re-raise exception #logger.debug('Leave write_itag') def _run_unipost_step(self, wrfout, current_time, thours): ''' Input variables for the function are: - full path to a wrfout file (regular wrfout naming) - time to run unipost for in format YYYY-MM-DD_HH - thours: TODO add description The following functionality is provided by the function: - validate input parameters - write itag file - run unipost.exe command - rename output - archive output - cleanup output ''' # see if current_time is in wrfout AND validate time format utils.validate_time_wrfout(wrfout, current_time) # extract domain information from wrfout filename domain = int(wrfout[-22:-20]) # write itag file self._write_itag(wrfout, current_time) # run unipost.exe subprocess.check_call(os.path.join(self.config['filesystem']['upp_dir'], 'bin', 'unipost.exe'), cwd=self.post_dir, stdout=utils.devnull(), stderr=utils.devnull()) # rename and archive output self._archive_output(current_time, thours, domain) # cleanup output files self._cleanup_output_files() def run_unipost_file(self, wrfout, frequency=2, use_t0=False): ''' Input variables for the function are: - wrfout: full path to a wrfout file (regular wrfout naming) - (optional) frequency: time interval in hours at which processing should take place - (optional) use_t0: boolean, process time step 0 The function provides the following functionality: description ''' time_steps = utils.timesteps_wrfout(wrfout) # convert to hours since timestep 0 td = [int((t - time_steps[0]).total_seconds()/3600) for t in time_steps] # modulo should be zero if not td[-1]%frequency==0: message = '' # TODO: add error message #logger.error(message) raise IOError(message) else: # create list of booleans where module is 0 modulo = [tdi%frequency==0 for tdi in td] for idx, tstep in enumerate(time_steps): if (not use_t0 and idx==0) or (modulo[idx] is False): continue # convert time step to time string current_time = utils.datetime_to_string(tstep) # run unipost step self._run_unipost_step(wrfout, current_time, td[idx]) def _archive_output(self, current_time, thours, domain): ''' rename unipost.exe output to wrfpost_d0${domain}_time.grb and archive ''' import shutil # verify that domain is an int if not isinstance(domain, int): message = 'domain id should be an integer' #logger.error(message) raise IOError(message) # define original and destination filename origname = 'WRFPRS%02d.tm00' %thours outname = 'wrfpost_d%02d_%s.grb' %(domain, current_time) # rename file and move to archive dir shutil.move(os.path.join(self.post_dir, origname), os.path.join(self.config['filesystem']['upp_archive_dir'], outname)) # check if file is indeed archived utils.check_file_exists(os.path.join(self.config['filesystem']['upp_archive_dir'], outname)) <file_sep>/requirements-rtd.txt numpy sphinx sphinx-autobuild <file_sep>/wrfpy/cylc/wps_init.py #!/usr/bin/env python import argparse import datetime import time from wrfpy.wps import wps from wrfpy import utils def wps_init(datestart, dateend): ''' Initialize WPS timestep ''' WPS = wps() # initialize object WPS._initialize(datestart, dateend) def main(datestring, interval): ''' Main function to initialize WPS timestep: - converts cylc timestring to datetime object - calls wps_init() ''' dt = utils.convert_cylc_time(datestring) wps_init(dt, dt + datetime.timedelta(hours=interval)) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize WPS step.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') parser.add_argument('interval', metavar='I', type=int, help='Time interval in hours') # parse arguments args = parser.parse_args() # call main main(args.datestring, args.interval) <file_sep>/wrfpy/cylc/copy_synop.py #!/usr/bin/env python import argparse import datetime import time from wrfpy import utils from wrfpy.config import config from pynetcdf2littler.wrapper_littler import wrapper_littler from dateutil.relativedelta import relativedelta import os import glob import shutil class copySynop(config): '''' Example script how to copy output files from e.g. prepare_synop.py or combine_synop.py if there are different synop input files for e.g. different days/months ''' def __init__(self, args): config.__init__(self) obsDir = self.config['filesystem']['obs_dir'] obsFilename = self.config['filesystem']['obs_filename'] outputFile = os.path.join(obsDir, obsFilename) dt = utils.convert_cylc_time(args.datestring) # startdate dt1 = datetime.datetime(dt.year, dt.month, 1) dt1s = dt1.strftime('%Y%m%d') # convert to string inputdir = os.path.join(args.inputdir, dt1s) inputFile = os.path.join(inputdir, args.inputfile) # remove existing file utils.silentremove(outputFile) # copy inputfile to location specified in config.json shutil.copyfile(inputFile, outputFile) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize obsproc.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') parser.add_argument('-d', '--inputdir', help='inputdir', required=False, default=os.getcwd()) parser.add_argument('-i', '--inputfile', help='name of inputfile', required=True) # parse arguments args = parser.parse_args() # call main copySynop(args) <file_sep>/setup.py import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "WRFpy", version = "0.2.1", author = "<NAME>", author_email = "<EMAIL>", description = ("A python application that provides an easy way to set up," " run, and monitor (long) Weather Research and Forecasting " " (WRF) simulations."), license = "Apache 2.0", keywords = "WRF cylc workflow WRFDA", url = "https://github.com/ERA-URBAN/wrfpy", packages=['wrfpy'], include_package_data = True, # include everything in source control package_data={'wrfpy': ['cylc/*.py', 'examples/*']}, scripts=['wrfpy/scripts/wrfpy'], long_description=read('README.rst'), classifiers=[ "Development Status :: 4 - Beta", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: Apache Software License", ], install_requires=['numpy', 'Jinja2', 'MarkupSafe', 'PyYAML', 'f90nml', 'python-dateutil', 'astropy', 'pathos', 'netCDF4', 'pyOpenSSL'], ) <file_sep>/wrfpy/config.py #!/usr/bin/env python ''' description: Configuration part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' import json import os from wrfpy import utils import f90nml import yaml class config: ''' description ''' def __init__(self, wrfpy_config=False): global logger wrfpy_dir = os.environ['HOME'] logger = utils.start_logging(os.path.join(wrfpy_dir, 'wrfpy.log')) if not wrfpy_config: try: # get CYLC_SUITE_DEF_PATH environment variable wrfpy_dir = os.environ['CYLC_SUITE_DEF_PATH'] except KeyError: # default back to user home dir in case CYLC is not used wrfpy_dir = os.environ['HOME'] # config.json needs to be in base of wrfpy_dir self.configfile = os.path.join(wrfpy_dir, 'config.json') else: self.configfile = wrfpy_config try: logger.debug('Checking if configuration file exists: %s' %self.configfile) utils.check_file_exists(self.configfile, boolean=False) # read json config file self._read_json() # check config file for consistency and errors except IOError: # create config file self._create_empty_config() else: # check config self._check_config() def _create_empty_config(self): ''' create empty json config file ''' # define keys keys_dir = ['wrf_dir', 'wrf_run_dir', 'wrfda_dir', 'upp_dir', 'wps_dir', 'archive_dir', 'boundary_dir', 'upp_archive_dir', 'work_dir', 'obs_dir', 'obs_filename', 'radar_filepath'] keys_wrf = ['namelist.input', 'urbparm.tbl'] keys_upp = ['upp', 'upp_interval'] keys_wrfda = ['namelist.wrfda', 'wrfda', 'wrfda_type', 'cv_type', 'be.dat'] keys_general = ['date_start', 'date_end', 'boundary_interval', 'ref_lon', 'ref_lat', 'run_hours', 'fix_urban_temps'] keys_wps = ['namelist.wps', 'run_hours', 'vtable', 'geogrid.tbl', 'metgrid.tbl'] keys_slurm = ['slurm_real.exe', 'slurm_wrf.exe', 'slurm_ungrib.exe', 'slurm_metgrid.exe', 'slurm_geogrid.exe', 'slurm_obsproc.exe', 'slurm_updatebc.exe', 'slurm_da_wrfvar.exe'] keys_urbantemps = ['TBL_URB', 'TGL_URB', 'TSLB', 'ah.csv', 'urban_stations'] # create dictionaries config_dir = {key: '' for key in keys_dir} options_general = {key: '' for key in keys_general} options_wrfda = {key: '' for key in keys_wrfda} options_wrf = {key: '' for key in keys_wrf} options_upp = {key: '' for key in keys_upp} options_wps = {key: '' for key in keys_wps} options_slurm = {key: '' for key in keys_slurm} options_urbantemps = {key: '' for key in keys_urbantemps} # combine dictionaries config_out = {} config_out['filesystem'] = config_dir config_out['options_wrf'] = options_wrf config_out['options_wps'] = options_wps config_out['options_upp'] = options_upp config_out['options_slurm'] = options_slurm config_out['options_wrfda'] = options_wrfda config_out['options_general'] = options_general config_out['options_urbantemps'] = options_urbantemps # write json config file with open(self.configfile, 'w') as outfile: json.dump(config_out, outfile,sort_keys=True, indent=4) # print message pointing user to edit config file self._print_config_message() def _print_config_message(self): ''' print message pointing the user to edit the configuration file ''' message = '''>>> A configuration file has been created at %s >>> Please edit the configuration file before continuing.''' %self.configfile print(message) logger.info(message) def _read_json(self): ''' read json config file ''' with open(self.configfile, 'r') as infile: #self.config = json.load(infile) self.config = yaml.safe_load(infile) def _check_config(self): ''' check configuration file ''' self._check_general() # check general options self._check_wrf() # check wrf options self._check_wps() # check wps options self._check_wrfda() # check wrfda self._check_upp() # check upp def _check_wrfda(self): ''' check if wrfda option is set check if wrfda_type is supported check wrfda_dir for consistency ''' if self.config['options_wrfda']['wrfda']: self._check_wrfda_type() self._check_wrfda_dir() def _check_wrfda_type(self): ''' check if wrfda_type in json config file is either 3dvar of 4dvar ''' if (not self.config['options_wrfda']['wrfda_type'].lower() in ['3dvar', '4dvar']): message = ("Only '3dvar' or '4dvar' supported in ", "config['options']['wrfda_type']") logger.error(message) raise IOError(message) def _check_wrfda_dir(self): ''' check if the wrfda directory exist check if obsproc.exe and da_wrfvar.exe executables exist in the wrfda directory ''' # TODO: find out if we can verify that WRFDA dir is 3dvar or 4dvar compiled assert os.path.isdir(self.config['filesystem']['wrfda_dir']), ( 'wrfda directory %s not found' %self.config['filesystem']['wrfda_dir']) # create list of files to check files_to_check = [ os.path.join(self.config['filesystem']['wrfda_dir'], filename) for filename in ['var/obsproc/obsproc.exe', 'var/da/da_wrfvar.exe']] # check if all files in the list exist and are readable [utils.check_file_exists(filename) for filename in files_to_check] def _check_upp(self): if self.config['options_upp']['upp']: # TODO: check UPP interval self._check_upp_dir() def _check_upp_dir(self): assert os.path.isdir(self.config['filesystem']['upp_dir']), ( 'upp directory %s not found' %self.config['filesystem']['upp_dir']) # create list of files to check files_to_check = [ os.path.join(self.config['filesystem']['upp_dir'], filename) for filename in ['bin/unipost.exe', 'parm/wrf_cntrl.parm']] # check if all files in the list exist and are readable [utils.check_file_exists(filename) for filename in files_to_check] def _check_general(self): ''' check general options in json config file - date_start and date_end have a valid format - end_date is after start_date - boundary_interval is an integer ''' # check if start_date and end_date are in valid format start_date = utils.return_validate( self.config['options_general']['date_start']) end_date = utils.return_validate( self.config['options_general']['date_end']) # end_date should be after start_date if (start_date >= end_date): message = 'start_date is after end_date' logger.error(message) raise IOError(message) # check if run_hours is specified run_hours = self.config['options_general']['run_hours'] assert run_hours, "No General run_hours specified in config file" # boundary interval should be an int number of hours assert isinstance(self.config['options_general']['boundary_interval'], int), ('boundary_interval should be given as an ' 'integer in %s' % self.configfile) # boundary interval should not be larger than time between start_date # and end_date assert ((self.config['options_general']['boundary_interval']) <= ( end_date - start_date).total_seconds()), ( 'boundary interval is larger than time between start_date and ' 'end_date') def _check_wps(self): ''' check wps options in json config file ''' # verify that the config option is specified by the user assert (len(self.config['options_wps']['namelist.wps']) > 0), ( 'No WPS namelist.wps specified in config file') # check if specified namelist.wps exist and are readable utils.check_file_exists(self.config['options_wps']['namelist.wps']) # check if run_hours is specified run_hours = self.config['options_wps']['run_hours'] assert run_hours, "No WPS run_hours specified in config file" # check if namelist.wps is in the required format and has all keys needed self._check_namelist_wps() def _check_namelist_wps(self): ''' check if namelist.wps is in the required format and has all keys needed ''' # verify that example namelist.wps exists and is not removed by user basepath = utils.get_wrfpy_path() self.example_file = os.path.join(basepath, 'examples', 'namelist.wps') utils.check_file_exists(self.example_file) # load specified namelist self.user_nml = f90nml.read(self.config['options_wps']['namelist.wps']) # verify that all keys in self.user_nml are also in example namelist self._verify_namelist_wps_keys() # validate the key information specified self._validate_namelist_wps_keys() def _verify_namelist_wps_keys(self): ''' verify that all keys in example_nml are also in user_nml ''' # load example namelist.wps example_nml = f90nml.read(self.example_file) example_keys = example_nml.keys() for section in example_nml.keys(): for key in example_nml[section].keys(): assert self.user_nml[section][key], ( 'Key not found in user specified namelist: %s' %self.config['options_wps']['namelist.wps']) def _validate_namelist_wps_keys(self): ''' verify that user specified namelist.wps contains valid information for all domains specified by the max_dom key ''' pass def _check_wrf(self): ''' check wrf options in json config file ''' # verify that the config option is specified by the user assert (len(self.config['options_wrf']['namelist.input']) > 0), ( 'No WRF namelist.input specified in config file') # check if specified namelist.wps exist and are readable utils.check_file_exists(self.config['options_wrf']['namelist.input']) # check if namelist.input is in the required format and has all keys needed self._check_namelist_wrf() def _check_namelist_wrf(self): ''' check if namelist.input is in the required format and has all keys needed ''' pass <file_sep>/requirements-test.txt coverage pytest pytest-cov<2.6.0 <file_sep>/wrfpy/cylc/retry_wrf.py #!/usr/bin/env python ''' description: WRF part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' from wrfpy.config import config from wrfpy import utils import f90nml import os import shutil import argparse import collections import subprocess import time class retry_wrf(config): ''' change namelist timestep in rundir ''' def __init__(self): config.__init__(self) # load config self.wrf_run_dir = self.config['filesystem']['wrf_run_dir'] self._cli_parser() self.define_retry_values() self.load_nml() self.change_namelist() self.write_namelist() self.run_wrf() def _cli_parser(self): ''' parse command line arguments ''' parser = argparse.ArgumentParser( description='WRF retry script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') parser.add_argument('retrynumber', metavar='M', type=int, help='cylc retry number') args = parser.parse_args() self.retry_number = args.retrynumber self.dt = utils.convert_cylc_time(args.datestring) def load_nml(self): ''' load namelist in wrf rundir ''' self.wrf_nml = f90nml.read(os.path.join(self.wrf_run_dir, 'namelist.input')) def define_retry_values(self): ''' define retry values ''' # empty nested dictionary self.retry_values = collections.defaultdict(dict) # define retry steps self.retry_values[1]['time_step'] = 10 self.retry_values[1]['parent_time_step_ratio'] = [1, 5, 5] self.retry_values[2]['time_step'] = 8 self.retry_values[2]['parent_time_step_ratio'] = [1, 5, 5] self.retry_values[3]['time_step'] = 12 self.retry_values[3]['parent_time_step_ratio'] = [1, 6, 6] self.retry_values[4]['time_step'] = 6 self.retry_values[4]['parent_time_step_ratio'] = [1, 5, 5] def change_namelist(self): if self.retry_number in [1,2,3,4]: self.wrf_nml['domains']['parent_time_step_ratio' ] = self.retry_values[self.retry_number]['parent_time_step_ratio'] self.wrf_nml['domains']['time_step' ] = self.retry_values[self.retry_number]['time_step'] elif self.retry_number > 4: print('falling back to no data assimilation') for dom in [1, 2, 3]: # construct wrfout name for domain 1 dt_str = self.dt.strftime('%Y-%m-%d_%H:%M:%S') wrfvar_input = 'wrfvar_input_d0' + str(dom) + '_' + dt_str # remove wrfinput file with data assimilation os.remove(os.path.join(self.wrf_run_dir, 'wrfinput_d0' + str(dom))) # copy wrfinput file without data assimilation as fallback shutil.copyfile(os.path.join(self.wrf_run_dir, wrfvar_input), os.path.join(self.wrf_run_dir, 'wrfinput_d0' + str(dom))) def write_namelist(self): ''' write changed namelist to disk ''' # remove backup file if exists try: os.remove(os.path.join(self.wrf_run_dir, 'namelist.input.bak')) except OSError: pass # copy file to backup file shutil.copyfile(os.path.join(self.wrf_run_dir, 'namelist.input'), os.path.join(self.wrf_run_dir, 'namelist.input.bak')) # remove original namelist os.remove(os.path.join(self.wrf_run_dir, 'namelist.input')) # write new namelist self.wrf_nml.write(os.path.join(self.wrf_run_dir, 'namelist.input')) def run_wrf(self): ''' run wrf ''' j_id = None if len(self.config['options_slurm']['slurm_wrf.exe']): # run using slurm if j_id: mid = "--dependency=afterok:%d" %j_id wrf_command = ['sbatch', mid, self.config['options_slurm']['slurm_wrf.exe']] else: wrf_command = ['sbatch', self.config['options_slurm']['slurm_wrf.exe']] utils.check_file_exists(wrf_command[-1]) try: res = subprocess.check_output(wrf_command, cwd=self.wrf_run_dir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('WRF failed %s:' %wrf_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: # run locally subprocess.check_call(os.path.join(self.wrf_run_dir, 'wrf.exe'), cwd=self.wrf_run_dir, stdout=utils.devnull(), stderr=utils.devnull()) if __name__=="__main__": retry_wrf() <file_sep>/wrfpy/wrf.py #!/usr/bin/env python ''' description: WRF part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' from wrfpy.config import config from datetime import datetime import glob import os import f90nml from wrfpy import utils import subprocess import shutil class run_wrf(config): ''' run_wrf is a subclass of config # TODO: use better names ''' def __init__(self): config.__init__(self) self.wrf_rundir = self.config['filesystem']['wrf_run_dir'] def initialize(self, datestart, dateend): ''' initialize new WRF run ''' self.check_wrf_rundir() self.cleanup_previous_wrf_run() self.prepare_wrf_config(datestart, dateend) def check_wrf_rundir(self): ''' check if rundir exists if rundir doesn't exist, copy over content of self.config['filesystem']['wrf_dir']/run ''' utils._create_directory(self.wrf_rundir) # create list of files in self.config['filesystem']['wrf_dir']/run files = glob.glob(os.path.join(self.config['filesystem']['wrf_dir'], 'run', '*')) for fl in files: fname = os.path.basename(fl) if (os.path.splitext(fname)[1] == '.exe'): # don't copy over the executables continue shutil.copyfile(fl, os.path.join(self.wrf_rundir, fname)) def cleanup_previous_wrf_run(self): from utils import silentremove ''' cleanup initial/boundary conditions and namelist from previous WRF run ''' # remove initial conditions (wrfinput files) for filename in glob.glob(os.path.join( self.config['filesystem']['wrf_run_dir'], 'wrfinput_d*')): silentremove(filename) # remove lateral boundary conditions (wrfbdy_d01) silentremove(os.path.join(self.config['filesystem']['wrf_run_dir'], 'wrfbdy_d01')) silentremove(os.path.join(self.config['filesystem']['wrf_run_dir'], 'namelist.input')) def prepare_wrf_config(self, datestart, dateend): ''' Copy over default WRF namelist and modify time_control variables ''' from datetime import datetime # check if both datestart and dateend are a datetime instance if not all([ isinstance(dt, datetime) for dt in [datestart, dateend] ]): raise TypeError("datestart and dateend must be an instance of datetime") # read WRF namelist in WRF work_dir wrf_nml = f90nml.read(self.config['options_wrf']['namelist.input']) # get number of domains ndoms = wrf_nml['domains']['max_dom'] # check if ndoms is an integer and >0 if not (isinstance(ndoms, int) and ndoms>0): raise ValueError("'domains_max_dom' namelist variable should be an " \ "integer>0") # define dictionary with time control values dict = {'time_control:start_year':datestart.year, 'time_control:start_month':datestart.month, 'time_control:start_day':datestart.day, 'time_control:start_hour':datestart.hour, 'time_control:end_year':dateend.year, 'time_control:end_month':dateend.month, 'time_control:end_day':dateend.day, 'time_control:end_hour':dateend.hour, } # loop over dictionary and set start/end date parameters for el in dict.keys(): if not isinstance(dict[el], list): wrf_nml[el.split(':')[0]][el.split(':')[1]] = [dict[el]] * ndoms else: wrf_nml[el.split(':')[0]][el.split(':')[1]] = dict[el] * ndoms # set interval_seconds to total seconds between datestart and dateend wrf_nml['time_control']['interval_seconds'] = int(self.config[ 'options_general']['boundary_interval']) # calculate datetime.timedelta between datestart and dateend td = dateend - datestart # set run_days, run_hours, run_minutes, run_seconds td_days, td_hours, td_minutes, td_seconds = utils.days_hours_minutes_seconds(td) wrf_nml['time_control']['run_days'] = td_days wrf_nml['time_control']['run_hours'] = td_hours wrf_nml['time_control']['run_minutes'] = td_minutes wrf_nml['time_control']['run_seconds'] = td_seconds # check if WUR urban config is to be used if 'sf_urban_use_wur_config' in wrf_nml['physics']: # get start_date from config.json start_date = utils.return_validate( self.config['options_general']['date_start']) # if very first timestep, don't initialize urban parameters from file if (wrf_nml['physics']['sf_urban_use_wur_config'] and start_date == datestart): wrf_nml['physics']['sf_urban_init_from_file'] = False else: wrf_nml['physics']['sf_urban_init_from_file'] = True # write namelist.input wrf_nml.write(os.path.join( self.config['filesystem']['wrf_run_dir'], 'namelist.input')) def run_real(self, j_id=None): ''' run wrf real.exe ''' # check if slurm_real.exe is defined if len(self.config['options_slurm']['slurm_real.exe']): if j_id: mid = "--dependency=afterok:%d" %j_id real_command = ['sbatch', mid, self.config['options_slurm']['slurm_real.exe']] else: real_command = ['sbatch', self.config['options_slurm']['slurm_real.exe']] utils.check_file_exists(real_command[-1]) utils.silentremove(os.path.join(self.wrf_rundir, 'real.exe')) os.symlink(os.path.join(self.config['filesystem']['wrf_dir'],'main','real.exe'), os.path.join(self.wrf_rundir, 'real.exe')) try: res = subprocess.check_output(real_command, cwd=self.wrf_rundir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('Real failed %s:' %real_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: # run locally real_command = os.path.join(self.config['filesystem']['wrf_dir'], 'main', 'real.exe') utils.check_file_exists(real_command) try: subprocess.check_call(real_command, cwd=self.wrf_rundir, stdout=utils.devnull(), stderr=utils.devnull()) except subprocess.CalledProcessError: #logger.error('real.exe failed %s:' %real_command) raise # re-raise exception def run_wrf(self, j_id=None): ''' run wrf.exe ''' # check if slurm_wrf.exe is defined if len(self.config['options_slurm']['slurm_wrf.exe']): if j_id: mid = "--dependency=afterok:%d" %j_id wrf_command = ['sbatch', mid, self.config['options_slurm']['slurm_wrf.exe']] else: wrf_command = ['sbatch', self.config['options_slurm']['slurm_wrf.exe']] utils.check_file_exists(wrf_command[-1]) utils.silentremove(os.path.join(self.wrf_rundir, 'wrf.exe')) os.symlink(os.path.join(self.config['filesystem']['wrf_dir'],'main','wrf.exe'), os.path.join(self.wrf_rundir, 'wrf.exe')) try: res = subprocess.check_output(wrf_command, cwd=self.wrf_rundir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: logger.error('Wrf failed %s:' %wrf_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: # run locally wrf_command = os.path.join(self.config['filesystem']['wrf_dir'], 'main', 'wrf.exe') utils.check_file_exists(wrf_command) try: subprocess.check_call(wrf_command, cwd=self.wrf_rundir, stdout=utils.devnull(), stderr=utils.devnull()) except subprocess.CalledProcessError: logger.error('wrf.exe failed %s:' %wrf_command) raise # re-raise exception <file_sep>/wrfpy/cylc/run_wrf.py #!/usr/bin/env python import argparse import datetime import time from wrfpy.wrf import run_wrf from wrfpy import utils def main(): ''' Main function to initialize WPS timestep: - converts cylc timestring to datetime object - calls wrf.__init() and initialize() ''' WRF = run_wrf() WRF.run_wrf() if __name__=="__main__": main() <file_sep>/tests/end_to_end_test.py import os from os.path import dirname, abspath import unittest import tempfile from wrfpy.configuration import configuration class end2endtest(unittest.TestCase): def setUp(self): ''' setup test environment ''' # define test_data location self.test_data = os.path.join(dirname(abspath(__file__)), '..', 'test_data') def test_01(self): ''' Test single radar with 2 vertical levels ''' with tempfile.TemporaryDirectory() as temp_dir: results = {} results['suitename'] = 'test' results['basedir'] = temp_dir results['init'] = True configuration(results) # test if config.json exists outfile = os.path.join(results['basedir'], results['suitename'], 'config.json') self.assertEqual(os.path.exists(outfile), 1) if __name__ == "__main__": unittest.main() <file_sep>/wrfpy/configuration.py #!/usr/bin/env python ''' description: Configuration part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' from wrfpy.config import config from wrfpy import utils import os from distutils.dir_util import copy_tree import pkg_resources class configuration(config): def __init__(self, results): global logger logger = utils.start_logging(os.path.join(os.path.expanduser("~"), 'wrfpy.log')) if results['init']: self._create_directory_structure(results['suitename'], results['basedir']) elif results['create']: self._create_cylc_config(results['suitename'], results['basedir']) def _create_directory_structure(self, suitename, basedir=None): ''' Create directory structure for the Cylc configuration ''' # set basedir to users home directory if not supplied if not basedir: basedir = os.path.join(os.path.expanduser("~"), 'cylc-suites') # subdirectories to create subdirs = ['bin', 'control', 'doc', 'inc'] # create subdirectories [utils._create_directory( os.path.join(basedir, suitename, subdir)) for subdir in subdirs] # copy over helper scripts for cylc cylcDir = pkg_resources.resource_filename('wrfpy', 'cylc/') targetDir = os.path.join(basedir, suitename, 'bin') copy_tree(cylcDir, targetDir) # create empty json config file in suite directory # this does not overwrite an existing config file config.__init__(self, os.path.join( basedir, suitename, 'config.json')) def _create_cylc_config(self, suitename, basedir): ''' Create cylc suite.rc configuration file based on config.json ''' config.__init__(self, os.path.join( basedir, suitename, 'config.json')) self.incr_hour = self.config['options_general']['run_hours'] self.wps_interval_hours = self.config['options_wps']['run_hours'] suiterc = self._header() suiterc += self._scheduling() suiterc += self._runtime() suiterc += self._visualization() self._write(suiterc, os.path.join(basedir, suitename, 'suite.rc')) def _header(self): ''' define suite.rc header information ''' start_time = utils.datetime_to_string( utils.return_validate(self.config[ 'options_general']['date_start']), format='%Y%m%dT%H') end_time = utils.datetime_to_string( utils.return_validate(self.config['options_general']['date_end']), format='%Y%m%dT%H') # define template template = """#!Jinja2 {{% set START = "{start_time}" %}} {{% set STOP = "{end_time}" %}} """ # context variables in template context = { "start_time": start_time, "end_time": end_time } return template.format(**context) def _scheduling(self): ''' define suite.rc scheduling information ''' # get start_hour and increment time from config.json start_hour = str( utils.return_validate (self.config['options_general']['date_start']).hour).zfill(2) # check if we need to add upp try: if self.config['options_upp']['upp']: uppBlock = "=> upp" else: uppBlock = "" except KeyError: uppBlock = "" # define template template = """[scheduling] initial cycle point = {{{{ START }}}} final cycle point = {{{{ STOP }}}} [[dependencies]] # Initial cycle point [[[R1]]] graph = \"\"\" wrf_init => wps => wrf_real => wrfda => wrf_run {upp} obsproc_init => obsproc_run => wrfda \"\"\" # Repeat every {incr_hour} hours, starting {incr_hour} hours # after initial cylce point [[[+PT{incr_hour}H/PT{incr_hour}H]]] graph = \"\"\" wrf_run[-PT{incr_hour}H] => wrf_init => wrf_real => wrfda => wrf_run {upp} wrfda[-PT{incr_hour}H] => obsproc_init => obsproc_run => wrfda \"\"\" # Repeat every {wps_incr_hour} hours, starting {wps_incr_hour} hours # after initial cylce point [[[+PT{wps_incr_hour}H/PT{wps_incr_hour}H]]] graph = \"\"\" wps[-PT{wps_incr_hour}H] => wps => wrf_init \"\"\" """ # context variables in template context = { "start_hour": start_hour, "incr_hour": self.incr_hour, "wps_incr_hour": self.wps_interval_hours, "upp": uppBlock } return template.format(**context) def _runtime(self): ''' define suite.rc runtime information ''' return (self._runtime_base() + self._runtime_init_wrf() + self._runtime_init_obsproc() + self._runtime_real() + self._runtime_wrf() + self._runtime_obsproc() + self._runtime_wrfda() + self._runtime_upp() + self._runtime_wps()) def _runtime_base(self): ''' define suite.rc runtime information: base ''' # define template template = """[runtime] [[root]] # suite defaults [[[job submission]]] method = background """ # context variables in template context = {} return template.format(**context) def _runtime_init_wrf(self): ''' define suite.rc runtime information: init ''' init_command = "wrf_init.py $CYLC_TASK_CYCLE_POINT {incr_hour}" init_context = { "incr_hour": self.incr_hour } init = init_command.format(**init_context) # define template template = """ [[wrf_init]] script = \"\"\" {wrf_init} \"\"\" [[[job submission]]] method = {method} [[[directives]]] {directives}""" # context variables in template context = { "wrf_init": init, "method": "background", "directives": "" } return template.format(**context) def _runtime_init_obsproc(self): ''' define suite.rc runtime information: init ''' init = "wrfda_obsproc_init.py $CYLC_TASK_CYCLE_POINT" # define template template = """ [[obsproc_init]] script = \"\"\" {obsproc_init} \"\"\" [[[job submission]]] method = {method} [[[directives]]] {directives}""" # context variables in template context = { "obsproc_init": init, "method": "background", "directives": "" } return template.format(**context) def _runtime_real(self): ''' define suite.rc runtime information: real.exe ''' wrf_real = "run_real.py" # define template template = """ [[wrf_real]] script = \"\"\" {wrf_real} \"\"\" [[[job submission]]] method = {method} [[[directives]]] {directives}""" # context variables in template context = { "wrf_real": wrf_real, "method": "background", "directives": "" } return template.format(**context) def _runtime_wrf(self): ''' define suite.rc runtime information: wrf.exe ''' wrf_run = "run_wrf.py" # define template template = """ [[wrf_run]] script = \"\"\" {wrf_run} \"\"\" [[[job submission]]] method = {method} [[[directives]]] {directives}""" # context variables in template context = { "wrf_run": wrf_run, "method": "background", "directives": "" } return template.format(**context) def _runtime_obsproc(self): ''' define suite.rc runtime information: obsproc.exe ''' obsproc_run = "wrfda_obsproc_run.py $CYLC_TASK_CYCLE_POINT" # define template template = """ [[obsproc_run]] script = \"\"\" {obsproc_run} \"\"\" [[[job submission]]] method = {method} [[[directives]]] {directives}""" # context variables in template context = { "obsproc_run": obsproc_run, "method": "background", "directives": "" } return template.format(**context) def _runtime_wrfda(self): ''' define suite.rc runtime information: wrfda ''' wrfda_run = "wrfda_run.py $CYLC_TASK_CYCLE_POINT" # define template template = """ [[wrfda]] script = \"\"\" {wrfda_run} \"\"\" [[[job submission]]] method = {method} [[[directives]]] {directives}""" # context variables in template context = { "wrfda_run": wrfda_run, "method": "background", "directives": "" } return template.format(**context) def _runtime_upp(self): ''' define suite.rc runtime information: wrfda ''' # define template template = """ [[upp]] script = \"\"\" {command} \"\"\" [[[job submission]]] method = {method} [[[directives]]] {directives} """ command = "upp.py $CYLC_TASK_CYCLE_POINT" context = { "command": command, "method": "background", "directives": "" } return template.format(**context) def _runtime_wps(self): ''' define suite.rc runtime information: wrfda ''' # define template template = """ [[wps]] pre-script = \"\"\" {pre_command} \"\"\" script = \"\"\" {command} \"\"\" post-script = \"\"\" {post_command} \"\"\" [[[environment]]] WORKDIR = {wps_workdir} CYLC_TASK_WORK_DIR = $WORKDIR [[[job submission]]] method = {method} [[[directives]]] {directives} """ pre_command = "wps_init.py $CYLC_TASK_CYCLE_POINT {wps_run_hours}" pre_command_context = { "wps_run_hours": self.wps_interval_hours, } command = "wps_run.py" command_context = { "wps_dir": self.config['filesystem']['wps_dir'] } post_command = "wps_post.py" context = { "wps_workdir": os.path.join(self.config['filesystem']['work_dir'], 'wps'), "pre_command": pre_command.format(**pre_command_context), "command": command.format(**command_context), "post_command": post_command, "method": "background", "directives": "" } return template.format(**context) def _visualization(self): ''' define suite.rc visualization information ''' # define template template = """ [visualization] initial cycle point = {{ START }} final cycle point = {{ STOP }} default node attributes = "style=filled", "fillcolor=grey" """ return template def _write(self, suiterc, filename): ''' write cylc suite.rc config to file ''' # create the itag file and write content to it based on the template try: with open(filename, 'w') as itag: itag.write(suiterc) except IOError: raise # re-raise exception <file_sep>/wrfpy/scale.py #!/usr/bin/env python from scipy import interpolate from netCDF4 import Dataset import os import numpy as np import shutil import f90nml from wrfpy.config import config from wrfpy import utils from datetime import datetime class wrfda_interpolate(config): def __init__(self, itype='rural'): if itype not in ['rural', 'urban', 'both']: raise Exception('Unknown itype, should be one of rural, urban, both') config.__init__(self) # read WRF namelist in WRF work_dir wrf_nml = f90nml.read(self.config['options_wrf']['namelist.input']) self.wrfda_workdir = os.path.join(self.config['filesystem']['work_dir'], 'wrfda') self.wrf_rundir = self.config['filesystem']['work_dir'] # get number of domains ndoms = wrf_nml['domains']['max_dom'] # check if ndoms is an integer and >0 if not (isinstance(ndoms, int) and ndoms>0): raise ValueError("'domains_max_dom' namelist variable should be an " \ "integer>0") doms = range(2, ndoms+1) for dom in doms: pdomain = 1 self.read_init(dom, pdomain) if ((itype=='rural') or (itype=='both')): self.fix_2d_field('ALBBCK', 'CANWAT', 'MU', 'PSFC', 'SST', 'TMN', 'TSK', 'T2') self.fix_3d_field('P', 'PH', 'SH2O', 'SMOIS', 'T', 'W', 'QVAPOR') self.fix_3d_field_uv(self.XLAT_U_p, self.XLONG_U_p, self.XLAT_U_c, self.XLONG_U_c, 'U') self.fix_3d_field_uv(self.XLAT_V_p, self.XLONG_V_p, self.XLAT_V_c, self.XLONG_V_c, 'V') if ndoms > 1: self.cleanup(dom) def read_init(self, cdom, pdom): c_wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(cdom)) p_wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(pdom)) self.fg_p = Dataset(os.path.join(p_wrfda_workdir, 'fg'), 'r') self.wrfinput_p = Dataset(os.path.join(p_wrfda_workdir, 'wrfvar_output'), 'r') shutil.copyfile(os.path.join(c_wrfda_workdir, 'fg'), os.path.join(c_wrfda_workdir, 'wrfvar_output')) self.wrfinput_c = Dataset(os.path.join(c_wrfda_workdir, 'wrfvar_output'), 'r+') # get time information from wrfinput file dtobj, datestr = self.get_time(os.path.join(c_wrfda_workdir, 'wrfvar_output')) # get file connection to wrfvar_input file for child domain in wrf run directory start_date = utils.return_validate( self.config['options_general']['date_start']) if (dtobj == start_date): # very first timestep self.wrfinput_c_nolsm = Dataset(os.path.join(self.wrf_rundir, ('wrfinput_d0' + str(cdom))), 'r') else: self.wrfinput_c_nolsm = Dataset(os.path.join(self.wrf_rundir, ('wrfvar_input_d0' + str(cdom) + '_' + datestr)), 'r') # lon/lat information parent domain self.XLONG_p = self.wrfinput_p.variables['XLONG'][0,:] self.XLAT_p = self.wrfinput_p.variables['XLAT'][0,:] # lon/lat information child domain self.XLONG_c = self.wrfinput_c.variables['XLONG'][0,:] self.XLAT_c = self.wrfinput_c.variables['XLAT'][0,:] # lon/lat information parent domain self.XLONG_U_p = self.wrfinput_p.variables['XLONG_U'][0,:] self.XLAT_U_p = self.wrfinput_p.variables['XLAT_U'][0,:] # lon/lat information child domain self.XLONG_U_c = self.wrfinput_c.variables['XLONG_U'][0,:] self.XLAT_U_c = self.wrfinput_c.variables['XLAT_U'][0,:] # V # lon/lat information parent domain self.XLONG_V_p = self.wrfinput_p.variables['XLONG_V'][0,:] self.XLAT_V_p = self.wrfinput_p.variables['XLAT_V'][0,:] # lon/lat information child domain self.XLONG_V_c = self.wrfinput_c.variables['XLONG_V'][0,:] self.XLAT_V_c = self.wrfinput_c.variables['XLAT_V'][0,:] def get_time(self, wrfinput): ''' get time from wrfinput file ''' wrfinput = Dataset(wrfinput, 'r') # open netcdf file # get datetime string from wrfinput file datestr = ''.join(wrfinput.variables['Times'][0]) # convert to datetime object dtobj = datetime.strptime(datestr, '%Y-%m-%d_%H:%M:%S') wrfinput.close() # close netcdf file return dtobj, datestr def fix_2d_field(self, *variables): #XLONG_p_i = self.XLONG_p[self.wrfinput_p.variables['LU_INDEX'][0,:]==1].reshape(-1) #XLAT_p_i = self.XLAT_p[self.wrfinput_p.variables['LU_INDEX'][0,:]==1].reshape(-1) XLONG_p_i = self.XLONG_p.reshape(-1) XLAT_p_i = self.XLAT_p.reshape(-1) for variable in variables: var = self.wrfinput_p.variables[variable][0,:] - self.fg_p.variables[variable][0,:] #var_i = var[self.wrfinput_p.variables['LU_INDEX'][0,:]==1].reshape(-1) var_i = var.reshape(-1) # interpolate regular wrfda variables with nearest neighbor interpolation intp_var = interpolate.griddata((XLONG_p_i,XLAT_p_i), var_i, (self.XLONG_c.reshape(-1),self.XLAT_c.reshape(-1)), method='nearest').reshape(np.shape(self.XLONG_c)) self.wrfinput_c.variables[variable][:] += intp_var def fix_3d_field(self, *variables): XLONG_p_i = self.XLONG_p.reshape(-1) XLAT_p_i = self.XLAT_p.reshape(-1) for variable in variables: var = self.wrfinput_p.variables[variable][0,:] - self.fg_p.variables[variable][0,:] # interpolate regular wrfda variables with nearest neighbor interpolation intp_var = [interpolate.griddata((XLONG_p_i,XLAT_p_i), var[lev,:].reshape(-1), (self.XLONG_c.reshape(-1),self.XLAT_c.reshape(-1)), method='nearest').reshape(np.shape(self.XLONG_c)) for lev in range(0,len(var))] self.wrfinput_c.variables[variable][:] += intp_var def fix_3d_field_uv(self,XLAT_p, XLONG_p, XLAT_c, XLONG_c, *variables): for variable in variables: var = self.wrfinput_p.variables[variable][0,:] - self.fg_p.variables[variable][0,:] intp_var = [interpolate.griddata((XLONG_p.reshape(-1),XLAT_p.reshape(-1)), var[lev,:].reshape(-1), (XLONG_c.reshape(-1),XLAT_c.reshape(-1)), method='nearest').reshape(np.shape(XLONG_c)) for lev in range(0,len(var))] self.wrfinput_c.variables[variable][:] += intp_var def cleanup(self, cdom): ''' close netcdf files and write changes ''' self.wrfinput_p.close() self.wrfinput_c.close() self.wrfinput_c_nolsm.close() self.fg_p.close() # copy results back to original file c_wrfda_workdir = os.path.join(self.wrfda_workdir, "d0" + str(cdom)) shutil.copyfile(os.path.join(c_wrfda_workdir, 'wrfvar_output'), os.path.join(c_wrfda_workdir, 'fg')) if __name__=="__main__": wrfda_interpolate() <file_sep>/wrfpy/cylc/prepare_synop.py #!/usr/bin/env python import argparse import datetime import time from wrfpy import utils from pynetcdf2littler.wrapper_littler import wrapper_littler from dateutil.relativedelta import relativedelta import os def main(args): ''' Example script to integrate pynetcdf2littler into CYLC ''' dt = utils.convert_cylc_time(args.datestring) # startdate dt1 = datetime.datetime(dt.year, dt.month, 1) dt1s = dt1.strftime('%Y%m%d') # convert to string dt2 = dt1 + relativedelta(months=1) dt2s = dt2.strftime('%Y%m%d') # convert to string outputdir = os.path.join(args.outputdir, dt1s) wrapper_littler(args.filelist, args.namelist, outputdir, args.outputfile, dt1s, dt2s) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize obsproc.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') parser.add_argument('-f', '--filelist', help='filelist containing netcdf files', default='wrapper.filelist', required=False) parser.add_argument('-n', '--namelist', help='netcdf2littler namelist', required=True) parser.add_argument('-d', '--outputdir', help='outputdir', required=False, default=os.getcwd()) parser.add_argument('-o', '--outputfile', help='name of outputfile', required=False, default='pynetcdf2littler.output') # parse arguments args = parser.parse_args() # call main main(args) <file_sep>/wrfpy/cylc/wrfda_run.py #!/usr/bin/env python import argparse import datetime import time from wrfpy import utils from wrfpy.wrfda import wrfda from wrfpy.bumpskin import * from wrfpy.scale import wrfda_interpolate from wrfpy.config import config import shutil class dataAssimilation(config): ''' Data assimilation helper class ''' def __init__(self, datestring): config.__init__(self) datestart = utils.convert_cylc_time(datestring) # initialize WRFDA object WRFDA = wrfda(datestart) WRFDA.prepare_updatebc(datestart) # update lower boundary conditions for domain in range(1, WRFDA.max_dom+1): WRFDA.updatebc_run(domain) # run da_updatebc.exe # copy radar data into WRFDA workdir if available try: radarFile = self.config['filesystem']['radar_filepath'] radarTarget = os.path.join(self.config['filesystem']['work_dir'], 'wrfda', 'd01', 'ob.radar') shutil.copyfile(radarFile, radarTarget) except (KeyError, IOError): pass # prepare for running da_wrfvar.exe WRFDA.prepare_wrfda() # run da_wrfvar.exe WRFDA.wrfvar_run(1) # interpolate rural variables from wrfda wrfda_interpolate(itype='rural') try: urbanData = self.config['options_urbantemps']['urban_stations'] except KeyError: urbanData = False if urbanData: bskin = bumpskin(urbanData, dstationtypes=['davis', 'vp2', 'vantage']) # update URBPARM.TBL with anthropogenic heat factors try: urbparmFile = self.config['options_wrf']['urbparm.tbl'] except KeyError: urbparmFile = False if urbparmFile: urbparm(datestart, urbparmFile) # update lateral boundary conditions WRFDA.prepare_updatebc_type('lateral', datestart, 1) WRFDA.updatebc_run(1) # copy files over to WRF run_dir WRFDA.wrfda_post(datestart) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize obsproc.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') # parse arguments args = parser.parse_args() # call dataAssimilation class dataAssimilation(args.datestring) <file_sep>/wrfpy/cylc/combine_synop.py #!/usr/bin/env python import argparse import datetime import time from wrfpy import utils from pynetcdf2littler.wrapper_littler import wrapper_littler from dateutil.relativedelta import relativedelta import os import glob import fileinput def main(args): ''' Example script to combine different output files from the prepare_synop.py script ''' dt = utils.convert_cylc_time(args.datestring) # startdate dt1 = datetime.datetime(dt.year, dt.month, 1) dt1s = dt1.strftime('%Y%m%d') # convert to string outputdir = os.path.join(args.outputdir, dt1s) filenames = glob.glob(os.path.join(outputdir, '*')) outputfile = args.outputfile if filenames: with open(os.path.join (outputdir, outputfile), 'w') as fout: for line in fileinput.input(filenames): fout.write(line) else: with open(outputfile, 'a'): os.utime(outputfile, None) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize obsproc.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') parser.add_argument('-d', '--outputdir', help='outputdir', required=False, default=os.getcwd()) parser.add_argument('-o', '--outputfile', help='name of outputfile', required=True) # parse arguments args = parser.parse_args() # call main main(args) <file_sep>/wrfpy/cylc/archive.py #!/usr/bin/env python from netCDF4 import Dataset as ncdf from netCDF4 import date2num import pandas import time import os from dateutil import relativedelta import argparse import f90nml import shutil from wrfpy.config import config from wrfpy import utils from astropy.convolution import convolve import numpy as np class postprocess(config): def __init__(self, datestart, dateend): config.__init__(self) self.startdate = datestart self.enddate = dateend # read WRF namelist in WRF work_dir wrf_nml = f90nml.read(self.config['options_wrf']['namelist.input']) # get number of domains self.ndoms = wrf_nml['domains']['max_dom'] self.rundir = self.config['filesystem']['wrf_run_dir'] # archive in subdir per year self.archivedir = os.path.join( self.config['filesystem']['archive_dir'], str(self.startdate.year)) utils._create_directory(self.archivedir) # define static variables self.define_vars_static() # define variables that need to be stored hourly self.define_vars_hourly() # define variables that need to be stored every minute for the inner # domain, hourly for the other domains self.define_vars_minute() self.define_vars_deac() # define variables to be deaccumulated self.archive() # archive "normal" variables self.archive_wrfvar_input() # archive wrfvar_input files # get start_date from config.json start_date = utils.return_validate( self.config['options_general']['date_start']) if (start_date == datestart): # very first timestep self.archive_static() # archive static variables self.cleanup() def define_vars_hourly(self): ''' create dict of outputstream:variable for output that has to be saved every hour ''' self.hour_var = [ 'VEGFRA', 'MU', 'MUB', 'Q2', 'T2', 'TH2', 'PSFC', 'U10', 'V10', 'GRDFLX', 'ACSNOM', 'SNOW', 'SNOWH', 'CANWAT', 'TC2M_URB', 'TP2M_URB', 'LAI', 'VAR', 'F', 'E', 'TSK', 'SWDOWN', 'GLW', 'SWNORM', 'ALBEDO', 'ALBBCK', 'EMISS', 'NOAHRES', 'UST', 'PBLH', 'HFX', 'LH', 'SNOWC', 'OLR', 'SFCEXC', 'Z0', 'SST', 'U', 'V', 'W', 'PH', 'PHB', 'T', 'P', 'PB', 'P_HYD', 'QVAPOR', 'QCLOUD', 'QRAIN', 'QICE', 'QSNOW', 'QGRAUP', 'CLDFRA', 'TSLB', 'SMOIS', 'SMCREL'] def define_vars_static(self): ''' Static variables. Run only once on the very first timestep ''' self.static_var = [ 'ZS', 'DZS', 'XLAND', 'TMN'] def define_vars_minute(self): ''' create dict of outputstream:variable for output that has to be saved every minute for the inner domain ''' self.minute_var = [ 'SFROFF', 'UDROFF', 'QFX', 'SR', 'RAINNC', 'SNOWNC', 'GRAUPELNC', 'HAILNC'] def define_vars_deac(self): self.deac_var = [ 'SNOWNC', 'RAINNC', 'SFROFF', 'UDROFF', 'SNOWC', 'GRAUPELNC', 'HAILNC'] def write_netcdf(self, var, inpdata, lat, lon, dt, dim, outfile): ''' Write netcdf output file ''' # open output file ncfile = ncdf(outfile, 'w') # create dimensions and variables if dim == 3: ncfile.createDimension('time', len(dt)) ncfile.createDimension('south_north', np.shape(inpdata)[1]) ncfile.createDimension('west_east', np.shape(inpdata)[2]) data = ncfile.createVariable(var, 'f4', ('time', 'south_north', 'west_east',), zlib=True, fill_value=-999) elif dim == 4: ncfile.createDimension('time', len(dt)) ncfile.createDimension('bottom_top', np.shape(inpdata)[1]) ncfile.createDimension('south_north', np.shape(inpdata)[2]) ncfile.createDimension('west_east', np.shape(inpdata)[3]) data = ncfile.createVariable(var, 'f4', ('time', 'bottom_top', 'south_north', 'west_east',), zlib=True, fill_value=-999) data1 = ncfile.createVariable('latitude', 'f4', ('south_north', 'west_east',), zlib=True) data2 = ncfile.createVariable('longitude', 'f4', ('south_north', 'west_east',), zlib=True) timevar = ncfile.createVariable('time', 'f4', ('time',), zlib=True) # time axis UTC dt = [date2num(d.to_datetime(), units='minutes since 2010-01-01 00:00:00', calendar='gregorian') for d in dt] # define attributes timevar.units = 'minutes since 2010-01-01 00:00:00' timevar.calendar = 'gregorian' timevar.standard_name = 'time' timevar.long_name = 'time in UTC' data1.units = 'degree_east' data1.standard_name = 'longitude' data1.FieldType = 104 data1.description = "longitude, west is negative" data1.MemoryOrder = "XY" data1.coordinates = "lon lat" data2.units = 'degree_north' data2.standard_name = 'latitude' data2.description = 'latitude, south is negative' data2.FieldType = 104 data2.MemoryOrder = "XY" data2.coordinates = "lon lat" try: data[:] = inpdata[:] except IndexError: raise # lat/lon should be a static field try: data1[:] = lat[0, :] data2[:] = lon[0, :] except IndexError: raise timevar[:] = dt # Add global attributes ncfile.history = 'Created ' + time.ctime(time.time()) ncfile.close() def getvar(self, var, domain, datestr): ''' Read variable form netCDF file and return array ''' # define and load input file input_fn = var + '_d0' + str(domain) + '_' + datestr input_file = os.path.join(self.rundir, input_fn) ncfile = ncdf(input_file, 'r') # read variable and close netCDF file tmp = ncfile.variables[var][:] ncfile.close() return tmp @staticmethod def spatial_filter(data): ''' Apply spatial convolution filter to input data ''' kernel = np.array([[1, 1, 1], [1, 0, 1], [1, 1, 1]]) if data.ndim == 2: dataF = convolve(data[:], kernel, nan_treatment='interpolate', preserve_nan=True) return dataF elif data.ndim == 3: dataF = np.zeros(np.shape(data)) for i in range(0, len(data)): dataF[i, :] = convolve(data[i, :], kernel, nan_treatment='interpolate', preserve_nan=True) return dataF else: return data def archive(self): ''' archive standard output files ''' # loop over all domains for domain in range(1, self.ndoms + 1): # get lat/lon information from wrfout datestr_fn = self.startdate.strftime('%Y-%m-%d_%H:%M:%S') wrfout_n = 'wrfout_d0' + str(domain) + '_' + datestr_fn wrfout = ncdf(os.path.join(self.rundir, wrfout_n), 'r') lat = wrfout.variables['XLAT'][:] lon = wrfout.variables['XLONG'][:] lat_u = wrfout.variables['XLAT_U'][:] lon_u = wrfout.variables['XLONG_U'][:] lat_v = wrfout.variables['XLAT_V'][:] lon_v = wrfout.variables['XLONG_V'][:] frc_urb = wrfout.variables['FRC_URB2D'][:] wrfout.close() # iterate over all variables that need to be archived for var in (self.hour_var + self.minute_var): print(var) output_fn = (var + '_d0' + str(domain) + '_' + datestr_fn + '.nc') output_file = os.path.join(self.archivedir, output_fn) for cdate in pandas.date_range(self.startdate, self.enddate, freq='2H')[:-1]: datestr_in = cdate.strftime('%Y-%m-%d_%H:%M:%S') if not var == 'TC2M_URB': tmp = self.getvar(var, domain, datestr_in) else: # compute TC2M_URB from T2, TP2M_URB and FRC_URB2D # load required variables tp2m_urb = self.getvar('TP2M_URB', domain, datestr_in) # set non-urban points to NaN instead of 0 tp2m_urb[tp2m_urb == 0] = np.nan t2 = self.getvar('T2', domain, datestr_in) # compute tc2m_urb tmp = (t2 - (1 - frc_urb) * tp2m_urb) / frc_urb # compute spatial filtered variant tmpF = (self.spatial_filter(t2) - (1 - frc_urb) * self.spatial_filter(tp2m_urb)) / frc_urb # overwrite outer edges of domain with original data tmpF[:, 0, :] = tmp[:, 0, :] tmpF[:, -1, :] = tmp[:, -1, :] tmpF[:, :, 0] = tmp[:, :, 0] tmpF[:, :, -1] = tmp[:, :, -1] # difference between filtered/unfiltered diff = np.abs(tmp - tmpF) # replace points in tmp where diff>1 with tmpF tmp[diff > 1] = tmpF[diff > 1] # set NaN to 0 in tc2m_urb tmp[np.isnan(tmp)] = 0 # combine steps from input files if var in self.deac_var: # need to deaccumulate this variable try: output = np.vstack((output, np.diff(tmp, axis=0))) except NameError: output = np.vstack((tmp[0, :][np.newaxis, :], np.diff(tmp, axis=0))) else: # variable only needs appending try: output = np.vstack((output, tmp[1:])) except NameError: output = tmp # find number of dimensions (3d/4d variable) dim = np.ndim(tmp) del tmp # cleanup # define time variable in output file if (var in self.minute_var) and (domain == self.ndoms): # minute variable in inner domain => minute output dt = pandas.date_range(self.startdate, self.enddate, freq='1min')[:] else: # else hourly output dt = pandas.date_range(self.startdate, self.enddate, freq='1H')[:] # write netcdf outfile if var == 'U': self.write_netcdf(var, output, lat_u, lon_u, dt, dim, output_file) elif var == 'V': self.write_netcdf(var, output, lat_v, lon_v, dt, dim, output_file) else: self.write_netcdf(var, output, lat, lon, dt, dim, output_file) del output def archive_wrfvar_input(self): ''' archive wrfvar_input files ''' # loop over all domains wrfvar_archivedir = os.path.join(self.archivedir, 'wrfvar') utils._create_directory(wrfvar_archivedir) start_date = utils.return_validate( self.config['options_general']['date_start']) for domain in range(1, self.ndoms + 1): # iterate over all variables that need to be archived for cdate in pandas.date_range(self.startdate, self.enddate, freq='2H')[:-1]: if (cdate != start_date): datestr_in = cdate.strftime('%Y-%m-%d_%H:%M:%S') # define and load input file input_fn = ('wrfvar_input' + '_d0' + str(domain) + '_' + datestr_in) input_file = os.path.join(self.rundir, input_fn) output_file = os.path.join(wrfvar_archivedir, input_fn) # copy wrfvar_input to archive dir shutil.copyfile(input_file, output_file) def archive_static(self): ''' archive non-changing files ''' # loop over all domains static_archivedir = os.path.join(self.archivedir, 'static') utils._create_directory(static_archivedir) for domain in range(1, self.ndoms + 1): # iterate over all variables that need to be archived for var in self.static_var: datestr_in = self.startdate.strftime('%Y-%m-%d_%H:%M:%S') # define and load input file input_fn = var + '_d0' + str(domain) + '_' + datestr_in input_file = os.path.join(self.rundir, input_fn) output_file = os.path.join(static_archivedir, input_fn) # copy wrfvar_input to archive dir shutil.copyfile(input_file, output_file) def cleanup(self): ''' cleanup files in WRF run directory ''' # loop over all domains for domain in range(1, self.ndoms + 1): # iterate over all variables that need to be archived for var in (self.hour_var + self.minute_var + ['wrfout', 'wrfvar_input']): for cdate in pandas.date_range(self.startdate, self.enddate, freq='2H')[:-1]: datestr_in = cdate.strftime('%Y-%m-%d_%H:%M:%S') # define and load input file input_fn = var + '_d0' + str(domain) + '_' + datestr_in input_file = os.path.join(self.rundir, input_fn) utils.silentremove(input_file) def main(datestring): ''' Main function to call archive class ''' dt = utils.convert_cylc_time(datestring) postprocess(dt-relativedelta.relativedelta(days=1), dt) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Initialize obsproc.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') # parse arguments args = parser.parse_args() # call main main(args.datestring) <file_sep>/wrfpy/split_namelist.py #!/usr/bin/env python ''' description: split WRF namelist into first domain / rest license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' import f90nml import copy import mpl_toolkits.basemap.pyproj as pyproj from wrfpy.config import config import os from wrfpy import utils class split_nml_shared(config): ''' shared functionality for split_nml_wrf and split_nml_wps ''' def __init__(self, namelist): config.__init__(self) self.namelist = namelist self.read_namelist() self.create_namelist_copies() self.modify_coarse_namelist() self.modify_fine_namelist() def read_namelist(self): ''' read user supplied namelist ''' self.nml = f90nml.read(self.namelist) # get list of namelist keys self.keys = self.nml.keys() def create_namelist_copies(self): ''' create two (shallow) copies of the variable containing the namelist which will be used to create the output namelists ''' self.nml_coarse = copy.copy(self.nml) self.nml_fine = copy.copy(self.nml) def modify_coarse_namelist(self): ''' modify coarse namelist (resulting namelist contains outer domain only) ''' for section in self.nml.keys(): for key in self.nml[section].keys(): if isinstance(self.nml[section][key], list): if key not in ['eta_levels']: # don't modify these keys # use only first item from list self.nml_coarse[section][key] = self.nml[section][key][0] elif key == 'max_dom': self.nml_coarse[section][key] = 1 # only outer domain # else don't modify the key def modify_fine_namelist(self): ''' modify fine namelist (resulting namelist contains all but outer domain) ''' special_cases1 = ['parent_grid_ratio', 'i_parent_start', 'j_parent_start', 'parent_time_step_ratio'] special_cases2 = ['grid_id', 'parent_id'] for section in self.nml.keys(): for key in self.nml[section].keys(): if isinstance(self.nml[section][key], list): if key in special_cases1: if len(self.nml[section][key]) > 2: self.nml_fine[section][key] = [1] + self.nml[ section][key][2:] else: self.nml_fine[section][key] = 1 elif key in special_cases2: self.nml_fine[section][key] = self.nml[section][key][:-1] elif key not in ['eta_levels']: # don't modify these keys # start from second item in list self.nml_fine[section][key] = self.nml[section][key][1:] elif key=='time_step': self.nml_fine[section][key] = int( float(self.nml[section][key]) / self.nml['domains'][ 'parent_grid_ratio'][1]) elif key=='max_dom': self.nml_fine[section][key] = self.nml[section][key] - 1 class split_nml_wrf(split_nml_shared, config): def __init__(self): config.__init__(self) # load config wrf_namelist = self.config['options_wrf']['namelist.input'] split_nml_shared.__init__(self, wrf_namelist) self._save_namelists() def _save_namelists(self): ''' write coarse and fine WRF namelist.input to the respective run directories as namelist.forecast ''' # define namelist directories coarse_namelist_dir = os.path.join(self.config['filesystem']['work_dir'], 'wrf_coarse') fine_namelist_dir = os.path.join(self.config['filesystem']['work_dir'], 'wrf_fine') # create directories [utils._create_directory(directory) for directory in [coarse_namelist_dir, fine_namelist_dir]] # remove old files if needed [utils.silentremove(filename) for filename in [ os.path.join(dn, 'namelist.forecast') for dn in [coarse_namelist_dir, fine_namelist_dir]]] # write namelists self.nml_coarse.write(os.path.join(coarse_namelist_dir, 'namelist.forecast')) self.nml_fine.write(os.path.join(fine_namelist_dir, 'namelist.forecast')) class split_nml_wps(split_nml_shared, config): def __init__(self): config.__init__(self) # load config wps_namelist = self.config['options_wps']['namelist.wps'] split_nml_shared.__init__(self, wps_namelist) self._modify_fine_namelist_wps() self._save_namelists() def _modify_fine_namelist_wps(self): ''' wps specific fine namelist changes ''' # calculate new dx, dy, ref_lon, ref_lat for second domain self._calculate_center_second_domain() # modify dx, dy, ref_lon, ref_lat for second domain self.nml_fine['geogrid']['dx'] = self.dx self.nml_fine['geogrid']['dy'] = self.dy self.nml_fine['geogrid']['ref_lon'] = self.ref_lon self.nml_fine['geogrid']['ref_lat'] = self.ref_lat def _calculate_center_second_domain(self): ''' Calculate the center of the second domain for running in UPP mode ''' grid_ratio = self.nml['geogrid']['parent_grid_ratio'][1] i_start = self.nml['geogrid']['i_parent_start'] j_start = self.nml['geogrid']['j_parent_start'] e_we = self.nml['geogrid']['e_we'] e_sn = self.nml['geogrid']['e_sn'] ref_lat = self.nml['geogrid']['ref_lat'] ref_lon = self.nml['geogrid']['ref_lon'] truelat1 = self.nml['geogrid']['truelat1'] truelat2 = self.nml['geogrid']['truelat2'] # new dx and dy self.dx = float(self.nml['geogrid']['dx']) / grid_ratio self.dy = float(self.nml['geogrid']['dy']) / grid_ratio # define projection string projstring = ("+init=EPSG:4326 +proj=lcc +lat_1=%s +lat_2=%s +lat_0=%s " "+lon_0=%s +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 " "+units=m +no_defs" %(str(truelat1), str(truelat2), str(ref_lat), str(ref_lon))) projection = pyproj.Proj( projstring ) # calculate east/west/south/north west = (-self.nml['geogrid']['dx'] * (e_we[0] - 1 ) * 0.5) + ( (i_start[1] - 1) * self.nml['geogrid']['dx']) south = (-self.nml['geogrid']['dy'] * (e_sn[0] - 1 ) * 0.5) + ( (j_start[1] - 1) * self.nml['geogrid']['dy']) east = west + ((e_we[1] -1 ) * self.dx) north = south + ((e_sn[1] -1 ) * self.dy) # new ref_lat and ref_lon self.ref_lon, self.ref_lat = projection((west + east) * 0.5, (north + south) * 0.5, inverse=True) def _save_namelists(self): ''' write coarse and fine WRF namelist.input to the respective run directories as namelist.forecast ''' # define namelist directories coarse_namelist_dir = os.path.join(self.config['filesystem']['work_dir'], 'wps_coarse') fine_namelist_dir = os.path.join(self.config['filesystem']['work_dir'], 'wps_fine') # create directories [utils._create_directory(directory) for directory in [coarse_namelist_dir, fine_namelist_dir]] # remove old files if needed [utils.silentremove(filename) for filename in [ os.path.join(dn, 'namelist.wps') for dn in [coarse_namelist_dir, fine_namelist_dir]]] # write namelists self.nml_coarse.write(os.path.join(coarse_namelist_dir, 'namelist.wps')) self.nml_fine.write(os.path.join(fine_namelist_dir, 'namelist.wps')) if __name__=="__main__": split_nml_wps() split_nml_wrf() <file_sep>/wrfpy/cylc/wps_post.py #!/usr/bin/env python import argparse import datetime import time from wrfpy import utils from wrfpy.config import config import os #from urb import urb import shutil import glob class wps_post(config): '''' Main function to initialize WPS timestep: - converts cylc timestring to datetime object - calls wps_init() ''' def __init__(self): config.__init__(self) rundir = self.config['filesystem']['wrf_run_dir'] wpsdir = os.path.join(self.config['filesystem']['work_dir'], 'wps') ## wrf run dir # cleanup old met_em files # create list of files to remove #files = [glob.glob(os.path.join(rundir, ext)) # for ext in ['met_em*']] # flatten list #files_flat = [item for sublist in files for item in sublist] # remove files silently #[ utils.silentremove(filename) for filename in files_flat ] # copy new met_em files # create list of files to copy files = [glob.glob(os.path.join(wpsdir, ext)) for ext in ['met_em*']] # flatten list files_flat = [item for sublist in files for item in sublist] [ shutil.copyfile(filename, os.path.join(rundir, os.path.basename(filename))) for filename in files_flat ] ## wps workdir # create list of files to remove files = [glob.glob(os.path.join(wpsdir, ext)) for ext in ['met_em*', 'FILE*', 'PFILE*', 'GRIBFILE*']] # flatten list files_flat = [item for sublist in files for item in sublist] # remove files silently [ utils.silentremove(filename) for filename in files_flat ] if __name__=="__main__": wps_post() <file_sep>/tests/test_config.py #!/usr/bin/env python """ description: Configuration part of wrfpy license: APACHE 2.0 """ import os import tempfile import unittest import pkg_resources from wrfpy.config import config class TestConfig(unittest.TestCase): """Tests for the config module.""" def test_load_valid_config(self): """Test validation for run_hours fields in general.""" with tempfile.TemporaryDirectory() as temp_dir: config_file = os.path.join(temp_dir, "config.json") cfg = self._create_basic_config(config_file) cfg._check_config() self.assertEqual(1, cfg.config["options_general"]["boundary_interval"]) def test_general_run_hours(self): """Test validation for run_hours fields in wps.""" with tempfile.TemporaryDirectory() as temp_dir: config_file = os.path.join(temp_dir, "config.json") cfg = self._create_basic_config(config_file) # fail to validate if wps run_hours is not present cfg.config["options_general"]["run_hours"] = None with self.assertRaises(AssertionError): cfg._check_general() def test_wps_run_hours(self): """Test validation for run_hours fields in general and wps.""" with tempfile.TemporaryDirectory() as temp_dir: config_file = os.path.join(temp_dir, "config.json") cfg = self._create_basic_config(config_file) # fail to validate if general run_hours is not present cfg.config["options_wps"]["run_hours"] = None with self.assertRaises(AssertionError): cfg._check_wps() def test_start_date_before_end_date_validation(self): """Test validation for start date coming before end date.""" with tempfile.TemporaryDirectory() as temp_dir: config_file = os.path.join(temp_dir, "config.json") cfg = self._create_basic_config(config_file) # fail to validate if general run_hours is not present cfg.config["options_general"]["date_start"], \ cfg.config["options_general"]["date_end"] = cfg.config["options_general"]["date_end"], \ cfg.config["options_general"]["date_start"] with self.assertRaises(IOError): cfg._check_general() @classmethod def _create_basic_config(cls, config_file: str) -> config: """Create minimal configuration file for unit config unit tests.""" cfg = config(wrfpy_config=config_file) cfg._read_json() # general cfg.config["options_general"]["boundary_interval"] = 1 cfg.config["options_general"]["date_end"] = "2019-01-01_01" cfg.config["options_general"]["date_start"] = "2019-01-01_00" cfg.config["options_general"]["run_hours"] = "1" # wps cfg.config["options_wps"]["namelist.wps"] = cls._get_example_namelist() cfg.config["options_wps"]["run_hours"] = "1" # wrf cfg.config["options_wrf"]["namelist.input"] = cls._get_example_namelist() return cfg @classmethod def _get_example_namelist(cls) -> str: resource_package = __name__ resource_path = '/'.join(('..', 'wrfpy', 'examples', 'namelist.wps')) filename = pkg_resources.resource_filename(resource_package, resource_path) return os.path.realpath(filename) if __name__ == '__main__': unittest.main() <file_sep>/wrfpy/wps.py #!/usr/bin/env python ''' description: WRF Preprocessing System (WPS) part of wrfpy license: APACHE 2.0 author: <NAME>, NLeSC (<EMAIL>) ''' from wrfpy import utils import glob import subprocess import os import errno import f90nml from wrfpy.config import config from datetime import datetime import shutil from netCDF4 import Dataset class wps(config): ''' description ''' def __init__(self): config.__init__(self) # load config # define and create wps working directory self.wps_workdir = os.path.join(self.config['filesystem']['work_dir'], 'wps') utils._create_directory(self.wps_workdir) def _initialize(self, datestart, dateend, boundarydir=False): ''' Initialize WPS working directory / namelist ''' if not boundarydir: self.boundarydir = self.config['filesystem']['boundary_dir'] else: self.boundarydir = boundarydir self._clean_boundaries_wps() # clean leftover boundaries self._prepare_namelist(datestart, dateend) self._link_boundary_files() self._link_vtable() self._link_tbl_files() def _clean_boundaries_wps(self): ''' clean old leftover boundary files in WPS directory ''' # create list of files to remove files = [glob.glob(os.path.join(self.wps_workdir, ext)) for ext in ['GRIBFILE.*', 'FILE:', 'PFILE:', 'PRES:']] # flatten list files_flat = [item for sublist in files for item in sublist] # remove files silently [ utils.silentremove(filename) for filename in files_flat ] def _prepare_namelist(self, datestart, dateend): ''' prepare wps namelist ''' # read WPS namelist in WPS work_dir wps_nml = f90nml.read(self.config['options_wps']['namelist.wps']) # get numer of domains ndoms = wps_nml['share']['max_dom'] # check if ndoms is an integer and >0 if not (isinstance(ndoms, int) and ndoms>0): raise ValueError("'domains_max_dom' namelist variable should be an " \ "integer>0") # check if both datestart and dateend are a datetime instance if not all([ isinstance(dt, datetime) for dt in [datestart, dateend] ]): raise TypeError("datestart and dateend must be an instance of datetime") # set new datestart and dateend wps_nml['share']['start_date'] = [datetime.strftime(datestart, '%Y-%m-%d_%H:%M:%S')] * ndoms wps_nml['share']['end_date'] = [datetime.strftime(dateend, '%Y-%m-%d_%H:%M:%S')] * ndoms # write namelist in wps work_dir utils.silentremove(os.path.join( self.config['filesystem']['work_dir'], 'wps', 'namelist.wps')) wps_nml.write(os.path.join( self.config['filesystem']['work_dir'], 'wps', 'namelist.wps')) def _link_boundary_files(self): ''' link boundary grib files to wps work directory with the required naming ''' # get list of files to link filelist = glob.glob(os.path.join(self.boundarydir, '*')) # make sure we only have files filelist = [fl for fl in filelist if os.path.isfile(fl)] if len(filelist) == 0: message = 'linking boundary files failed, no files found to link' #logger.error(message) raise IOError(message) # get list of filename extensions to use for destination link linkext = self._get_ext_list(len(filelist)) # link grib files [os.symlink(filelist[idx], os.path.join( self.wps_workdir, 'GRIBFILE.' + linkext[idx])) for idx in range(len(filelist))] def _get_ext_list(self, num): ''' create list of filename extensions for num number of files Extensions have the form: AAA, AAB, AAC... ABA, ABB...,BAA, BAB... ''' from string import ascii_uppercase # create list of uppercase letters used linkname extension ext = [ascii_uppercase[idx] for idx in range(0,len(ascii_uppercase))] i1, i2, i3 = 0, 0, 0 for filenum in range(num): # loop over number of files # append extension to list (or create list for first iteration) try: list_ext.append(ext[i3] + ext[i2] + ext[i1]) except NameError: list_ext = [ext[i3] + ext[i2] + ext[i1]] i1 += 1 # increment i1 if i1 >= len(ascii_uppercase): i1 = 0 i2 += 1 # increment i2 if i2 >= len(ascii_uppercase): i2 = 0 i3 += 1 # increment i3 if i3 >= len(ascii_uppercase): message = 'Too many files to link' #logger.error(message) raise IOError(message) return list_ext def _link_vtable(self): ''' link the required Vtable ''' utils.silentremove(os.path.join(self.wps_workdir, 'Vtable')) vtable = self.config['options_wps']['vtable'] vtable_path = os.path.join(self.config['filesystem']['wps_dir'], 'ungrib', 'Variable_Tables', vtable) os.symlink(vtable_path, os.path.join(self.wps_workdir, 'Vtable')) def _link_tbl_files(self): ''' link GEOGRID.TBL and METGRID.TBL into wps work_dir ''' # geogrid if not os.path.isfile(os.path.join(self.wps_workdir, 'geogrid', 'GEOGRID.TBL')): if not self.config['options_wps']['geogrid.tbl']: geogridtbl = os.path.join(self.config['filesystem']['wps_dir'], 'geogrid', 'GEOGRID.TBL.ARW') else: geogridtbl = self.config['options_wps']['geogrid.tbl'] utils._create_directory(os.path.join(self.wps_workdir, 'geogrid')) os.symlink(geogridtbl, os.path.join(self.wps_workdir, 'geogrid', 'GEOGRID.TBL')) # metgrid if not os.path.isfile(os.path.join(self.wps_workdir, 'metgrid', 'METGRID.TBL')): if not self.config['options_wps']['metgrid.tbl']: metgridtbl = os.path.join(self.config['filesystem']['wps_dir'], 'metgrid', 'METGRID.TBL.ARW') else: metgridtbl = self.config['options_wps']['metgrid.tbl'] utils._create_directory(os.path.join(self.wps_workdir, 'metgrid')) os.symlink(metgridtbl, os.path.join(self.wps_workdir, 'metgrid', 'METGRID.TBL')) def _run_geogrid(self, j_id=None): ''' run geogrid.exe (locally or using slurm script defined in config.json) ''' # get number of domains from wps namelist wps_nml = f90nml.read(self.config['options_wps']['namelist.wps']) ndoms = wps_nml['share']['max_dom'] # check if geo_em files already exist for all domains try: for dom in range(1, ndoms + 1): fname = "geo_em.d{}.nc".format(str(dom).zfill(2)) ncfile = Dataset(os.path.join(self.wps_workdir, fname)) ncfile.close() except IOError: # create geo_em nc files if len(self.config['options_slurm']['slurm_geogrid.exe']): # run using slurm if j_id: mid = "--dependency=afterok:%d" %j_id geogrid_command = ['sbatch', mid, self.config['options_slurm']['slurm_geogrid.exe']] else: geogrid_command = ['sbatch', self.config['options_slurm']['slurm_geogrid.exe']] utils.check_file_exists(geogrid_command[1]) utils.silentremove(os.path.join(self.wps_workdir, 'geogrid', 'geogrid.exe')) os.symlink(os.path.join(self.config['filesystem']['wps_dir'],'geogrid','geogrid.exe'), os.path.join(self.wps_workdir, 'geogrid', 'geogrid.exe')) try: res = subprocess.check_output(geogrid_command, cwd=self.wps_workdir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('Metgrid failed %s:' %geogrid_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: geogrid_command = os.path.join(self.config['filesystem']['wps_dir'], 'geogrid', 'geogrid.exe') utils.check_file_exists(geogrid_command) try: subprocess.check_call(geogrid_command, cwd=self.wps_workdir, stdout=utils.devnull(), stderr=utils.devnull()) except subprocess.CalledProcessError: #logger.error('Geogrid failed %s:' %geogrid_command) raise # re-raise exception def _run_ungrib(self, j_id=None): ''' run ungrib.exe (locally or using slurm script defined in config.json) ''' if len(self.config['options_slurm']['slurm_ungrib.exe']): # run using slurm if j_id: mid = "--dependency=afterok:%d" %j_id ungrib_command = ['sbatch', mid, self.config['options_slurm']['slurm_ungrib.exe']] else: ungrib_command = ['sbatch', self.config['options_slurm']['slurm_ungrib.exe']] utils.check_file_exists(ungrib_command[-1]) utils.silentremove(os.path.join(self.wps_workdir, 'ungrib', 'ungrib.exe')) if not os.path.isdir(os.path.join(self.wps_workdir, 'ungrib')): utils._create_directory(os.path.join(self.wps_workdir, 'ungrib')) os.symlink(os.path.join(self.config['filesystem']['wps_dir'],'ungrib','ungrib.exe'), os.path.join(self.wps_workdir, 'ungrib', 'ungrib.exe')) try: res = subprocess.check_output(ungrib_command, cwd=self.wps_workdir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('Ungrib failed %s:' %ungrib_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: ungrib_command = os.path.join(self.config['filesystem']['wps_dir'], 'ungrib', 'ungrib.exe') utils.check_file_exists(ungrib_command) try: subprocess.check_call(ungrib_command, cwd=self.wps_workdir, stdout=utils.devnull(), stderr=utils.devnull()) except subprocess.CalledProcessError: #logger.error('Ungrib failed %s:' %ungrib_command) raise # re-raise exception def _run_metgrid(self, j_id=None): ''' run metgrid.exe (locally or using slurm script defined in config.json) ''' if len(self.config['options_slurm']['slurm_metgrid.exe']): # run using slurm if j_id: mid = "--dependency=afterok:%d" %j_id metgrid_command = ['sbatch', mid, self.config['options_slurm']['slurm_metgrid.exe']] else: metgrid_command = ['sbatch', self.config['options_slurm']['slurm_metgrid.exe']] utils.check_file_exists(metgrid_command[-1]) utils.silentremove(os.path.join(self.wps_workdir, 'metgrid', 'metgrid.exe')) os.symlink(os.path.join(self.config['filesystem']['wps_dir'],'metgrid','metgrid.exe'), os.path.join(self.wps_workdir, 'metgrid', 'metgrid.exe')) try: res = subprocess.check_output(metgrid_command, cwd=self.wps_workdir, stderr=utils.devnull()) j_id = int(res.split()[-1]) # slurm job-id except subprocess.CalledProcessError: #logger.error('Metgrid failed %s:' %metgrid_command) raise # re-raise exception utils.waitJobToFinish(j_id) else: metgrid_command = os.path.join(self.config['filesystem']['wps_dir'], 'metgrid', 'metgrid.exe') utils.check_file_exists(metgrid_command) try: subprocess.check_call(metgrid_command, cwd=self.wps_workdir, stdout=utils.devnull(), stderr=utils.devnull()) except subprocess.CalledProcessError: #logger.error('Metgrid failed %s:' %metgrid_command) raise # re-raise exception <file_sep>/wrfpy/cylc/upp.py #!/usr/bin/env python import argparse import datetime import time from wrfpy import utils from wrfpy.upp import upp from wrfpy.config import config import os class run_upp(config): '''' ''' def __init__(self, datestring): config.__init__(self) dt = utils.convert_cylc_time(datestring) postprocess = upp() # construct wrfout name for domain 1 dt_str = dt.strftime('%Y-%m-%d_%H:%M:%S') wrfout_name = 'wrfout_d01_' + dt_str wrfout_file = os.path.join(self.config['filesystem']['wrf_run_dir'], wrfout_name) start_date = utils.return_validate(postprocess.config['options_general']['date_start']) upp_interval = postprocess.config['options_upp']['upp_interval'] if (start_date == dt): # very first timestep postprocess.run_unipost_file(wrfout_file, frequency=upp_interval, use_t0=True) else: postprocess.run_unipost_file(wrfout_file, frequency=upp_interval, use_t0=False) if __name__=="__main__": parser = argparse.ArgumentParser(description='Initialize WRF step.') parser.add_argument('datestring', metavar='N', type=str, help='Date-time string from cylc suite') # parse arguments args = parser.parse_args() # call main run_upp(args.datestring)
74462c98593ca06653f174468ab52d17dfc0a501
[ "Markdown", "Python", "Text", "reStructuredText" ]
34
Python
ERA-URBAN/wrfpy
caa1159326abcc59e5e25921f5de72a274962275
421c32397fb71a5437f93a5b03bf5dc3a2a12955
refs/heads/master
<repo_name>katelin013/go_linebot<file_sep>/README.md 練習LineBot 用Go 網頁爬蟲 從卡提諾正妹論壇 抓取隨機圖片 <file_sep>/main.go package main import ( "fmt" "log" "math/rand" "net/http" "os" "strconv" "strings" "time" "github.com/PuerkitoBio/goquery" "github.com/line/line-bot-sdk-go/linebot" ) var bot *linebot.Client var messages []linebot.Message var imgary [5]linebot.ImageMessage func main() { var err error bot, err = linebot.New(os.Getenv("ChannelSecret"), os.Getenv("ChannelAccessToken")) log.Println("Bot:", bot, " err:", err) http.HandleFunc("/callback", callbackHandler) port := os.Getenv("PORT") addr := fmt.Sprintf(":%s", port) http.ListenAndServe(addr, nil) } func callbackHandler(w http.ResponseWriter, r *http.Request) { events, err := bot.ParseRequest(r) if err != nil { if err == linebot.ErrInvalidSignature { w.WriteHeader(400) } else { w.WriteHeader(500) } return } for _, event := range events { if event.Type == linebot.EventTypeMessage { switch message := event.Message.(type) { case *linebot.TextMessage: if strings.Contains(message.Text, "test") { s := linebot.NewImageMessage("test", "test") fmt.Println(s) } else if strings.Contains(message.Text, "妹子") { imgAry := getPrettyUrl() if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewImageMessage(imgAry[0], imgAry[0]), linebot.NewImageMessage(imgAry[1], imgAry[1]), linebot.NewImageMessage(imgAry[2], imgAry[2]), linebot.NewImageMessage(imgAry[3], imgAry[3]), linebot.NewImageMessage(imgAry[4], imgAry[4])).Do(); err != nil { log.Print(err) } } else { } } } } } func botReplyMsg(s string) string { result := "" switch s { case "1": result = "a" case "2": result = "b" default: result = "我聽不懂你在說什麼小朋友!!" } return result } func getPrettyUrl() []string { var strAry []string var imgAry []string rand.Seed(time.Now().UnixNano()) baseUrl := "https://ck101.com/forum-3581-" + strconv.Itoa(rand.Intn(1000)) + ".html" doc, err := goquery.NewDocument(baseUrl) if err != nil { log.Fatal(err) } doc.Find("td.thumb_preview").Find("a").Each(func(i int, s *goquery.Selection) { text2, _ := s.Attr("href") strAry = append(strAry, text2) }) prettyUrl := strAry[rand.Intn(len(strAry))] doc2, err := goquery.NewDocument(prettyUrl) if err != nil { log.Fatal(err) } doc2.Find("img").Each(func(i int, s *goquery.Selection) { imgText, _ := s.Attr("file") if len(imgText) > 0 && strings.Contains(imgText, "https") && strings.Contains(imgText, "jpg") { imgAry = append(imgAry, imgText) } }) return imgAry }
c82fd10d4f4de0a1a70cae22a14d2867c9adc43c
[ "Markdown", "Go" ]
2
Markdown
katelin013/go_linebot
646beb8355eb5d24a873f0fa77705687f305a06c
6caddb48283ed6dd52abf9df9f5732686cd0fca4
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class trackdistance : MonoBehaviour { //BIG AWL CHANGE GITHUB!?!??! public float distanceTravelled = 0; Vector3 lastPosition; // Use this for initialization void Start () { lastPosition = transform.position; } // Update is called once per frame void Update () { Debug.Log(distanceTravelled + "ok this time it will work"); distanceTravelled += Vector3.Distance(transform.position, lastPosition); lastPosition = transform.position; } }
7893f97f8cbfbea8aba86958e268eec32360ebc6
[ "C#" ]
1
C#
SwcMarshall/Test2
2c8173d6176fbe3cf0ce201175b79f050c253e7b
6d8c82d8b68b4f07bc0b3795585024d494e3abe4
refs/heads/main
<file_sep>version: '3.7' volumes: rabbitmq-data: db_data: services: vscode: build: context: .. dockerfile: Dockerfile.dev args: # [Choice] Python version: 3, 3.8, 3.7, 3.6 VARIANT: 3 USER_UID: 1000 USER_GID: 1000 volumes: - ..:/workspace:cached #- ..:/workspace - ~/.ssh:/home/vscode/.ssh - ~/.ssh:/root/.ssh - /var/run/docker.sock:/var/run/docker.sock environment: TZ: 'Europe/Copenhagen' #- DATABASE_CONN_URI=postgres@database:5432/postgress #- RABBITMQ_CONN_URI=amqp://guest:guest@rabbitmq:5672/ RABBITMQ_DEFAULT_USER: 'guest' RABBITMQ_DEFAULT_PASS: 'guest' RABBITMQ_HOST: 'rabbitmq' MYSQL_DATABASE: 'commentdb' # So you don't have to use root, but you can if you like MYSQL_USER: 'user' # You can use whatever password you like MYSQL_PASSWORD: '<PASSWORD>' # Password for root access MYSQL_ROOT_PASSWORD: '<PASSWORD>' MYSQL_HOST: 'mySQL' RABBITMQ_PORT: '5672' cap_add: - SYS_PTRACE security_opt: - seccomp:unconfined command: sleep infinity restart: unless-stopped rabbitmq: image: rabbitmq:3-management volumes: - rabbitmq-data:/var/lib/rabbitmq ports: - 5672:5672 - 15672:15672 environment: RABBITMQ_DEFAULT_USER: 'guest' RABBITMQ_DEFAULT_PASS: '<PASSWORD>' restart: unless-stopped mySQL: image: mysql:8 container_name: comment_db volumes: - db_data:/var/lib/mysql environment: MYSQL_DATABASE: 'commentdb' # So you don't have to use root, but you can if you like MYSQL_USER: 'user' # You can use whatever password you like MYSQL_PASSWORD: '<PASSWORD>' # Password for root access MYSQL_ROOT_PASSWORD: '<PASSWORD>' MYSQL_HOST: 'mySQL' ports: - 3306:3306 restart: unless-stopped app: build: .. ports: - 5000:5000 depends_on: - mySQL - rabbitmq environment: RABBITMQ_DEFAULT_USER: 'guest' RABBITMQ_DEFAULT_PASS: 'guest' RABBITMQ_HOST: 'rabbitmq' RABBITMQ_PORT: '5672' MYSQL_DATABASE: 'commentdb' MYSQL_HOST: 'mySQL' # So you don't have to use root, but you can if you like MYSQL_USER: 'user' # You can use whatever password you like MYSQL_PASSWORD: '<PASSWORD>' # Password for root access MYSQL_ROOT_PASSWORD: '<PASSWORD>' restart: unless-stopped<file_sep>import os USER = os.environ['MYSQL_USER'] PASSWORD = os.environ['<PASSWORD>'] HOST = os.environ['MYSQL_HOST'] DATABASE = os.environ['MYSQL_DATABASE'] DATABASE_CONNECTION_URI = f'mysql+mysqlconnector://{USER}:{PASSWORD}@{HOST}:3306/{DATABASE}' AMQP_USER = os.environ['RABBITMQ_DEFAULT_USER'] AMQP_PASSWORD = os.environ['RABBITMQ_DEFAULT_PASS'] RABBITMQ_PORT = os.environ['RABBITMQ_PORT'] RABBITMQ_HOST = os.environ['RABBITMQ_HOST'] AMQP_URI = f"amqp://{AMQP_USER}:{AMQP_PASSWORD}@{RABBITMQ_HOST}:{RABBITMQ_PORT}/"<file_sep>import unittest import json from dbmanager import get_all_comments, request_comment, update_comment, delete_comment, request_comments_for_post, create_comment, remove_all_comments from receiver import session, send import time import pika class TestComments(unittest.TestCase): # Tests for dbmanager class test_auth_id = <PASSWORD> test_post_id = 2147483645 test_role = 6 admin_role = 21 hdrs = {'jwt': '<KEY>', 'http-response': '200'} properties = pika.BasicProperties(correlation_id='1337', content_type='application/json', headers=hdrs) def test_create_a_comment(self): loadedJson = json.loads(create_comment(session, self.test_auth_id, self.test_post_id, "This is a test", self.properties)) httpResponse = loadedJson['http_response'] # Clean database from test comment entry delete_comment(session, self.test_auth_id, loadedJson['comment_id'], self.admin_role, self.properties) self.assertEqual(httpResponse, 200, "[-] Error creating comment") def test_request_comment_by_id(self): createJson = json.loads(create_comment(session, self.test_auth_id, self.test_post_id, "This is a test", self.properties)) temp = request_comment(session, createJson['comment_id'], self.properties) loadedJson = json.loads(temp) httpResponse = loadedJson['http_response'] # Clean database from test comment entry delete_comment(session, self.test_auth_id, createJson['comment_id'], self.admin_role, self.properties) self.assertEqual(httpResponse, 200, "[-] Error requesting comment") def test_request_comment_by_id_wrongId(self): createJson = json.loads(create_comment(session, self.test_auth_id, self.test_post_id, "This is a test", self.properties)) temp = request_comment(session, self.test_auth_id, self.properties) loadedJson = json.loads(temp) httpResponse = loadedJson['http_response'] # Clean database from test comment entry delete_comment(session, self.test_auth_id, createJson['comment_id'], self.admin_role, self.properties) self.assertEqual(httpResponse, 403, "[-] Requests with wrong ID, positive HTTP response anyways.") def test_update_comment_content(self): #createJson = json.loads(create_comment(session, 999999, 999999, "This is a test")) createJson = json.loads(create_comment(session, self.test_auth_id, self.test_post_id, "This is a test", self.properties)) temp = update_comment(session, createJson['comment_id'], self.test_auth_id, "Rewrote test content", self.test_role, self.properties) loadedJson = json.loads(temp) httpResponse = loadedJson['http_response'] # Clean database from test comment entry delete_comment(session, self.test_auth_id, createJson['comment_id'], self.admin_role, self.properties) self.assertEqual(httpResponse, 200, "[-] Error changing comment") def test_update_comment_wrong_author(self): createJson = json.loads(create_comment(session, self.test_auth_id, self.test_post_id, "This is a test", self.properties)) temp = update_comment(session, createJson['comment_id'], 42, "Rewrote test content", self.test_role, self.properties) loadedJson = json.loads(temp) httpResponse = loadedJson['http_response'] # Clean database from test comment entry delete_comment(session, self.test_auth_id, createJson['comment_id'], self.admin_role, self.properties) self.assertEqual(httpResponse, 403, "[-] Changing comment with wrong author still gives positive HTTP response.") def test_delete_a_comment(self): createJson = json.loads(create_comment(session, self.test_auth_id, self.test_post_id, "This is a test", self.properties)) temp = delete_comment(session, self.test_auth_id, createJson['comment_id'], self.test_role, self.properties) loadedJson = json.loads(temp) httpResponse = loadedJson['http_response'] self.assertEqual(httpResponse, 200, "[-] Error deleting comment") def test_delete_a_comment_wrong_author(self): createJson = json.loads(create_comment(session, self.test_auth_id, self.test_post_id, "This is a test", self.properties)) temp = delete_comment(session, 42, createJson['comment_id'], self.test_role, self.properties) loadedJson = json.loads(temp) httpResponse = loadedJson['http_response'] # Clean database from test comment entry delete_comment(session, self.test_auth_id, createJson['comment_id'], self.admin_role, self.properties) self.assertEqual(httpResponse, 403, "[-] Deleting a comment with wrong author, still gives positive HTTP response.") # RabbitMQ tests # Send an event # Look in the database if the event has triggered anything if __name__ == '__main__': unittest.main() <file_sep># For reference: https://www.docker.com/blog/containerized-python-development-part-1/ # This dockerfile will run the tests. # set base image (host OS) FROM python:3.9 # set the working directory in the container WORKDIR /code # copy the dependencies file to the working directory COPY requirements.txt . # install dependencies RUN pip install -r requirements.txt # copy the content COPY . . # command to run on container start CMD [ "python", "./tests.py" ] <file_sep># API Specification For every event, if it is a request it is stated what routing key the rabbitmq message should contain. And for the response, it is stated what routing key the response to the event will be put. ## CreateComment Request Routing Key - "CreateComment" ```json { "user_id": "<User id of the person wanting to create a comment>", "post_id": "<Id of the post user wants to comment on>", "content": "<Content of the comment>" } ``` Response Routing Key - "ConfirmCommentCreation" ```json { "comment_id": "<Id of the created comment>", "http_response": "HTTP response, 200 success, 403 unsuccessful", "created_at": "<ISO8601 timestamp>" } ``` ## UpdateComment At this time, updating comments will simply replace the current content of a comment within the DB with some new content. Request Routing Key - "UpdateComment" ```json { "comment_id": "<Id of the comment requestet>", "user_id": "<id of the user wanting to change a comment>", "content": "<Content of the new comment>" } ``` Response Routing Key - "ConfirmCommentUpdate" ```json { "http_response": "HTTP response, 200 for success, 403 if unsuccessful", "comment_id": "<Id of the comment user wants to change>", "update_timestamp": "<ISO8601 timestamp, 1000001 if unsuccessful>" } ``` ## DeleteComment Request Routing Key - "DeleteComment" ```json { "comment_id": "<Id of the comment user wants to delete>", "user_id": "<Id of the user wanting to make the change>", } ``` Response Routing Key - "ConfirmCommentDelete" ```json { "http_response": "HTTP response, 200 for success, 403 if unsuccessful" } ``` ## RequestComment Request Routing Key - "RequestComment" ```json { "comment_id": "<Id of the comment user wants to receive>" } ``` Response Routing Key - "ReturnComment" ```json { "comment_id": "<Id of the comment>", "author_id": "<Id of the author of comment", "post_id": "<Id of the post associated with comment>", "created_at": "<ISO8601 timestamp>", "content": "<content>", "http_response": "HTTP response code, 200 for success, 403 if unsucessful" } ``` ## RequestCommentsForPost Request Routing Key - "RequestCommentsForPost" ```json { "post_id": "<Id of the post user wants to receive comments from>" } ``` Response Routing Key - "ReturnCommentsForPost" ```json { "list_of_comments": "<Array of comments, each element contains comments id, post id, creation time, and content.>" } ``` <file_sep>from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from dbmanager import get_all_comments, request_comment, update_comment, delete_comment, request_comments_for_post, create_comment, delete_comments_for_post from config import DATABASE_CONNECTION_URI from models import Base, Comment from jose import jwt import mysql.connector import json import pika import sys import time from config import AMQP_PASSWORD, AMQP_USER, AMQP_URI, RABBITMQ_PORT, RABBITMQ_HOST # For the db part print("Connecting to database") engine = create_engine(DATABASE_CONNECTION_URI) #Connect to a specific database, remove echo later Base.metadata.create_all(bind=engine) # From the base, create all the tables in Base to the connected DB Session = sessionmaker(bind=engine) #Create a session factory session = Session() #Start a session with the engine print("Succesfully connected to database") # end of db part events = ['CreateComment', 'UpdateComment', 'DeleteComment', 'RequestComment', 'RequestCommentsForPost', "ConfirmOnePostDeletion"] ''' @Input: Event string, json data(dict) @Output: None, puts object onto rapid ''' def send(event, data, properties): channel.basic_publish(exchange='rapid', routing_key=event, body=data, properties=properties) #It decodes the token and makes sure that the issuer is what we expect and that it has not expired def verify(token): try: decoded = jwt.decode(token, "secret", algorithms=['HS256']) millis = int(round(time.time() * 1000)) if (decoded["iss"] == "ImageHost.sdu.dk" and decoded["exp"] < millis): return decoded else: return None except: return None ''' @Input: event string, json data(dict) @Output: Nothing, calls a function to put object onto rapid ''' def receive(event, data, properties): data = json.loads(data) print(properties.headers) jwt = verify(properties.headers['jwt']) if event == "CreateComment": if(jwt): jsonObject = create_comment(session, int(jwt['sub']), data['post_id'], data['content'], properties) # Get the actual http response from the action and put it into properties httpResponse = json.loads(jsonObject)['http_response'] properties.headers['http_response'] = httpResponse send("ConfirmCommentCreation", jsonObject, properties) print(f'Created comment with json: {jsonObject}') else: errorJson = json.dumps({'comment_id': 2147483645, 'http_response': 403, 'created_at': 1000001}, indent=2, default=str) send("ConfirmCommentCreation", errorJson, properties) print(f'Created comment with json: {jsonObject}') elif event == "UpdateComment": if(jwt): jsonObject = update_comment(session, int(data['comment_id']), int(jwt['sub']), data['content'], int(jwt['role']), properties) httpResponse = json.loads(jsonObject)['http_response'] properties.headers['http_response'] = httpResponse send("ConfirmCommentUpdate", jsonObject, properties) print(f'Updated comment with {jsonObject}') else: errorJson = json.dumps({'http_response': 403, 'comment_id': data['comment_id'], 'update_timestamp': 1000001}, indent=2, default=str) send("ConfirmCommentUpdate", errorJson, properties) print(f'Updated comment with {jsonObject}') elif event == "DeleteComment": if(jwt): jsonObject = delete_comment(session, int(jwt['sub']), int(data['comment_id']), int(jwt['role']), properties) httpResponse = json.loads(jsonObject)['http_response'] properties.headers['http_response'] = httpResponse send("ConfirmCommentDelete", jsonObject, properties) print(f'Deleted comment with {jsonObject}') else: errorJson = json.dumps({'http_response': 403}, indent=2, default=str) send("ConfirmCommentDelete", errorJson, properties) print(f'Deleted comment with {jsonObject}') elif event == "ConfirmOnePostDeletion": # No checking needed, as this has been done by the one triggering the event delete_comments_for_post(session, data['post_id']) elif event == "RequestComment": jsonObject = request_comment(session, data['comment_id'], properties) httpResponse = json.loads(jsonObject)['http_response'] properties.headers['http_response'] = httpResponse send("ReturnComment", jsonObject, properties) print(f'Requested comment with {jsonObject}') elif event == "RequestCommentsForPost": jsonObject = request_comments_for_post(session, data['post_id'], properties) properties.headers['http_response'] = 200 send("ReturnCommentsForPost", jsonObject, properties) print(f'Requested comment for post {jsonObject}') else: pass # A wrong event has been given def callback(channel, method, properties, body): event = method.routing_key print("###################################") print(method) print(properties) print(body) print("###################################") receive(event, body, properties) if __name__ == '__main__': print("Trying to connect to rabbitmq") print("Rabbit host:", RABBITMQ_HOST) print("Rabbit user:", AMQP_USER) print("Rabbit pass:", AMQP_PASSWORD) credentials = pika.PlainCredentials(AMQP_USER, AMQP_PASSWORD) connection = pika.BlockingConnection(pika.ConnectionParameters( host=RABBITMQ_HOST, port=RABBITMQ_PORT, virtual_host='/', credentials=credentials)) channel = connection.channel() channel.exchange_declare(exchange='rapid', exchange_type='direct') channel.queue_declare('comments') print("Succesfully connected to rabbitmq") for event in events: print(f"Binding to event: {event}") channel.queue_bind(queue='comments', exchange='rapid', routing_key=event) print("Starts consuming:") channel.basic_consume(queue='comments', on_message_callback=callback, auto_ack=True) channel.start_consuming() <file_sep>## ONLY a tester file.. import pika, json from config import AMQP_PASSWORD, AMQP_USER from dbmanager import get_all_comments, request_comments_for_post, request_comment, delete_comments_for_post from receiver import session credentials = pika.PlainCredentials(AMQP_USER, AMQP_PASSWORD) connection = pika.BlockingConnection(pika.ConnectionParameters( host='rabbitmq', port=5672, virtual_host='/', credentials=credentials)) channel = connection.channel() channel = connection.channel() channel.exchange_declare(exchange='rapid', exchange_type='direct') # Create a comment: #jsonob = json.dumps({'user_id': "3", 'post_id': "5", 'content': "imma fking yeet"}, indent=2, default=str) #event = "CreateComment" # Delete comments for post: #jsonob = json.dumps({'post_id': "6"}, indent=2, default=str) #event = "ConfirmOnePostDeletion" # Update a comment: #jsonob = json.dumps({'comment_id': 16, 'user_id': 1, 'content': "I am changed, still yeeting"}, indent=2, default=str) #event = "UpdateComment" # Delete a comment: #jsonob = json.dumps({'user_id': 1, 'comment_id': 16}, indent=2, default=str) #event = "DeleteComment" hdrs = {'jwt': '<KEY>', 'http_response': '200'} properties = pika.BasicProperties(correlation_id='1337', content_type='application/json', headers=hdrs) channel.basic_publish(exchange='rapid', routing_key=event, body=jsonob, properties=properties) connection.close() comments = get_all_comments(session) for comment in comments: print(comment.id) print(comment.authorId) print(comment.postId) print(comment.content) <file_sep>from datetime import datetime from models import Base, Comment import json import sys import sqlalchemy user_role_range = [x for x in range(10)] mod_role_range = [x for x in range(10,20)] admin_role_range = [x for x in range(20,30)] ''' For testing. Given a session, returns all objects for that session. ''' def get_all_comments(session): #session = Session() comments = session.query(Comment).all() return comments def remove_all_comments(session, properties): comments = get_all_comments(session) for comment in comments: delete_comment(session, comment.authorId, comment.id, 25, properties) ''' For testing ''' def size_of_db(session): size = 0 comments = session.query(Comment).all() for comment in comments: size = size + 1 return size ''' @Input - A session, and comment Id(cId) @Output - Json object containing the comment's id, post id, ISO8601 timestamp(when it was created), and the content. ''' def request_comment(session, cId, properties): print("Requesting a comment") try: comment = session.query(Comment).get(cId) return json.dumps({'comment_id': comment.id, 'author_id': comment.authorId, 'post_id': comment.postId, 'created_at': comment.postedAt, 'content': comment.content, 'http_response': 200}, indent=2, default=str) except (sqlalchemy.exc.InterfaceError, sqlalchemy.exc.OperationalError): print("Database is down, crashing service. Restarting, sending default error on rapid") jsonObject = json.dumps({'comment_id': 9999999, 'http_response': 403, 'created_at': 9999999}, indent=2, default=str) properties.headers['http_response'] = 503 send("ConfirmCommentCreation", jsonObject, properties) exit() #raise Exception("Database is down, crashing service. Restarting, sending default error on rapid") except Exception as e: print("[-] Exception ", e.__class__, " occurred.") return json.dumps({'comment_id': 9999999, 'http_response': 403, 'created_at': 9999999}, indent=2, default=str) ''' @Input - A session, authorId, postId, content @Output - The created comment's id, ISO8601 timestamp for when it was created, and http response code. ''' def create_comment(session, authorId, postId, content, properties): print("Creating a comment") try: comment = Comment() comment.authorId = authorId comment.postId = postId comment.postedAt = datetime.now().isoformat() comment.content = content session.add(comment) session.commit() session.refresh(comment) # Needs this to refer to comment.id return json.dumps({'comment_id': comment.id, 'http_response': 200, 'created_at': comment.postedAt}, indent=2, default=str) except (sqlalchemy.exc.InterfaceError, sqlalchemy.exc.OperationalError): print("Database is down, crashing service. Restarting, sending default error on rapid") jsonObject = json.dumps({'comment_id': 9999999, 'http_response': 403, 'created_at': 9999999}, indent=2, default=str) properties.headers['http_response'] = 503 send("ConfirmCommentCreation", jsonObject, properties) exit() #raise Exception("Database is down, crashing service. Restarting, sending default error on rapid") except Exception as e: print("[-] Exception ", e.__class__, " occurred.") return json.dumps({'comment_id': 9999999, 'http_response': 403, 'created_at': 9999999}, indent=2, default=str) ''' @Input - A session, id of the comment user wants to change, id of the author/user wanting to make a change, and the new content. @Return - id of the comment being changed, http response code, ISO8601 timestamp representing when it was modified. ''' def update_comment(session, cId, aId, newContent, role, properties): print("Updating a comment") try: comment = session.query(Comment).get(cId) # Might not exist if(aId == comment.authorId or role in mod_role_range or role in admin_role_range): comment.content = newContent comment.postedAt = datetime.now().isoformat() session.commit() return json.dumps({'http_response': 200, 'comment_id': comment.id, 'update_timestamp': comment.postedAt}, indent=2, default=str) else: return json.dumps({'http_response': 403, 'comment_id': comment.id, 'update_timestamp': comment.postedAt}, indent=2, default=str) except (sqlalchemy.exc.InterfaceError, sqlalchemy.exc.OperationalError): print("Database is down, crashing service. Restarting, sending default error on rapid") jsonObject = json.dumps({'http_response': 503, 'comment_id': 9999999, 'update_timestamp': 9999999}, indent=2, default=str) properties.headers['http_response'] = 503 send("ConfirmCommentCreation", jsonObject, properties) exit() #raise Exception("Database is down, crashing service. Restarting, sending default error on rapid") except Exception as e: print("[-] Exception ", e.__class__, " occurred.") return json.dumps({'http_response': 503, 'comment_id': 9999999, 'update_timestamp': 9999999}, indent=2, default=str) ''' @Input - A session, id of the user/author wanting to delete comment, and the id of the comment @Output - Http response code ''' def delete_comment(session, aId, cId, role, properties): print("Deleting a comment") #apparently it has to be done in two steps. Can't just call .delete() try: comment = session.query(Comment).get(cId) # Might not exist if(aId == comment.authorId or role in mod_role_range or role in admin_role_range): session.delete(comment) session.commit() return json.dumps({'http_response': 200}, indent=2, default=str) else: return json.dumps({'http_response': 403}, indent=2, default=str) except (sqlalchemy.exc.InterfaceError, sqlalchemy.exc.OperationalError): print("Database is down, crashing service. Restarting, sending default error on rapid") jsonObject = json.dumps({'http_response': 503}, indent=2, default=str) properties.headers['http_response'] = 503 send("ConfirmCommentCreation", jsonObject, properties) exit() # raise Exception("Database is down, crashing service. Restarting, sending default error on rapid") except Exception as e: print("[-] Exception ", e.__class__, " occurred.") return json.dumps({'http_response': 403}, indent=2, default=str) ''' @Input - A session, and the id of a post @Output - A list of comments in json format ''' def request_comments_for_post(session, pId, properties): print("Getting comments for post") jsonComments = [] try: comments = session.query(Comment).filter(Comment.postId==pId).all() for comment in comments: jsonDump = json.dumps({'comment_id': comment.id, 'author_id': comment.authorId, 'post_id': comment.postId, 'created_at': comment.postedAt, 'content': comment.content}, indent=2, default=str) jsonComments.append(json.loads(jsonDump)) return json.dumps({'list_of_comments': jsonComments}, indent=2, default=str) except (sqlalchemy.exc.InterfaceError, sqlalchemy.exc.OperationalError): print("Database is down, crashing service. Restarting, sending default error on rapid") jsonObject = json.dumps({'list_of_comments': jsonComments}, indent=2, default=str) properties.headers['http_response'] = 503 send("ConfirmCommentCreation", jsonObject, properties) exit() #raise Exception("Database is down, crashing service. Restarting, sending default error on rapid") except Exception as e: print("[-] Exception ", e.__class__, " occurred.") properties.headers['http_response'] = 403 return json.dumps({'list_of_comments': jsonComments}, indent=2, default=str) def delete_comments_for_post(session, pId): try: comments = session.query(Comment).filter(Comment.postId==pId).all() for comment in comments: session.delete(comment) session.commit() except Exception as e: print("[-] Exception ", e.__class__, " occurred.") <file_sep>flask==1.0.2 flask-sqlalchemy==2.3.0 pika mysql-connector-python python-jose[cryptography]<file_sep>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine, Column, Integer, String, DateTime # Base which is shared by "all" of the models Base = declarative_base() ############# Models ################ class Comment(Base): __tablename__ = 'comments' id = Column(Integer, primary_key=True) authorId = Column(Integer) postId = Column(String(100)) postedAt = Column(DateTime) content = Column(String(100)) <file_sep>flask==1.0.2 flask-sqlalchemy==2.3.0 pika python-jose[cryptography] mysql-connector-python docker>=4.0.0 parameterized>=0.7.0 # This is for the dockerfile doing the testing
d35dae2518f79ef4505fb69bae4facbd34f01d67
[ "YAML", "Markdown", "Python", "Text", "Dockerfile" ]
11
YAML
MSDO-ImageHost/Comments
bdd8061c5ea6b9967426e27a0f85793adc170dc3
9b0b844822a49f8f7528a255e98f6033f9c392fc
refs/heads/master
<repo_name>iamasbcx/myHips<file_sep>/drv/FQDrv.h /*++ Copyright (c) 1999-2002 Microsoft Corporation Module Name: scrubber.h Abstract: Header file which contains the structures, type definitions, constants, global variables and function prototypes that are only visible within the kernel. Environment: Kernel mode --*/ #ifndef __FQDRV_H__ #define __FQDRV_H__ /////////////////////////////////////////////////////////////////////////// // // Global variables // /////////////////////////////////////////////////////////////////////////// #define MAX_PATH 256 struct Data { //应用层发来的 路径+操作命令 结构体 ULONG command; WCHAR filename[MAX_PATH]; }; typedef struct Data Data; typedef enum _IOMONITOR_COMMAND { //操作命令 DEFAULT_PATH, ADD_PATH, DELETE_PATH, CLOSE_PATH, OPEN_PATH, PAUSE_REGMON, RESTART_REGMON, DEFAULT_PROCESS, ADD_PROCESS, DELETE_PROCESS, PAUSE_PROCESS, RESTART_PROCESS, DEFAULT_MODULE, ADD_MODULE, DELETE_MODULE, PAUSE_MODULE, RESTART_MODULE, DELETE_FILE, ADD_NETREJECT, DELETE_NETREJECT, PAUSE_NETMON, RESTART_NETMON, } IOMonitorCommand; typedef enum _result { //操作命令 ADD_SUCCESS, ADD_PATH_ALREADY_EXISTS, ADD_FAITH, DELETE_SUCCESS, DELETE_PATH_NOT_EXISTS, DELETE_FAITH, PAUSE_FILEMON, RESTART_FILEMON, MPAUSE_REGMON, MRESTART_REGMON, MPAUSE_PROCESS, MRESTART_PROCESS, MPAUSE_MODULE, MRESTART_MODULE, MPAUSE_NETMON, MRESTART_NETMON, } RuleResult; typedef struct filenames { //路径链表结点 UNICODE_STRING filename; struct filenames* pNext; }filenames,*pFilenames; //删除文件相关 //定义LIST_ENTRY typedef struct _FILE_LIST_ENTRY { LIST_ENTRY ENTRY; PWSTR NameBuffer; }FILE_LIST_ENTRY, *PFILE_LIST_ENTRY; //保存文件信息的结构体 //void ModifyPathList(PUNICODE_STRING filename); //之前把添加和删除在一个函数实现的,这个路径存在就默认为删除命令,不存在就默认本次为添加命令(因为懒得解析结构体,只发一个路径),后来感觉还是不合适,就分开了 typedef struct _FQDRV_DATA { // // The object that identifies this driver. // PDRIVER_OBJECT DriverObject; // // The filter handle that results from a call to // FltRegisterFilter. // PFLT_FILTER Filter; // // Listens for incoming connections // PFLT_PORT ServerPort; // // User process that connected to the port // PEPROCESS UserProcess; // // Client port for a connection to user-mode // PFLT_PORT ClientPort; } FQDRV_DATA, *PFQDRV_DATA; extern FQDRV_DATA FQDRVData; typedef struct _FQDRV_STREAM_HANDLE_CONTEXT { BOOLEAN RescanRequired; } FQDRV_STREAM_HANDLE_CONTEXT, *PFQDRV_STREAM_HANDLE_CONTEXT; #pragma warning(push) #pragma warning(disable:4200) // disable warnings for structures with zero length arrays. typedef struct _FQDRV_CREATE_PARAMS { WCHAR String[0]; } FQDRV_CREATE_PARAMS, *PFQDRV_CREATE_PARAMS; #pragma warning(pop) /////////////////////////////////////////////////////////////////////////// // // Prototypes for the startup and unload routines used for // this Filter. // // Implementation in FQDRV.c // /////////////////////////////////////////////////////////////////////////// DRIVER_INITIALIZE DriverEntry; NTSTATUS DriverEntry( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath ); NTSTATUS FQDRVUnload( __in FLT_FILTER_UNLOAD_FLAGS Flags ); NTSTATUS FQDRVQueryTeardown( __in PCFLT_RELATED_OBJECTS FltObjects, __in FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags ); FLT_PREOP_CALLBACK_STATUS FQDRVPreCreate( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ); FLT_POSTOP_CALLBACK_STATUS FQDRVPostCreate( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __in_opt PVOID CompletionContext, __in FLT_POST_OPERATION_FLAGS Flags ); FLT_PREOP_CALLBACK_STATUS FQDRVPreCleanup( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ); FLT_PREOP_CALLBACK_STATUS FQDRVPreWrite( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ); NTSTATUS FQDRVInstanceSetup( __in PCFLT_RELATED_OBJECTS FltObjects, __in FLT_INSTANCE_SETUP_FLAGS Flags, __in DEVICE_TYPE VolumeDeviceType, __in FLT_FILESYSTEM_TYPE VolumeFilesystemType ); FLT_PREOP_CALLBACK_STATUS FQDRVPreSetInforMation( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ); FLT_POSTOP_CALLBACK_STATUS FQDRVPostSetInforMation( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __in_opt PVOID CompletionContext, __in FLT_POST_OPERATION_FLAGS Flags ); NTSTATUS MessageNotifyCallback( IN PVOID PortCookie, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength,//用户可以接受的数据的最大长度. OUT PULONG ReturnOutputBufferLength); ULONG AddPathList(PUNICODE_STRING filename, pFilenames *headFilenames); ULONG DeletePathList(PUNICODE_STRING filename, pFilenames *headFilenames); BOOLEAN searchRule(WCHAR *path, pFilenames *headFilenames); //注册表相关 NTKERNELAPI UCHAR* PsGetProcessImageFileName(PEPROCESS Process);//获取进程的DOS文件路径 LARGE_INTEGER CmHandle; NTSTATUS PtRegisterInit(); NTSTATUS PtRegisterUnInit(); BOOLEAN IsProcessName(char *string, PEPROCESS eprocess); BOOLEAN GetRegistryObjectCompleteName(PUNICODE_STRING pRegistryPath, PUNICODE_STRING pPartialRegistryPath, PVOID pRegistryObject); NTSTATUS RegistryCallback ( IN PVOID CallbackContext, IN PVOID Argument1,//操作类型, IN PVOID Argument2//操作的结构体指针 ); //进程相关 PWCHAR GetProcessNameByProcessId(HANDLE ProcessId); VOID MyCreateProcessNotifyEx( __inout PEPROCESS Process, __in HANDLE ProcessId, __in_opt PPS_CREATE_NOTIFY_INFO CreateInfo ); VOID MyCreateProcessNotifyEx ( __inout PEPROCESS Process, __in HANDLE ProcessId, __in_opt PPS_CREATE_NOTIFY_INFO CreateInfo ); NTSTATUS PtProcessInit(); NTSTATUS PtProcessUnInit(); BOOLEAN searchProcessRule(WCHAR *path, pFilenames *headFilenames); void DenyLoadDriver(PVOID DriverEntry); PVOID GetDriverEntryByImageBase(PVOID ImageBase); VOID LoadImageNotifyRoutine ( __in_opt PUNICODE_STRING FullImageName, __in HANDLE ProcessId, __in PIMAGE_INFO ImageInfo ); NTSTATUS PtModuleInit(); NTSTATUS PtModuleUnInit(); BOOLEAN searchModuleRule(WCHAR *path, pFilenames *headFilenames); //删除文件相关 NTSTATUS myDelFile(const WCHAR* fileName); NTSTATUS myDelFileDir(const WCHAR * directory); //WFP相关 #endif /* __FQDRV_H__ */ <file_sep>/CProcessManager.cpp // CProcessManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "CProcessManager.h" #include "afxdialogex.h" #include "CFileManager.h" extern pFileRule g_ProcessRule; // CProcessManager 对话框 IMPLEMENT_DYNAMIC(CProcessManager, CDialogEx) CProcessManager::CProcessManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_PROCESS_MANAGER, pParent) , m_ProcessRule(_T("")) , m_ruleState(_T("")) { } CProcessManager::~CProcessManager() { } void CProcessManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_ProcessRule); DDX_Text(pDX, IDC_EDIT2, m_ruleState); DDX_Control(pDX, IDC_LIST1, m_listCtrl); } BEGIN_MESSAGE_MAP(CProcessManager, CDialogEx) ON_BN_CLICKED(IDC_BUTTON_ADD, &CProcessManager::OnBnClickedButtonAdd) ON_BN_CLICKED(IDC_BUTTON_DEL, &CProcessManager::OnBnClickedButtonDel) ON_BN_CLICKED(IDC_BUTTON_PAUSE, &CProcessManager::OnBnClickedButtonPause) ON_BN_CLICKED(IDC_BUTTON_RESTART, &CProcessManager::OnBnClickedButtonRestart) END_MESSAGE_MAP() // CProcessManager 消息处理程序 void CProcessManager::OnBnClickedButtonAdd() { // TODO: Add your control notification handler code here // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_ProcessRule.GetBuffer(); AddToDriver(p, ADD_PROCESS); int iLine = 0; int ret = AddPathList(p, &g_ProcessRule); if (ret) { iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, p); } switch (ret) { case 1: m_ruleState = L"添加路径成功"; break; case 2: m_ruleState = L"添加路径失败,已经存在"; break; case 3: default: m_ruleState = L"添加路径失败"; break; } UpdateData(FALSE); writeToProcessMonFile(); } bool writeToProcessMonFile() { FILE *fp; _wfopen_s(&fp, L".\\PROCESSRULE.txt", L"w+"); if (fp == NULL) return FALSE; pFileRule new_filename, current, precurrent; current = precurrent = g_ProcessRule; while (current != NULL) { fputws(current->filePath, fp); if (current->pNext != NULL) { fputwc('\n', fp); } current = current->pNext; } fclose(fp); return true; } void CProcessManager::OnBnClickedButtonDel() { // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_ProcessRule.GetBuffer(); DeleteFromDriver(p, DELETE_PROCESS); int ret = DeletePathList(p, &g_ProcessRule); int iLine = 0; if (ret == 1) { while (m_listCtrl.DeleteItem(0)); pFileRule new_filename, current, precurrent; current = precurrent = g_ProcessRule; while (current != NULL) { int iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, current->filePath); current = current->pNext; } UpdateData(FALSE); } switch (ret) { case 1: m_ruleState = L"删除路径成功"; break; case 2: m_ruleState = L"删除路径失败,不存在"; break; case 3: default: m_ruleState = L"删除路径失败"; break; } UpdateData(FALSE); writeToFile(); } void CProcessManager::OnBnClickedButtonPause() { // TODO: Add your control notification handler code here Data data; void *pData = NULL; data.command = PAUSE_PROCESS; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void CProcessManager::OnBnClickedButtonRestart() { // TODO: Add your control notification handler code here Data data; void *pData = NULL; data.command = RESTART_PROCESS; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } //WCHAR* NopEnter(WCHAR* str) // 此处代码是抄的, 但是比较 好懂. //{ // WCHAR* p; // if ((p = wcschr(str, '\n')) != NULL) // * p = '\0'; // return str; //} BOOL CProcessManager::OnInitDialog() { CDialogEx::OnInitDialog(); m_listCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT); m_listCtrl.InsertColumn(0, _T("进程过滤规则"), LVCFMT_LEFT, 240); FILE *fp; int iLine = 0; _wfopen_s(&fp, L".\\PROCESSRULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { int ret = 0; WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); m_listCtrl.InsertItem(iLine, p1); } fclose(fp); // TODO: Add extra initialization here //addDefaultProcessRule(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } <file_sep>/CArkManager.h #pragma once // CArkManager 对话框 class CArkManager : public CDialogEx { DECLARE_DYNAMIC(CArkManager) public: CArkManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CArkManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_ARK_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() }; <file_sep>/CLogManager.cpp // CLogManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "CLogManager.h" #include "afxdialogex.h" // CLogManager 对话框 IMPLEMENT_DYNAMIC(CLogManager, CDialogEx) CLogManager::CLogManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_LOG_MANAGER, pParent) { } CLogManager::~CLogManager() { } void CLogManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CLogManager, CDialogEx) END_MESSAGE_MAP() // CLogManager 消息处理程序 <file_sep>/drv/commonFun.h #pragma once BOOLEAN IsPatternMatch(const PWCHAR pExpression, const PWCHAR pName, BOOLEAN IgnoreCase); wchar_t *my_wcsrstr(const wchar_t *str, const wchar_t *sub_str); VOID UnicodeToChar(PUNICODE_STRING dst, char *src); VOID WcharToChar(PWCHAR src, PCHAR dst); VOID CharToWchar(PCHAR src, PWCHAR dst); BOOLEAN IsShortNamePath(WCHAR * wszFileName); NTSTATUS MyRtlVolumeDeviceToDosName( IN PUNICODE_STRING DeviceName, OUT PUNICODE_STRING DosName ); BOOLEAN NTAPI GetNTLinkName(IN WCHAR * wszNTName, OUT WCHAR * wszFileName); NTSTATUS QuerySymbolicLink( IN PUNICODE_STRING SymbolicLinkName, OUT PUNICODE_STRING LinkTarget ); BOOLEAN QueryVolumeName(WCHAR ch, WCHAR * name, USHORT size); BOOLEAN NTAPI GetNtDeviceName(IN WCHAR * filename, OUT WCHAR * ntname); VOID ToUpperString(WCHAR* str);<file_sep>/CFileManager.cpp // CFileManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "CFileManager.h" #include "afxdialogex.h" #include <windows.h> #include <stdlib.h> #include <stdio.h> #include <winioctl.h> #include <string.h> #include <crtdbg.h> #include <assert.h> #include <fltUser.h> #include "CFilePopWindows.h" #include "scanuk.h" #include "scanuser.h" #include <dontuse.h> #pragma comment(lib,"fltLib.lib") #ifdef _DEBUG #define new DEBUG_NEW #endif #define SCANNER_DEFAULT_REQUEST_COUNT 5 #define SCANNER_DEFAULT_THREAD_COUNT 2 #define SCANNER_MAX_THREAD_COUNT 64 HANDLE g_port = 0; pFileRule g_fileRule = NULL; pFileRule g_ProcessRule = NULL; pFileRule g_ModuleRule = NULL; pFileRule g_NetRule = NULL; typedef struct _SCANNER_THREAD_CONTEXT { HANDLE Port; HANDLE Completion; } SCANNER_THREAD_CONTEXT, *PSCANNER_THREAD_CONTEXT; DWORD HandData(LPCTSTR tip) { CFilePopWindows m_FilePopWindows; m_FilePopWindows.SetText(tip); m_FilePopWindows.DoModal(); if (m_FilePopWindows.m_allow == TRUE) { return 1; } else { return 0; } } // CFileManager 对话框 IMPLEMENT_DYNAMIC(CFileManager, CDialogEx) CFileManager::CFileManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_FILE_MANAGER, pParent) , m_szPath(_T("")) , m_rule(_T("")) , m_ruleState(_T("")) { } CFileManager::~CFileManager() { } void CFileManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_FILEPATH, m_szPath); DDX_Text(pDX, IDC_EDIT_RULE, m_rule); DDX_Text(pDX, IDC_EDIT1, m_ruleState); DDX_Control(pDX, IDC_LIST_FILEMON, m_listCtrl); } BEGIN_MESSAGE_MAP(CFileManager, CDialogEx) ON_BN_CLICKED(IDC_BUTTON_BROWSE, &CFileManager::OnBnClickedButtonBrowse) ON_WM_DROPFILES() ON_BN_CLICKED(IDC_BUTTON_FILEMON, &CFileManager::OnBnClickedButtonFilemon) ON_BN_CLICKED(IDC_BUTTON_ADD, &CFileManager::OnBnClickedButtonAdd) ON_BN_CLICKED(IDC_BUTTON_DEL, &CFileManager::OnBnClickedButtonDel) ON_BN_CLICKED(IDC_BUTTON_PAUSE, &CFileManager::OnBnClickedButtonPause) ON_BN_CLICKED(IDC_BUTTON_RESTART, &CFileManager::OnBnClickedButtonRestart) ON_BN_CLICKED(IDC_BUTTON_DELFILE, &CFileManager::OnBnClickedButtonDelfile) END_MESSAGE_MAP() // CFileManager 消息处理程序 void CFileManager::OnBnClickedButtonBrowse() { // TODO: 在此添加控件通知处理程序代码 TCHAR szFolderPath[MAX_PATH] = { 0 }; BROWSEINFO sInfo; ::ZeroMemory(&sInfo, sizeof(BROWSEINFO)); sInfo.pidlRoot = 0; sInfo.lpszTitle = _T("请选择处理结果存储路径"); sInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_EDITBOX | BIF_DONTGOBELOWDOMAIN; sInfo.lpfn = NULL; // 显示文件夹选择对话框 LPITEMIDLIST lpidlBrowse = ::SHBrowseForFolder(&sInfo); if (lpidlBrowse != NULL) { // 取得文件夹名 if (::SHGetPathFromIDList(lpidlBrowse, szFolderPath)) { m_szPath = szFolderPath; } } if (lpidlBrowse != NULL) { ::CoTaskMemFree(lpidlBrowse); } UpdateData(FALSE); } void CFileManager::OnDropFiles(HDROP hDropInfo) { // TODO: 在此添加消息处理程序代码和/或调用默认值 CDialogEx::OnDropFiles(hDropInfo); // TODO: Add your message handler code here and/or call default // TODO: Add your message handler code here and/or call default UINT count; TCHAR filePath[MAX_PATH] = { 0 }; count = DragQueryFile(hDropInfo, 0xFFFFFFFF, NULL, 0); if (count == 1) { DragQueryFile(hDropInfo, 0, filePath, sizeof(filePath)); m_szPath = filePath; UpdateData(FALSE); DragFinish(hDropInfo); CDialog::OnDropFiles(hDropInfo); return; } else { //m_vectorFile.clear(); for (UINT i = 0; i < count; i++) { int pathLen = DragQueryFile(hDropInfo, i, filePath, sizeof(filePath)); m_szPath = filePath; //m_vectorFile.push_back(filePath); //break; } UpdateData(FALSE); DragFinish(hDropInfo); } CDialogEx::OnDropFiles(hDropInfo); } //此函数需放到线程中执行 DWORD ScannerWorker( __in PSCANNER_THREAD_CONTEXT Context ) { DWORD dwRet = 0; DWORD outSize = 0; HRESULT hr = 0; ULONG_PTR key = 0; BOOL result = TRUE; //CHAR strPop[MAX_PATH*2] = {0}; WCHAR strOptions[50 * 2] = { 0 };//操作类型字符串 WCHAR LastPath[MAX_PATH * 2] = { 0 }; BOOL LastResult = TRUE; LPOVERLAPPED pOvlp; PSCANNER_NOTIFICATION notification; SCANNER_REPLY_MESSAGE replyMessage; PSCANNER_MESSAGE message; //DWORD dwRet = 0; CString tip = NULL; memset(LastPath, '\0', MAX_PATH * 2); #pragma warning(push) #pragma warning(disable:4127) // conditional expression is constant while (TRUE) { #pragma warning(pop) // // Poll for messages from the filter component to scan. // result = GetQueuedCompletionStatus(Context->Completion, &outSize, &key, &pOvlp, INFINITE); // // Obtain the message: note that the message we sent down via FltGetMessage() may NOT be // the one dequeued off the completion queue: this is solely because there are multiple // threads per single port handle. Any of the FilterGetMessage() issued messages can be // completed in random order - and we will just dequeue a random one. // message = CONTAINING_RECORD(pOvlp, SCANNER_MESSAGE, Ovlp); if (!result) { hr = HRESULT_FROM_WIN32(GetLastError()); break; } //printf( "Received message, size %d\n", pOvlp->InternalHigh ); //tip.Format(L"Received message, size %d\n", pOvlp->InternalHigh ); notification = &message->Notification; if (notification->Operation == 1) { if (wcsncmp(LastPath, notification->TargetPath, wcslen(notification->TargetPath)) == 0) { memset(LastPath, '\0', MAX_PATH * 2); result = LastResult; goto EX; } } memset(strOptions, '\0', 50); switch (notification->Operation) { case 1: wcscpy_s(strOptions, 50, L"创建"); break; case 2: wcscpy_s(strOptions, 50, L"重命名"); break; case 3: wcscpy_s(strOptions, 50, L"删除"); break; case 4: wcscpy_s(strOptions, 50, L"新键注册表"); break; case 5: wcscpy_s(strOptions, 50, L"删除key"); break; case 6: wcscpy_s(strOptions, 50, L"设置键值"); break; case 7: wcscpy_s(strOptions, 50, L"删除键值"); break; case 8: wcscpy_s(strOptions, 50, L"重命名键值"); break; case 9: wcscpy_s(strOptions, 50, L"进程创建"); break; case 10: wcscpy_s(strOptions, 50, L"模块加载"); break; default: wcscpy_s(strOptions, 50, L"爆炸"); break; } //memset(strPop,'\0',MAX_PATH*2); switch (notification->Operation) { case 1: tip.Format(L"进程:%s\r\n操作:%s\r\n目标:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath); break; case 2: tip.Format(L"进程:%s\r\n操作:%s\r\n目标:%s\r\n重名为:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath, notification->RePathName); break; case 3: tip.Format(L"进程:%s\r\n操作:%s\r\n目标:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath); break; case 4: tip.Format(L"注册表路径:%s\r\n操作:%s\r\n目标:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath); break; case 5: tip.Format(L"注册表路径:%s\r\n操作:%s\r\n是否放行?", notification->ProcessPath, strOptions); break; case 6: tip.Format(L"注册表路径:%s\r\n操作:%s\r\n目标:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath); break; case 7: tip.Format(L"注册表路径:%s\r\n操作:%s\r\n目标:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath); break; case 8: tip.Format(L"注册表路径:%s\r\n操作:%s\r\n目标:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath); break; case 9: tip.Format(L"进程监控:%s\r\n操作:%s\r\n目标:%s\r\n是否放行?", notification->ProcessPath, strOptions, notification->TargetPath); break; case 10: tip.Format(L"模块监控:%s\r\n操作:%s\r\n是否放行?", notification->ProcessPath, strOptions); break; default: break; } Sleep(1000); //dwRet = MessageBoxA(NULL,strPop,"监控到攻击行为",MB_YESNO); dwRet = HandData(tip); if (dwRet == 1) result = FALSE; else result = TRUE; LastResult = result; EX: wcsncpy_s(LastPath, MAX_PATH * 2, notification->TargetPath, MAX_PATH * 2); replyMessage.ReplyHeader.Status = 0; replyMessage.ReplyHeader.MessageId = message->MessageHeader.MessageId; replyMessage.Reply.SafeToOpen = !result; printf("Replying message, ResultCode: %d\n", replyMessage.Reply.SafeToOpen); hr = FilterReplyMessage(Context->Port, (PFILTER_REPLY_HEADER)&replyMessage, sizeof(replyMessage)); if (SUCCEEDED(hr)) { printf("Replied message\n"); } else { printf("Scanner: Error replying message. Error = 0x%X\n", hr); break; } memset(&message->Ovlp, 0, sizeof(OVERLAPPED)); hr = FilterGetMessage(Context->Port, &message->MessageHeader, FIELD_OFFSET(SCANNER_MESSAGE, Ovlp), &message->Ovlp); if (hr != HRESULT_FROM_WIN32(ERROR_IO_PENDING)) { break; } } if (!SUCCEEDED(hr)) { if (hr == HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE)) { // // Scanner port disconncted. // printf("Scanner: Port is disconnected, probably due to scanner filter unloading.\n"); } else { printf("Scanner: Unknown error occured. Error = 0x%X\n", hr); } } free(message); return hr; } //此函数需放到线程中执行 int InitFltUser() { DWORD dwDefRequestCount = SCANNER_DEFAULT_REQUEST_COUNT; DWORD dwDefThreadCount = SCANNER_DEFAULT_THREAD_COUNT; DWORD dwMaxThreadCount = SCANNER_MAX_THREAD_COUNT; SCANNER_THREAD_CONTEXT context; PSCANNER_MESSAGE msg; HANDLE threads[SCANNER_MAX_THREAD_COUNT]; CString tip = NULL; DWORD threadId; DWORD i = 0; //连接到端口 HRESULT hr = FilterConnectCommunicationPort(ScannerPortName, 0, NULL, 0, NULL, &g_port); if (IS_ERROR(hr)) { AfxMessageBox(L"hr is null\n"); return 0; } //为这个句柄创建一个Comption HANDLE completion = CreateIoCompletionPort(g_port, NULL, 0, dwDefThreadCount); if (completion == NULL) { tip.Format(L"ERROR: Creating completion port: %d\n", GetLastError()); AfxMessageBox(tip); CloseHandle(g_port); return 0; } //tip.Format(L"Scanner: Port = 0x%p Completion = 0x%p\n", g_port, completion ); //this->SetWindowTextW(tip); context.Port = g_port; context.Completion = completion; //创建规定的线程 for (i = 0; i < dwDefThreadCount; i++) { //创建线程 threads[i] = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ScannerWorker, &context, 0, &threadId); if (threads[i] == NULL) { hr = GetLastError(); tip.Format(L"ERROR: Couldn't create thread: %d\n", hr); //this->SetWindowTextW(tip); goto main_cleanup; } for (DWORD j = 0; j < dwDefRequestCount; j++) { // // Allocate the message. // #pragma prefast(suppress:__WARNING_MEMORY_LEAK, "msg will not be leaked because it is freed in ScannerWorker") msg = (PSCANNER_MESSAGE)malloc(sizeof(SCANNER_MESSAGE)); if (msg == NULL) { hr = ERROR_NOT_ENOUGH_MEMORY; goto main_cleanup; } memset(&msg->Ovlp, 0, sizeof(OVERLAPPED)); // // Request messages from the filter driver. // hr = FilterGetMessage(g_port, &msg->MessageHeader, FIELD_OFFSET(SCANNER_MESSAGE, Ovlp), &msg->Ovlp); if (hr != HRESULT_FROM_WIN32(ERROR_IO_PENDING)) { free(msg); goto main_cleanup; } } } hr = S_OK; WaitForMultipleObjectsEx(i, threads, TRUE, INFINITE, FALSE); //返回线程数组和 数组个数 main_cleanup: tip.Format(L"Scanner: All done. Result = 0x%08x\n", hr); //this->SetWindowTextW(tip); CloseHandle(g_port); CloseHandle(completion); return hr + 1; } void CFileManager::OnBnClickedButtonFilemon() { // TODO: Add your control notification handler code here CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)InitFltUser, NULL, 0, NULL); bool ret=addDefaultRule(); addDefaultProcessRule(); addDefaultModuleRule(); addDefaultNetRejectRule(); //if(!ret){ // MessageBoxW(NULL, L"读取文件失败", MB_OK); // //} } HRESULT SendToDriver(LPVOID lpInBuffer, DWORD dwInBufferSize) { //通讯端口 HRESULT hResult = S_OK; wchar_t OutBuffer[MAX_PATH] = { 0 }; DWORD bytesReturned = 0; Data *data = (pData)lpInBuffer; hResult = FilterSendMessage(g_port, lpInBuffer, dwInBufferSize, OutBuffer, sizeof(OutBuffer), &bytesReturned); if (IS_ERROR(hResult)) { return hResult; } //MessageBoxW(NULL, OutBuffer, L"返回结果", MB_OK); OutputDebugString(L"从内核发来的信息是:"); OutputDebugString(OutBuffer); OutputDebugString(L"\n"); return hResult; } void AddToDriver(WCHAR * filename, IOMonitorCommand cmd) { Data data; Data *pData = NULL; data.command = cmd; wcscpy_s(data.filename, MAX_PATH, filename); pData = &data; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void DeleteFromDriver(WCHAR * filename, IOMonitorCommand cmd) { Data data; void *pData = NULL; data.command = cmd; wcscpy_s(data.filename, MAX_PATH, filename); pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void PauseDriver() { Data data; void *pData = NULL; data.command = CLOSE_PATH; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void RenewDriver() { Data data; void *pData = NULL; data.command = OPEN_PATH; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void CFileManager::OnBnClickedButtonAdd() { // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_rule.GetBuffer(); AddToDriver(p,ADD_PATH); int iLine = 0; int ret=AddPathList(p,&g_fileRule); if (ret) { iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, p); } switch (ret) { case 1: m_ruleState = L"添加路径成功"; break; case 2: m_ruleState = L"添加路径失败,已经存在"; break; case 3: default: m_ruleState = L"添加路径失败"; break; } UpdateData(FALSE); writeToFile(); } void CFileManager::OnBnClickedButtonDel() { // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_rule.GetBuffer(); DeleteFromDriver(p,DELETE_PATH); int ret = DeletePathList(p,&g_fileRule); int iLine = 0; if (ret == 1) { while (m_listCtrl.DeleteItem(0)); pFileRule new_filename, current, precurrent; current = precurrent = g_fileRule; while (current != NULL) { int iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, current->filePath); current = current->pNext; } UpdateData(FALSE); } switch (ret) { case 1: m_ruleState = L"删除路径成功"; break; case 2: m_ruleState = L"删除路径失败,不存在"; break; case 3: default: m_ruleState = L"删除路径失败"; break; } UpdateData(FALSE); writeToFile(); } void CFileManager::OnBnClickedButtonPause() { PauseDriver(); m_ruleState = L"暂停监控"; UpdateData(FALSE); // TODO: Add your control notification handler code here } void CFileManager::OnBnClickedButtonRestart() { // TODO: Add your control notification handler code here RenewDriver(); m_ruleState = L"继续监控"; UpdateData(FALSE); } WCHAR* NopEnter(WCHAR* str) // 此处代码是抄的, 但是比较 好懂. { WCHAR* p; if ((p =wcschr(str, '\n')) != NULL) * p = '\0'; return str; } bool addDefaultRule() { FILE *fp; _wfopen_s(&fp,L".\\FILERULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { int ret = 0; WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); AddToDriver(p1,ADD_PATH); ret=AddPathList(p1,&g_fileRule); } fclose(fp); return true; } bool addDefaultProcessRule() { FILE *fp; _wfopen_s(&fp, L".\\PROCESSRULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); AddToDriver(p1, ADD_PROCESS); AddPathList(p1, &g_ProcessRule); } fclose(fp); return true; } bool addDefaultModuleRule() { FILE *fp; _wfopen_s(&fp, L".\\MODULERULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); AddToDriver(p1, ADD_MODULE); AddPathList(p1, &g_ModuleRule); } fclose(fp); return true; } bool addDefaultNetRejectRule() { FILE *fp; _wfopen_s(&fp, L".\\NETRULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); AddToDriver(p1, ADD_NETREJECT); AddPathList(p1, &g_NetRule); } fclose(fp); return true; } int AddPathList(WCHAR* filename ,pFileRule* headFileRule) { pFileRule new_filename, current, precurrent; new_filename = (pFileRule)malloc(sizeof(fileRule)); ZeroMemory(new_filename, sizeof(fileRule)); memcpy_s(new_filename->filePath, MAX_PATH, filename, MAX_PATH); //MessageBoxW(NULL, new_filename->filePath, new_filename->filePath, MB_OK); new_filename->pNext = NULL; __try { new_filename->pNext = NULL; if (NULL == *headFileRule) //头是空的,路径添加到头 { *headFileRule = new_filename; return 1; } current = *headFileRule; while (current != NULL) { if (!wcscmp(current->filePath,new_filename->filePath))//链表中含有这个路径,返回 { free(new_filename); new_filename = NULL; return 2; } precurrent = current; current = current->pNext; } //链表中没有这个路径,添加 current = *headFileRule; while (current->pNext != NULL) { current = current->pNext; } current->pNext = new_filename; return 1; } __except (EXCEPTION_EXECUTE_HANDLER) { free(new_filename); new_filename = NULL; return 3; } } int DeletePathList(WCHAR* filename, pFileRule* headFileRule) { pFileRule new_filename, current, precurrent; current = precurrent = *headFileRule; while (current != NULL) { __try { if (!wcscmp(current->filePath, filename)) { //判断一下是否是头,如果是头,就让头指向第二个,删掉第一个 if (current == *headFileRule) { *headFileRule = current->pNext; free(current); current = NULL; return 1; } //如果不是头,删掉当前的 precurrent->pNext = current->pNext; current->pNext = NULL; free(current); current = NULL; return 1; } precurrent = current; current = current->pNext; } __except (EXCEPTION_EXECUTE_HANDLER) { return 3; } } return 2; } bool writeToFile() { FILE *fp; _wfopen_s(&fp, L".\\FILERULE.txt", L"w+"); if (fp == NULL) return FALSE; pFileRule new_filename, current, precurrent; current = precurrent = g_fileRule; while (current != NULL) { fputws(current->filePath, fp); if (current->pNext != NULL) { fputwc('\n', fp); } current = current->pNext; } fclose(fp); return true; } //注册表 void PauseRegMon() { Data data; void *pData = NULL; data.command = PAUSE_REGMON; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void RenewRegMon() { Data data; void *pData = NULL; data.command = RESTART_REGMON; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } BOOL CFileManager::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: Add extra initialization here ChangeWindowMessageFilter(WM_DROPFILES, MSGFLT_ADD); ChangeWindowMessageFilter(0x0049, MSGFLT_ADD); // 0x0049 == WM_COPYGLOBALDATA m_listCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT); m_listCtrl.InsertColumn(0, _T("文件监控规则"), LVCFMT_LEFT, 240); FILE *fp; int iLine = 0; _wfopen_s(&fp, L".\\FILERULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { int ret = 0; WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); m_listCtrl.InsertItem(iLine, p1); } fclose(fp); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CFileManager::OnBnClickedButtonDelfile() { // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_szPath.GetBuffer(); DeleteFromDriver(p, DELETE_FILE); } <file_sep>/resource.h //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by FQHIPS.rc // #define IDR_MENU_TRAY 4 #define IDM_ABOUTBOX 0x0010 #define IDD_ABOUTBOX 100 #define IDS_ABOUTBOX 101 #define IDD_FQHIPS_DIALOG 102 #define IDR_MAINFRAME 128 #define IDD_DIALOG_FILE_MANAGER 130 #define IDD_DIALOG_REGEDIT_MANAGER 132 #define IDD_DIALOG_HIPS_MANAGER 134 #define IDD_DIALOG_PROCESS_MANAGER 136 #define IDD_DIALOG_FIREWALL_MANAGER 138 #define IDD_DIALOG_LOG_MANAGER 140 #define IDD_DIALOG_ARK_MANAGER 142 #define IDD_DIALOG_OTHER_MANAGER 144 #define IDI_FQICON 148 #define IDD_DIALOG_FILEPOPWINDOWS 149 #define IDC_TAB_MJFUNCTON 1000 #define IDC_EDIT_FILEPATH 1004 #define IDC_BUTTON_BROWSE 1005 #define IDC_EDIT_UNC 1006 #define IDC_BUTTON_U2L 1007 #define IDC_EDIT2 1008 #define IDC_EDIT_LOCAL 1008 #define IDC_BUTTON_FILEMON 1009 #define IDC_EDIT1 1010 #define IDC_EDIT_RULE 1011 #define IDC_BUTTON_ADD 1012 #define IDC_BUTTON_DEL 1013 #define IDC_BUTTON_PAUSE 1014 #define IDC_BUTTON_RESTART 1015 #define IDC_BUTTON_STARTDRV 1019 #define IDC_BUTTON_PAUSEDRV 1022 #define IDC_BUTTON_INSTALLDRV 1023 #define IDC_BUTTON_UNINSTALLDRV 1024 #define IDC_STATIC_TIMER 1025 #define IDC_BUTTON_STARTREG 1026 #define IDC_BUTTON_STOPREG 1027 #define IDC_BUTTON_PAUSEMOUDLE 1033 #define IDC_BUTTON_RESTARTMOUDLE 1034 #define IDC_BUTTON_ADDRULE 1036 #define IDC_BUTTON_DELRULE 1037 #define IDC_BUTTON_DELFILE 1038 #define IDC_LIST_FILEMON 1039 #define IDC_LIST1 1040 #define ID_32771 32771 #define ID_TRAY_REST 32772 #define ID_TRAY_RESTORE 32773 #define ID_32774 32774 #define ID_TRAY_EXIT 32775 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 151 #define _APS_NEXT_COMMAND_VALUE 32776 #define _APS_NEXT_CONTROL_VALUE 1045 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif <file_sep>/CLogManager.h #pragma once // CLogManager 对话框 class CLogManager : public CDialogEx { DECLARE_DYNAMIC(CLogManager) public: CLogManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CLogManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_LOG_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() }; <file_sep>/CArkManager.cpp // CArkManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "CArkManager.h" #include "afxdialogex.h" // CArkManager 对话框 IMPLEMENT_DYNAMIC(CArkManager, CDialogEx) CArkManager::CArkManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_ARK_MANAGER, pParent) { } CArkManager::~CArkManager() { } void CArkManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CArkManager, CDialogEx) END_MESSAGE_MAP() // CArkManager 消息处理程序 <file_sep>/FQHIPSDlg.h  // FQHIPSDlg.h: 头文件 // #pragma once #include "CArkManager.h" #include "CFileManager.h" #include "CFirewallManager.h" #include "CHipsManager.h" #include "CLogManager.h" #include "COtherManager.h" #include "CProcessManager.h" #include "CRegeditManager.h" #define MAX_DLG_PAGE 8//子对话框数量 // CFQHIPSDlg 对话框 class CFQHIPSDlg : public CDialogEx { // 构造 public: CFQHIPSDlg(CWnd* pParent = nullptr); // 标准构造函数 // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_FQHIPS_DIALOG }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: HICON m_hIcon; // 生成的消息映射函数 virtual BOOL OnInitDialog(); afx_msg void OnSysCommand(UINT nID, LPARAM lParam); afx_msg void OnPaint(); afx_msg HCURSOR OnQueryDragIcon(); DECLARE_MESSAGE_MAP() public: afx_msg void OnTcnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult); CTabCtrl m_tabCtrl; //定义其他对话框成员对象,做对话框组 CLogManager m_LogManager; CHipsManager m_HipsManager; CFileManager m_FileManager; CRegeditManager m_RegeditManager; CProcessManager m_ProcessManager; CFirewallManager m_FirewallManager; CArkManager m_ArkManager; COtherManager m_OtherManager; CDialog *m_pDialog[MAX_DLG_PAGE]; int m_CurSelTab; afx_msg void OnClose(); //添加托盘左右键回调函数 LRESULT OnTrayNotification(WPARAM wParam, LPARAM lParam); afx_msg void OnTrayRestore(); afx_msg void OnTrayExit(); afx_msg void OnBnClickedButtonStartdrv(); afx_msg void OnBnClickedButtonPausedrv(); afx_msg void OnBnClickedButtonInstalldrv(); afx_msg void OnBnClickedButtonUninstalldrv(); CString m_drvState; }; BOOL InstallDriver(const WCHAR* lpszDriverName, const WCHAR* lpszDriverPath, const WCHAR* lpszAltitude); BOOL StartDriver(const WCHAR* lpszDriverName); BOOL StopDriver(const WCHAR* lpszDriverName); BOOL DeleteDriver(const WCHAR* lpszDriverName); <file_sep>/CRegeditManager.h #pragma once // CRegeditManager 对话框 class CRegeditManager : public CDialogEx { DECLARE_DYNAMIC(CRegeditManager) public: CRegeditManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CRegeditManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_REGEDIT_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CString m_szUNC; CString m_szLocal; afx_msg void OnBnClickedButtonU2l(); afx_msg void OnBnClickedButtonStartreg(); afx_msg void OnBnClickedButtonStopreg(); }; <file_sep>/CFilePopWindows.cpp // CFilePopWindows.cpp : implementation file // #include "stdafx.h" #include "FQHIPS.h" #include "CFilePopWindows.h" #include "afxdialogex.h" #define TIMER_ELAPSE_ID 100 // CFilePopWindows dialog IMPLEMENT_DYNAMIC(CFilePopWindows, CDialogEx) CFilePopWindows::CFilePopWindows(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_FILEPOPWINDOWS, pParent) , m_information(_T("")) , m_szTime(_T("")) , m_lefttime(16) { } CFilePopWindows::~CFilePopWindows() { } void CFilePopWindows::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_information); DDX_Text(pDX, IDC_STATIC_TIMER, m_szTime); } void CFilePopWindows::SetText(LPCTSTR str) { m_information = str; } BEGIN_MESSAGE_MAP(CFilePopWindows, CDialogEx) ON_BN_CLICKED(IDOK, &CFilePopWindows::OnBnClickedOk) ON_BN_CLICKED(IDCANCEL, &CFilePopWindows::OnBnClickedCancel) ON_WM_TIMER() END_MESSAGE_MAP() // CFilePopWindows message handlers void CFilePopWindows::OnBnClickedOk() { // TODO: Add your control notification handler code here m_allow = TRUE; CDialogEx::OnOK(); } void CFilePopWindows::OnBnClickedCancel() { // TODO: Add your control notification handler code here m_allow = FALSE; CDialogEx::OnCancel(); } void CFilePopWindows::OnTimer(UINT_PTR nIDEvent) { // TODO: Add your message handler code here and/or call default // TODO: Add your message handler code here and/or call default switch (nIDEvent) { case TIMER_ELAPSE_ID: UpdateData(TRUE); m_szTime.Format(_T("»ΉΚ£: %2d Γλ"), --m_lefttime); UpdateData(FALSE); if (m_lefttime == 0) { KillTimer(nIDEvent); UpdateData(TRUE); CDialog::OnOK(); } break; default: break; } CDialog::OnTimer(nIDEvent); //CDialogEx::OnTimer(nIDEvent); } BOOL CFilePopWindows::OnInitDialog() { CDialogEx::OnInitDialog(); SetTimer(TIMER_ELAPSE_ID, 1 * 1000, NULL); // TODO: Add extra initialization here m_szTime = _T("»ΉΚ£: 16 Γλ"); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } <file_sep>/COtherManager.cpp // COtherManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "COtherManager.h" #include "afxdialogex.h" // COtherManager 对话框 IMPLEMENT_DYNAMIC(COtherManager, CDialogEx) COtherManager::COtherManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_OTHER_MANAGER, pParent) { } COtherManager::~COtherManager() { } void COtherManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(COtherManager, CDialogEx) END_MESSAGE_MAP() // COtherManager 消息处理程序 <file_sep>/CHipsManager.h #pragma once // CHipsManager 对话框 class CHipsManager : public CDialogEx { DECLARE_DYNAMIC(CHipsManager) public: CHipsManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CHipsManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_HIPS_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CString m_ModuleRule; CString m_ruleState; afx_msg void OnBnClickedButtonAddrule(); afx_msg void OnBnClickedButtonDelrule(); afx_msg void OnBnClickedButtonPausemoudle(); afx_msg void OnBnClickedButtonRestartmoudle(); CListCtrl m_listCtrl; virtual BOOL OnInitDialog(); }; bool writeToMoudleMonFile();<file_sep>/CFirewallManager.cpp // CFirewallManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "CFirewallManager.h" #include "afxdialogex.h" #include "CFileManager.h" // CFirewallManager 对话框 extern pFileRule g_NetRule; IMPLEMENT_DYNAMIC(CFirewallManager, CDialogEx) CFirewallManager::CFirewallManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_FIREWALL_MANAGER, pParent) , m_ruleState(_T("")) , m_NetRule(_T("")) { } CFirewallManager::~CFirewallManager() { } void CFirewallManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT2, m_ruleState); DDX_Text(pDX, IDC_EDIT1, m_NetRule); DDX_Control(pDX, IDC_LIST1, m_listCtrl); } BEGIN_MESSAGE_MAP(CFirewallManager, CDialogEx) ON_BN_CLICKED(IDC_BUTTON_ADD, &CFirewallManager::OnBnClickedButtonAdd) ON_BN_CLICKED(IDC_BUTTON_DEL, &CFirewallManager::OnBnClickedButtonDel) ON_BN_CLICKED(IDC_BUTTON_PAUSE, &CFirewallManager::OnBnClickedButtonPause) ON_BN_CLICKED(IDC_BUTTON_RESTART, &CFirewallManager::OnBnClickedButtonRestart) END_MESSAGE_MAP() // CFirewallManager 消息处理程序 void CFirewallManager::OnBnClickedButtonAdd() { // TODO: Add your control notification handler code here // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_NetRule.GetBuffer(); AddToDriver(p, ADD_NETREJECT); int ret = AddPathList(p, &g_NetRule); int iLine = 0; if (ret) { iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, p); } switch (ret) { case 1: m_ruleState = L"添加关闭网络进程成功"; break; case 2: m_ruleState = L"添加关闭网络进程失败,已经存在"; break; case 3: default: m_ruleState = L"添加关闭网络进程失败"; break; } UpdateData(FALSE); writeToNetMonFile(); } void CFirewallManager::OnBnClickedButtonDel() { // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_NetRule.GetBuffer(); DeleteFromDriver(p, DELETE_NETREJECT); int ret = DeletePathList(p, &g_NetRule); int iLine = 0; if (ret == 1) { while (m_listCtrl.DeleteItem(0)); pFileRule new_filename, current, precurrent; current = precurrent = g_NetRule; while (current != NULL) { int iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, current->filePath); current = current->pNext; } UpdateData(FALSE); } switch (ret) { case 1: m_ruleState = L"删除关闭网络进程成功"; break; case 2: m_ruleState = L"删除关闭网络进程失败,不存在"; break; case 3: default: m_ruleState = L"删除关闭网络进程失败"; break; } UpdateData(FALSE); writeToNetMonFile(); } BOOL CFirewallManager::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: Add extra initialization here m_listCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT); m_listCtrl.InsertColumn(0, _T("禁止访问网络的进程"), LVCFMT_LEFT, 240); FILE *fp; int iLine = 0; _wfopen_s(&fp, L".\\NETRULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { int ret = 0; WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); m_listCtrl.InsertItem(iLine, p1); } fclose(fp); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } bool writeToNetMonFile() { FILE *fp; _wfopen_s(&fp, L".\\NETRULE.txt", L"w+"); if (fp == NULL) return FALSE; pFileRule new_filename, current, precurrent; current = precurrent = g_NetRule; while (current != NULL) { fputws(current->filePath, fp); if (current->pNext != NULL) { fputwc('\n', fp); } current = current->pNext; } fclose(fp); return true; } void CFirewallManager::OnBnClickedButtonPause() { // TODO: Add your control notification handler code here Data data; void *pData = NULL; data.command = PAUSE_NETMON; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void CFirewallManager::OnBnClickedButtonRestart() { // TODO: Add your control notification handler code here Data data; void *pData = NULL; data.command = RESTART_NETMON; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } <file_sep>/drv/commonStruct.h #pragma once #ifndef __COMMONSTRUCT_H__ #define __COMMONSTRUCT_H__ // // Name of port used to communicate // const PWSTR FQDRVPortName = L"\\FQDRVPort"; #define FQDRV_READ_BUFFER_SIZE 1024 #define MAX_PATH 256 #define MAXPATHLEN 512 typedef struct _FQDRV_NOTIFICATION { ULONG Operation; WCHAR TargetPath[MAX_PATH]; WCHAR ProcessPath[MAX_PATH]; WCHAR RePathName[MAX_PATH]; } FQDRV_NOTIFICATION, *PFQDRV_NOTIFICATION; typedef struct _FQDRV_REPLY { BOOLEAN SafeToOpen; } FQDRV_REPLY, *PFQDRV_REPLY; #endif // __COMMONSTRUCT_H__<file_sep>/CFileManager.h #pragma once // CFileManager 对话框 class CFileManager : public CDialogEx { DECLARE_DYNAMIC(CFileManager) public: CFileManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CFileManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_FILE_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButtonBrowse(); CString m_szPath; afx_msg void OnDropFiles(HDROP hDropInfo); afx_msg void OnBnClickedButtonFilemon(); CString m_rule; afx_msg void OnBnClickedButtonAdd(); afx_msg void OnBnClickedButtonDel(); afx_msg void OnBnClickedButtonPause(); afx_msg void OnBnClickedButtonRestart(); CString m_ruleState; virtual BOOL OnInitDialog(); afx_msg void OnBnClickedButtonDelfile(); CListCtrl m_listCtrl; }; const PWSTR FQDRVPortName = L"\\FQDRVPort"; #define FQDRV_READ_BUFFER_SIZE 1024 //#define MAX_PATH 256 //文件目录链表 struct filenames { wchar_t filename[MAX_PATH]; struct filenames* pNext; }; typedef struct fileRule { WCHAR filePath[MAX_PATH]; struct fileRule* pNext; }fileRule,*pFileRule; typedef struct filenames filenames; //发送数据结构体 typedef struct Data { unsigned long command; wchar_t filename[MAX_PATH]; }Data,*pData; //命令定义 typedef enum _IOMONITOR_COMMAND { DEFAULT_PATH, ADD_PATH, DELETE_PATH, CLOSE_PATH, OPEN_PATH, PAUSE_REGMON, RESTART_REGMON, DEFAULT_PROCESS, ADD_PROCESS, DELETE_PROCESS, PAUSE_PROCESS, RESTART_PROCESS, DEFAULT_MODULE, ADD_MODULE, DELETE_MODULE, PAUSE_MODULE, RESTART_MODULE, DELETE_FILE, ADD_NETREJECT, DELETE_NETREJECT, PAUSE_NETMON, RESTART_NETMON, } IOMonitorCommand; //显示路径操作 //void ModifyPathList(wchar_t * filename); //读取文件内容 //void ReadPath(); WCHAR* NopEnter(WCHAR* str); // 此处代码是抄的, 但是比较 好懂. //与驱动通讯 HRESULT SendToDriver(LPVOID lpInBuffer, DWORD dwInBufferSize); //控制驱动路径 void AddToDriver(WCHAR * filename, IOMonitorCommand cmd); void DeleteFromDriver(WCHAR * filename,IOMonitorCommand cmd); void PauseDriver(); void RenewDriver(); //引用层操作规则函数 bool addDefaultRule(); int AddPathList(WCHAR* filename, pFileRule* headFileRule); int DeletePathList(WCHAR* filename, pFileRule* headFileRule); bool writeToFile(); //注册表通信函数 void PauseRegMon(); void RenewRegMon(); extern pFileRule g_fileRule; extern pFileRule g_ProcessRule; extern pFileRule g_ModuleRule; extern pFileRule g_NetRule; bool addDefaultProcessRule(); bool addDefaultModuleRule(); bool addDefaultNetRejectRule();<file_sep>/FQHIPSDlg.cpp  // FQHIPSDlg.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "FQHIPSDlg.h" #include "afxdialogex.h" #include <windows.h> #include <winioctl.h> #include <winsvc.h> #include <stdio.h> #include <conio.h> #define DRIVER_NAME L"FQDrv" #define DRIVER_PATH L".\\FQDrv.sys" #define DRIVER_ALTITUDE L"265000" //有同学反馈,他这里没有使用UNICODE编码,导致安装不生效 #ifdef _DEBUG #define new DEBUG_NEW #endif #define WM_ICON_NOTIFY WM_USER+100//托盘右下角消息 // 用于应用程序“关于”菜单项的 CAboutDlg 对话框 class CAboutDlg : public CDialogEx { public: CAboutDlg(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_ABOUTBOX }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 // 实现 protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CFQHIPSDlg 对话框 CFQHIPSDlg::CFQHIPSDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_FQHIPS_DIALOG, pParent) , m_drvState(_T("")) { m_hIcon = AfxGetApp()->LoadIcon(IDI_FQICON); } void CFQHIPSDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_TAB_MJFUNCTON, m_tabCtrl); DDX_Text(pDX, IDC_EDIT1, m_drvState); } BEGIN_MESSAGE_MAP(CFQHIPSDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_NOTIFY(TCN_SELCHANGE, IDC_TAB_MJFUNCTON, &CFQHIPSDlg::OnTcnSelchangeTab1) ON_WM_CLOSE() ON_MESSAGE(WM_ICON_NOTIFY, OnTrayNotification) ON_COMMAND(ID_TRAY_RESTORE, &CFQHIPSDlg::OnTrayRestore) ON_COMMAND(ID_TRAY_EXIT, &CFQHIPSDlg::OnTrayExit) ON_BN_CLICKED(IDC_BUTTON_STARTDRV, &CFQHIPSDlg::OnBnClickedButtonStartdrv) ON_BN_CLICKED(IDC_BUTTON_PAUSEDRV, &CFQHIPSDlg::OnBnClickedButtonPausedrv) ON_BN_CLICKED(IDC_BUTTON_INSTALLDRV, &CFQHIPSDlg::OnBnClickedButtonInstalldrv) ON_BN_CLICKED(IDC_BUTTON_UNINSTALLDRV, &CFQHIPSDlg::OnBnClickedButtonUninstalldrv) END_MESSAGE_MAP() // CFQHIPSDlg 消息处理程序 BOOL CFQHIPSDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 //为tabControl添加标签 m_tabCtrl.InsertItem(0, _T("程序引导")); m_tabCtrl.InsertItem(1, _T("模块监控")); m_tabCtrl.InsertItem(2, _T("文件管理")); m_tabCtrl.InsertItem(3, _T("注册表管理")); m_tabCtrl.InsertItem(4, _T("进程管理")); m_tabCtrl.InsertItem(5, _T("防火墙")); m_tabCtrl.InsertItem(6, _T("Ark功能(未完成)")); m_tabCtrl.InsertItem(7, _T("其他功能(关闭)")); m_tabCtrl.SetPadding(10); m_tabCtrl.SetMinTabWidth(50); m_tabCtrl.SetItemSize(CSize(50, 25)); //创建子对话框 m_LogManager.Create(IDD_DIALOG_LOG_MANAGER, &m_tabCtrl); m_HipsManager.Create(IDD_DIALOG_HIPS_MANAGER, &m_tabCtrl); m_FileManager.Create(IDD_DIALOG_FILE_MANAGER, &m_tabCtrl); m_RegeditManager.Create(IDD_DIALOG_REGEDIT_MANAGER, &m_tabCtrl); m_ProcessManager.Create(IDD_DIALOG_PROCESS_MANAGER, &m_tabCtrl); m_FirewallManager.Create(IDD_DIALOG_FIREWALL_MANAGER, &m_tabCtrl); m_ArkManager.Create(IDD_DIALOG_ARK_MANAGER, &m_tabCtrl); m_OtherManager.Create(IDD_DIALOG_OTHER_MANAGER, &m_tabCtrl); //设定在Tab内显示的范围,将子对话框拖动到主对话框内 CRect rc; m_tabCtrl.GetClientRect(rc); rc.top += 25; // rc.bottom -= 8; // rc.left += 8; // rc.right -= 8; m_LogManager.MoveWindow(&rc); m_HipsManager.MoveWindow(&rc); m_FileManager.MoveWindow(&rc); m_RegeditManager.MoveWindow(&rc); m_ProcessManager.MoveWindow(&rc); m_FirewallManager.MoveWindow(&rc); m_ArkManager.MoveWindow(&rc); m_OtherManager.MoveWindow(&rc); //把子对话框指针保存在主对话框的数组中 m_pDialog[0] = &m_LogManager; m_pDialog[1] = &m_HipsManager; m_pDialog[2] = &m_FileManager; m_pDialog[3] = &m_RegeditManager; m_pDialog[4] = &m_ProcessManager; m_pDialog[5] = &m_FirewallManager; m_pDialog[6] = &m_ArkManager; m_pDialog[7] = &m_OtherManager; //显示初始界面 m_pDialog[0]->ShowWindow(SW_SHOW); m_pDialog[1]->ShowWindow(SW_HIDE); m_pDialog[2]->ShowWindow(SW_HIDE); m_pDialog[3]->ShowWindow(SW_HIDE); m_pDialog[4]->ShowWindow(SW_HIDE); m_pDialog[5]->ShowWindow(SW_HIDE); m_pDialog[6]->ShowWindow(SW_HIDE); m_pDialog[7]->ShowWindow(SW_HIDE); //保存当前选择 m_CurSelTab = 0; //增加程序托盘功能 NOTIFYICONDATA m_tnid; m_tnid.cbSize = sizeof(NOTIFYICONDATA);//设置结构大小// m_tnid.hWnd = this->m_hWnd;//设置图标对应的窗口 m_tnid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP;//图标属性 m_tnid.uCallbackMessage = WM_ICON_NOTIFY;//应用程序定义的回调消息ID CString szToolTip; szToolTip = _T("非酋主防"); _tcscpy_s(m_tnid.szTip, szToolTip);//帮助信息 m_tnid.uID = IDR_MAINFRAME;//应用程序图标 m_tnid.hIcon = m_hIcon;//图标句柄 PNOTIFYICONDATA m_ptnid = &m_tnid; ::Shell_NotifyIcon(NIM_ADD, m_ptnid);//增加图标到系统盘 bool ret1=InstallDriver(DRIVER_NAME, DRIVER_PATH, DRIVER_ALTITUDE); if (!ret1) { MessageBoxW(NULL, L"安装失败,请检查文件是否完整", MB_OK); } bool ret = InstallDriver(DRIVER_NAME, DRIVER_PATH, DRIVER_ALTITUDE); if (!ret) { m_drvState = L"安装驱动失败"; } else { m_drvState = L"安装驱动成功"; } UpdateData(FALSE); return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CFQHIPSDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } //如果最小化,隐藏到托盘 if (nID == SC_MINIMIZE) { ShowWindow(FALSE); //隐藏窗口 } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CFQHIPSDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CFQHIPSDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CFQHIPSDlg::OnTcnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: 在此添加控件通知处理程序代码 m_pDialog[m_CurSelTab]->ShowWindow(SW_HIDE); m_CurSelTab = m_tabCtrl.GetCurSel(); if (m_pDialog[m_CurSelTab]) { m_pDialog[m_CurSelTab]->ShowWindow(SW_SHOW); } *pResult = 0; } void CFQHIPSDlg::OnClose() { // TODO: 在此添加消息处理程序代码和/或调用默认值 NOTIFYICONDATA nd = { 0 }; //实现关闭程序托盘也消失的功能 nd.cbSize = sizeof(NOTIFYICONDATA); nd.hWnd = m_hWnd; nd.uID = IDR_MAINFRAME; nd.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP; nd.uCallbackMessage = WM_ICON_NOTIFY; nd.hIcon = m_hIcon; Shell_NotifyIcon(NIM_DELETE, &nd); CDialogEx::OnClose(); } //托盘左右键函数 LRESULT CFQHIPSDlg::OnTrayNotification(WPARAM wParam, LPARAM lParam) { switch (lParam) { case WM_LBUTTONDOWN: { AfxGetApp()->m_pMainWnd->ShowWindow(SW_SHOWNORMAL); SetForegroundWindow(); break; } case WM_RBUTTONUP: { POINT point; HMENU hMenu, hSubMenu; GetCursorPos(&point); //鼠标位置 hMenu = LoadMenu(NULL, MAKEINTRESOURCE(IDR_MENU_TRAY)); // 加载菜单 hSubMenu = GetSubMenu(hMenu, 0);//得到子菜单(因为弹出式菜单是子菜单) SetForegroundWindow(); // 激活窗口并置前 TrackPopupMenu(hSubMenu, 0, point.x, point.y, 0, m_hWnd, NULL); } } return 1; } void CFQHIPSDlg::OnTrayRestore() { // TODO: 在此添加命令处理程序代码 AfxGetApp()->m_pMainWnd->ShowWindow(SW_SHOWNORMAL); SetForegroundWindow(); } void CFQHIPSDlg::OnTrayExit() { OnClose(); // TODO: 在此添加命令处理程序代码 } BOOL InstallDriver(const WCHAR* lpszDriverName, const WCHAR* lpszDriverPath, const WCHAR* lpszAltitude) { WCHAR szTempStr[MAX_PATH]; HKEY hKey; DWORD dwData; WCHAR szDriverImagePath[MAX_PATH]; if (NULL == lpszDriverName || NULL == lpszDriverPath) { return FALSE; } //得到完整的驱动路径 GetFullPathName(lpszDriverPath, MAX_PATH, szDriverImagePath, NULL); SC_HANDLE hServiceMgr = NULL;// SCM管理器的句柄 SC_HANDLE hService = NULL;// NT驱动程序的服务句柄 //打开服务控制管理器 hServiceMgr = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (hServiceMgr == NULL) { // OpenSCManager失败 CloseServiceHandle(hServiceMgr); return FALSE; } // OpenSCManager成功 //创建驱动所对应的服务 hService = CreateService(hServiceMgr, lpszDriverName, // 驱动程序的在注册表中的名字 lpszDriverName, // 注册表驱动程序的DisplayName 值 SERVICE_ALL_ACCESS, // 加载驱动程序的访问权限 SERVICE_FILE_SYSTEM_DRIVER, // 表示加载的服务是文件系统驱动程序 SERVICE_DEMAND_START, // 注册表驱动程序的Start 值 SERVICE_ERROR_NORMAL, // 注册表驱动程序的ErrorControl 值 szDriverImagePath, // 注册表驱动程序的ImagePath 值 L"FQDrv Content Montior",// 注册表驱动程序的Group 值 NULL, L"FltMgr", // 注册表驱动程序的DependOnService 值 NULL, NULL); if (hService == NULL) { if (GetLastError() == ERROR_SERVICE_EXISTS) { //服务创建失败,是由于服务已经创立过 CloseServiceHandle(hService); // 服务句柄 CloseServiceHandle(hServiceMgr); // SCM句柄 return TRUE; } else { CloseServiceHandle(hService); // 服务句柄 CloseServiceHandle(hServiceMgr); // SCM句柄 return FALSE; } } CloseServiceHandle(hService); // 服务句柄 CloseServiceHandle(hServiceMgr); // SCM句柄 //------------------------------------------------------------------------------------------------------- // SYSTEM\\CurrentControlSet\\Services\\DriverName\\Instances子健下的键值项 //------------------------------------------------------------------------------------------------------- wcscpy_s(szTempStr,L"SYSTEM\\CurrentControlSet\\Services\\"); wcscat_s(szTempStr, lpszDriverName); wcscat_s(szTempStr, L"\\Instances"); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, L"", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } // 注册表驱动程序的DefaultInstance 值 wsprintf(szTempStr, L"\%ls Instance", lpszDriverName); //wcscpy_s(szTempStr, lpszDriverName); //wcscat_s(szTempStr, L" Instance"); if (RegSetValueEx(hKey, L"DefaultInstance", 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)(wcslen(szTempStr)*sizeof(WCHAR))) != ERROR_SUCCESS) { return FALSE; } RegFlushKey(hKey);//刷新注册表 RegCloseKey(hKey); //------------------------------------------------------------------------------------------------------- // SYSTEM\\CurrentControlSet\\Services\\DriverName\\Instances\\DriverName Instance子健下的键值项 //------------------------------------------------------------------------------------------------------- wcscpy_s(szTempStr, L"SYSTEM\\CurrentControlSet\\Services\\"); wcscat_s(szTempStr, lpszDriverName); wcscat_s(szTempStr, L"\\Instances\\"); wcscat_s(szTempStr, lpszDriverName); wcscat_s(szTempStr, L" Instance"); if (RegCreateKeyEx(HKEY_LOCAL_MACHINE, szTempStr, 0, L"", REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, (LPDWORD)&dwData) != ERROR_SUCCESS) { return FALSE; } // 注册表驱动程序的Altitude 值 wcscpy_s(szTempStr, lpszAltitude); if (RegSetValueEx(hKey, L"Altitude", 0, REG_SZ, (CONST BYTE*)szTempStr, (DWORD)(wcslen(szTempStr)*sizeof(WCHAR))) != ERROR_SUCCESS) { return FALSE; } // 注册表驱动程序的Flags 值 dwData = 0x0; if (RegSetValueEx(hKey, L"Flags", 0, REG_DWORD, (CONST BYTE*)&dwData, sizeof(DWORD)) != ERROR_SUCCESS) { return FALSE; } RegFlushKey(hKey);//刷新注册表 RegCloseKey(hKey); return TRUE; } BOOL StartDriver(const WCHAR* lpszDriverName) { SC_HANDLE schManager; SC_HANDLE schService; SERVICE_STATUS svcStatus; if (NULL == lpszDriverName) { return FALSE; } schManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (NULL == schManager) { CloseServiceHandle(schManager); return FALSE; } schService = OpenService(schManager, lpszDriverName, SERVICE_ALL_ACCESS); if (NULL == schService) { CloseServiceHandle(schService); CloseServiceHandle(schManager); return FALSE; } if (!StartService(schService, 0, NULL)) { CloseServiceHandle(schService); CloseServiceHandle(schManager); int i = GetLastError(); CString STemp; STemp.Format(_T("%d"), i); MessageBox(NULL,STemp,STemp,MB_OK); if (GetLastError() == ERROR_SERVICE_ALREADY_RUNNING) { // 服务已经开启 return TRUE; } return FALSE; } CloseServiceHandle(schService); CloseServiceHandle(schManager); return TRUE; } BOOL StopDriver(const WCHAR* lpszDriverName) { SC_HANDLE schManager; SC_HANDLE schService; SERVICE_STATUS svcStatus; bool bStopped = false; schManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (NULL == schManager) { return FALSE; } schService = OpenService(schManager, lpszDriverName, SERVICE_ALL_ACCESS); if (NULL == schService) { CloseServiceHandle(schManager); return FALSE; } if (!ControlService(schService, SERVICE_CONTROL_STOP, &svcStatus) && (svcStatus.dwCurrentState != SERVICE_STOPPED)) { CloseServiceHandle(schService); CloseServiceHandle(schManager); return FALSE; } CloseServiceHandle(schService); CloseServiceHandle(schManager); return TRUE; } BOOL DeleteDriver(const WCHAR* lpszDriverName) { SC_HANDLE schManager; SC_HANDLE schService; SERVICE_STATUS svcStatus; schManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (NULL == schManager) { return FALSE; } schService = OpenService(schManager, lpszDriverName, SERVICE_ALL_ACCESS); if (NULL == schService) { CloseServiceHandle(schManager); return FALSE; } ControlService(schService, SERVICE_CONTROL_STOP, &svcStatus); if (!DeleteService(schService)) { CloseServiceHandle(schService); CloseServiceHandle(schManager); return FALSE; } CloseServiceHandle(schService); CloseServiceHandle(schManager); return TRUE; } void CFQHIPSDlg::OnBnClickedButtonStartdrv() { // TODO: Add your control notification handler code here bool ret = StartDriver(DRIVER_NAME); if (!ret) { m_drvState = L"开启驱动失败"; } else { m_drvState = L"开启驱动成功"; } UpdateData(FALSE); } void CFQHIPSDlg::OnBnClickedButtonPausedrv() { // TODO: Add your control notification handler code here bool ret=StopDriver(DRIVER_NAME); if (!ret) { m_drvState = L"暂停驱动失败"; } else { m_drvState = L"暂停驱动成功"; } UpdateData(FALSE); } void CFQHIPSDlg::OnBnClickedButtonInstalldrv() { // TODO: Add your control notification handler code here bool ret = InstallDriver(DRIVER_NAME, DRIVER_PATH, DRIVER_ALTITUDE); if (!ret) { m_drvState = L"安装驱动失败"; } else { m_drvState = L"安装驱动成功"; } UpdateData(FALSE); } void CFQHIPSDlg::OnBnClickedButtonUninstalldrv() { // TODO: Add your control notification handler code here bool ret=DeleteDriver(DRIVER_NAME); if (!ret) { m_drvState = L"卸载驱动失败"; } else { m_drvState = L"卸载驱动成功"; } UpdateData(FALSE); } <file_sep>/drv/commonFun.c #include <fltKernel.h> #include <dontuse.h> #include <suppress.h> #include <strsafe.h> #include <Ntstrsafe.h > #include "FQDrv.h" #include "commonFun.h" #define MAXPATHLEN 512 #define MAX_PATH 256 //UNICODE_STRINGz 转换为 CHAR* //输入 UNICODE_STRING 的指针,输出窄字符串,BUFFER 需要已经分配好空间 VOID UnicodeToChar(PUNICODE_STRING dst, char *src) { ANSI_STRING string; RtlUnicodeStringToAnsiString(&string, dst, TRUE); strcpy(src, string.Buffer); RtlFreeAnsiString(&string); } //WCHAR*转换为 CHAR* //输入宽字符串首地址,输出窄字符串,BUFFER 需要已经分配好空间 VOID WcharToChar(PWCHAR src, PCHAR dst) { UNICODE_STRING uString; ANSI_STRING aString; RtlInitUnicodeString(&uString, src); RtlUnicodeStringToAnsiString(&aString, &uString, TRUE); strcpy(dst, aString.Buffer); RtlFreeAnsiString(&aString); } //CHAR*转 WCHAR* //输入窄字符串首地址,输出宽字符串,BUFFER 需要已经分配好空间 VOID CharToWchar(PCHAR src, PWCHAR dst) { UNICODE_STRING uString; ANSI_STRING aString; RtlInitAnsiString(&aString, src); RtlAnsiStringToUnicodeString(&uString, &aString, TRUE); wcscpy(dst, uString.Buffer); RtlFreeUnicodeString(&uString); } wchar_t *my_wcsrstr(const wchar_t *str, const wchar_t *sub_str) { const wchar_t *p = NULL; const wchar_t *q = NULL; wchar_t *last = NULL; if (NULL == str || NULL == sub_str) { return NULL; } for (; *str; str++) { p = str, q = sub_str; while (*q && *p) { if (*q != *p) { break; } p++, q++; } if (*q == 0) { last = (wchar_t *)str; str = p - 1; } } return last; } BOOLEAN IsPatternMatch(const PWCHAR pExpression, const PWCHAR pName, BOOLEAN IgnoreCase) { if (NULL == pExpression || wcslen(pExpression) == 0) { return TRUE; } if (pName == NULL || wcslen(pName) == 0) { return FALSE; } if (L'$' == pExpression[0]) { UNICODE_STRING uNewExpression = { 0 }; WCHAR buffer[MAXPATHLEN] = { 0 }; UNICODE_STRING uExpression = { 0 }; UNICODE_STRING uName = { 0 }; RtlInitUnicodeString(&uName, pName); RtlInitUnicodeString(&uExpression, &pExpression[1]); if (FsRtlIsNameInExpression(&uExpression, &uName, IgnoreCase, NULL)) { WCHAR* last = my_wcsrstr(pExpression, L"\\*"); if (NULL == last) { return FALSE; } StringCbCopyNW(buffer, MAXPATHLEN * sizeof(WCHAR), &pExpression[1], (last - pExpression + 1) * sizeof(WCHAR)); StringCbCatW(buffer, MAXPATHLEN * sizeof(WCHAR), last); RtlInitUnicodeString(&uNewExpression, buffer); if (FsRtlIsNameInExpression(&uNewExpression, &uName, IgnoreCase, NULL)) { return FALSE; } else { return TRUE; } } else { return FALSE; } } else { UNICODE_STRING uExpression = { 0 }; UNICODE_STRING uName = { 0 }; RtlInitUnicodeString(&uExpression, pExpression); RtlInitUnicodeString(&uName, pName); return FsRtlIsNameInExpression(&uExpression, &uName, IgnoreCase, NULL); } } BOOLEAN IsShortNamePath(WCHAR * wszFileName) { WCHAR *p = wszFileName; while (*p != L'\0') { if (*p == L'~') { return TRUE; } p++; } return FALSE; } NTSTATUS QuerySymbolicLink( IN PUNICODE_STRING SymbolicLinkName, OUT PUNICODE_STRING LinkTarget ) { OBJECT_ATTRIBUTES oa = { 0 }; NTSTATUS status = 0; HANDLE handle = NULL; InitializeObjectAttributes( &oa, SymbolicLinkName, OBJ_CASE_INSENSITIVE, 0, 0); status = ZwOpenSymbolicLinkObject(&handle, GENERIC_READ, &oa); if (!NT_SUCCESS(status)) { return status; } LinkTarget->MaximumLength = MAX_PATH * sizeof(WCHAR); LinkTarget->Length = 0; LinkTarget->Buffer = ExAllocatePoolWithTag(PagedPool, LinkTarget->MaximumLength, 'SOD'); if (!LinkTarget->Buffer) { ZwClose(handle); return STATUS_INSUFFICIENT_RESOURCES; } RtlZeroMemory(LinkTarget->Buffer, LinkTarget->MaximumLength); status = ZwQuerySymbolicLinkObject(handle, LinkTarget, NULL); ZwClose(handle); if (!NT_SUCCESS(status)) { ExFreePool(LinkTarget->Buffer); } return status; } NTSTATUS MyRtlVolumeDeviceToDosName( IN PUNICODE_STRING DeviceName, OUT PUNICODE_STRING DosName ) /*++ Routine Description: This routine returns a valid DOS path for the given device object. This caller of this routine must call ExFreePool on DosName->Buffer when it is no longer needed. Arguments: VolumeDeviceObject - Supplies the volume device object. DosName - Returns the DOS name for the volume Return Value: NTSTATUS --*/ { NTSTATUS status = 0; UNICODE_STRING driveLetterName = { 0 }; WCHAR driveLetterNameBuf[128] = { 0 }; WCHAR c = L'\0'; WCHAR DriLetter[3] = { 0 }; UNICODE_STRING linkTarget = { 0 }; for (c = L'A'; c <= L'Z'; c++) { RtlInitEmptyUnicodeString(&driveLetterName, driveLetterNameBuf, sizeof(driveLetterNameBuf)); RtlAppendUnicodeToString(&driveLetterName, L"\\??\\"); DriLetter[0] = c; DriLetter[1] = L':'; DriLetter[2] = 0; RtlAppendUnicodeToString(&driveLetterName, DriLetter); status = QuerySymbolicLink(&driveLetterName, &linkTarget); if (!NT_SUCCESS(status)) { continue; } if (RtlEqualUnicodeString(&linkTarget, DeviceName, TRUE)) { ExFreePool(linkTarget.Buffer); break; } ExFreePool(linkTarget.Buffer); } if (c <= L'Z') { DosName->Buffer = ExAllocatePoolWithTag(PagedPool, 3 * sizeof(WCHAR), 'SOD'); if (!DosName->Buffer) { return STATUS_INSUFFICIENT_RESOURCES; } DosName->MaximumLength = 6; DosName->Length = 4; *DosName->Buffer = c; *(DosName->Buffer + 1) = ':'; *(DosName->Buffer + 2) = 0; return STATUS_SUCCESS; } return status; } //c:\\windows\\hi.txt<--\\device\\harddiskvolume1\\windows\\hi.txt BOOLEAN NTAPI GetNTLinkName(IN WCHAR * wszNTName, OUT WCHAR * wszFileName) { UNICODE_STRING ustrFileName = { 0 }; UNICODE_STRING ustrDosName = { 0 }; UNICODE_STRING ustrDeviceName = { 0 }; WCHAR *pPath = NULL; ULONG i = 0; ULONG ulSepNum = 0; if (wszFileName == NULL || wszNTName == NULL || _wcsnicmp(wszNTName, L"\\device\\harddiskvolume", wcslen(L"\\device\\harddiskvolume")) != 0) { return FALSE; } ustrFileName.Buffer = wszFileName; ustrFileName.Length = 0; ustrFileName.MaximumLength = sizeof(WCHAR)*MAX_PATH; while (wszNTName[i] != L'\0') { if (wszNTName[i] == L'\0') { break; } if (wszNTName[i] == L'\\') { ulSepNum++; } if (ulSepNum == 3) { wszNTName[i] = UNICODE_NULL; pPath = &wszNTName[i + 1]; break; } i++; } if (pPath == NULL) { return FALSE; } RtlInitUnicodeString(&ustrDeviceName, wszNTName); if (!NT_SUCCESS(MyRtlVolumeDeviceToDosName(&ustrDeviceName, &ustrDosName))) { return FALSE; } RtlCopyUnicodeString(&ustrFileName, &ustrDosName); RtlAppendUnicodeToString(&ustrFileName, L"\\"); RtlAppendUnicodeToString(&ustrFileName, pPath); ExFreePool(ustrDosName.Buffer); return TRUE; } BOOLEAN QueryVolumeName(WCHAR ch, WCHAR * name, USHORT size) { WCHAR szVolume[7] = L"\\??\\C:"; UNICODE_STRING LinkName; UNICODE_STRING VolName; UNICODE_STRING ustrTarget; NTSTATUS ntStatus = 0; RtlInitUnicodeString(&LinkName, szVolume); szVolume[4] = ch; ustrTarget.Buffer = name; ustrTarget.Length = 0; ustrTarget.MaximumLength = size; ntStatus = QuerySymbolicLink(&LinkName, &VolName); if (NT_SUCCESS(ntStatus)) { RtlCopyUnicodeString(&ustrTarget, &VolName); ExFreePool(VolName.Buffer); } return NT_SUCCESS(ntStatus); } //\\??\\c:\\windows\\hi.txt-->\\device\\harddiskvolume1\\windows\\hi.txt BOOLEAN NTAPI GetNtDeviceName(IN WCHAR * filename, OUT WCHAR * ntname) { UNICODE_STRING uVolName = { 0,0,0 }; WCHAR volName[MAX_PATH] = L""; WCHAR tmpName[MAX_PATH] = L""; WCHAR chVol = L'\0'; WCHAR * pPath = NULL; int i = 0; RtlStringCbCopyW(tmpName, MAX_PATH * sizeof(WCHAR), filename); for (i = 1; i < MAX_PATH - 1; i++) { if (tmpName[i] == L':') { pPath = &tmpName[(i + 1) % MAX_PATH]; chVol = tmpName[i - 1]; break; } } if (pPath == NULL) { return FALSE; } if (chVol == L'?') { uVolName.Length = 0; uVolName.MaximumLength = MAX_PATH * sizeof(WCHAR); uVolName.Buffer = ntname; RtlAppendUnicodeToString(&uVolName, L"\\Device\\HarddiskVolume?"); RtlAppendUnicodeToString(&uVolName, pPath); return TRUE; } else if (QueryVolumeName(chVol, volName, MAX_PATH * sizeof(WCHAR))) { uVolName.Length = 0; uVolName.MaximumLength = MAX_PATH * sizeof(WCHAR); uVolName.Buffer = ntname; RtlAppendUnicodeToString(&uVolName, volName); RtlAppendUnicodeToString(&uVolName, pPath); return TRUE; } return FALSE; } WCHAR my_towupper(WCHAR wch) { if (wch >= L'a' && wch <= L'z') { return wch - L'a' + L'A'; } return wch; } VOID ToUpperString(WCHAR* str) { for (int i = 0; str[i]; i++) { str[i] = my_towupper(str[i]); } } <file_sep>/COtherManager.h #pragma once // COtherManager 对话框 class COtherManager : public CDialogEx { DECLARE_DYNAMIC(COtherManager) public: COtherManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~COtherManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_OTHER_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() }; <file_sep>/CProcessManager.h #pragma once // CProcessManager 对话框 class CProcessManager : public CDialogEx { DECLARE_DYNAMIC(CProcessManager) public: CProcessManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CProcessManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_PROCESS_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: CString m_ProcessRule; afx_msg void OnBnClickedButtonAdd(); CString m_ruleState; afx_msg void OnBnClickedButtonDel(); afx_msg void OnBnClickedButtonPause(); afx_msg void OnBnClickedButtonRestart(); virtual BOOL OnInitDialog(); CListCtrl m_listCtrl; }; bool writeToProcessMonFile();<file_sep>/CFirewallManager.h #pragma once // CFirewallManager 对话框 class CFirewallManager : public CDialogEx { DECLARE_DYNAMIC(CFirewallManager) public: CFirewallManager(CWnd* pParent = nullptr); // 标准构造函数 virtual ~CFirewallManager(); // 对话框数据 #ifdef AFX_DESIGN_TIME enum { IDD = IDD_DIALOG_FIREWALL_MANAGER }; #endif protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedButtonAdd(); afx_msg void OnBnClickedButtonDel(); CString m_ruleState; CString m_NetRule; CListCtrl m_listCtrl; virtual BOOL OnInitDialog(); afx_msg void OnBnClickedButtonPause(); afx_msg void OnBnClickedButtonRestart(); }; bool writeToNetMonFile();<file_sep>/drv/FQDrv.c #include <fltKernel.h> #include <dontuse.h> #include <suppress.h> #include "commonStruct.h" #include "FQDrv.h" #include "commonFun.h" #include <ntimage.h> //#pragma comment(lib,"ntoskrnl.lib") //#pragma comment(lib,"ndis.lib") //#pragma comment(lib,"fwpkclnt.lib") //#pragma comment(lib,"uuid.lib") #define NDIS61 #include <ntddk.h> #pragma warning(push) #pragma warning(disable:4201) // unnamed struct/union #pragma warning(disable:4995) #include <fwpsk.h> #pragma warning(pop) #include <ndis.h> #include <fwpmk.h> #include <limits.h> #include <ws2ipdef.h> #include <in6addr.h> #include <ip2string.h> #include <strsafe.h> #define INITGUID #include <guiddef.h> #define bool BOOLEAN #define true TRUE #define false FALSE #define DEVICE_NAME L"\\Device\\WFP_TEST" #define DEVICE_DOSNAME L"\\DosDevices\\WFP_TEST" #define kmalloc(_s) ExAllocatePoolWithTag(NonPagedPool, _s, 'SYSQ') #define kfree(_p) ExFreePool(_p) #pragma prefast(disable:__WARNING_ENCODE_MEMBER_FUNCTION_POINTER, "Not valid for kernel mode drivers") DEFINE_GUID // {6812FC83-7D3E-499a-A012-55E0D85F348B} ( GUID_ALE_AUTH_CONNECT_CALLOUT_V4, 0x6812fc83, 0x7d3e, 0x499a, 0xa0, 0x12, 0x55, 0xe0, 0xd8, 0x5f, 0x34, 0x8b ); PDEVICE_OBJECT gDevObj; HANDLE gEngineHandle = 0; HANDLE gInjectHandle = 0; //CalloutId UINT32 gAleConnectCalloutId = 0; //FilterId UINT64 gAleConnectFilterId = 0; /* 以下两个回调函数没啥用 */ NTSTATUS NTAPI WallNotifyFn ( IN FWPS_CALLOUT_NOTIFY_TYPE notifyType, IN const GUID *filterKey, IN const FWPS_FILTER *filter ) { return STATUS_SUCCESS; } VOID NTAPI WallFlowDeleteFn ( IN UINT16 layerId, IN UINT32 calloutId, IN UINT64 flowContext ) { return; } //注册表相关 #define REGISTRY_POOL_TAG 'pRE' NTKERNELAPI NTSTATUS ObQueryNameString ( IN PVOID Object, OUT POBJECT_NAME_INFORMATION ObjectNameInfo, IN ULONG Length, OUT PULONG ReturnLength ); NTKERNELAPI NTSTATUS RtlUnicodeStringCopy ( __out PUNICODE_STRING DestinationString, __in PUNICODE_STRING SourceString ); //进程监控相关 NTKERNELAPI PCHAR PsGetProcessImageFileName(PEPROCESS Process); NTKERNELAPI NTSTATUS PsLookupProcessByProcessId(HANDLE ProcessId, PEPROCESS *Process); //删除文件相关 NTSTATUS ZwQueryDirectoryFile( __in HANDLE FileHandle, __in_opt HANDLE Event, __in_opt PIO_APC_ROUTINE ApcRoutine, __in_opt PVOID ApcContext, __out PIO_STATUS_BLOCK IoStatusBlock, __out PVOID FileInformation, __in ULONG Length, __in FILE_INFORMATION_CLASS FileInformationClass, __in BOOLEAN ReturnSingleEntry, __in_opt PUNICODE_STRING FileName, __in BOOLEAN RestartScan ); // // Structure that contains all the global data structures // used throughout the FQDRV. // FQDRV_DATA FQDRVData; UNICODE_STRING g_LastDelFileName = { 0 }; // // Function prototypes // pFilenames m_pfilenames=NULL;//文件规则链表 ERESOURCE g_fileLock; pFilenames m_pProcessNames = NULL;//进程规则链表 ERESOURCE g_processLock; pFilenames m_pMoudleNames = NULL;//模块规则链表 ERESOURCE g_moduleLock; pFilenames m_pNetRejectNames = NULL;//禁止网络访问规则链表 ERESOURCE g_NetRejectLock; ULONG g_ulCurrentWaitID = 0;//攻击事件ID VOID __stdcall LockWrite(ERESOURCE *lpLock) { KeEnterCriticalRegion(); ExAcquireResourceExclusiveLite(lpLock, TRUE); } VOID __stdcall UnLockWrite(ERESOURCE *lpLock) { ExReleaseResourceLite(lpLock); KeLeaveCriticalRegion(); } VOID __stdcall LockRead(ERESOURCE *lpLock) { KeEnterCriticalRegion(); ExAcquireResourceSharedLite(lpLock, TRUE); } VOID __stdcall LockReadStarveWriter(ERESOURCE *lpLock) { KeEnterCriticalRegion(); ExAcquireSharedStarveExclusive(lpLock, TRUE); } VOID __stdcall UnLockRead(ERESOURCE *lpLock) { ExReleaseResourceLite(lpLock); KeLeaveCriticalRegion(); } VOID __stdcall InitLock(ERESOURCE *lpLock) { ExInitializeResourceLite(lpLock); } VOID __stdcall DeleteLock(ERESOURCE *lpLock) { ExDeleteResourceLite(lpLock); } ULONG isOpenFilter = 1; ULONG isOpenReg = 1; ULONG isOpenProcess = 1; ULONG isOpenModule = 1; ULONG isOpenNet = 1; NTSTATUS FQDRVPortConnect( __in PFLT_PORT ClientPort, __in_opt PVOID ServerPortCookie, __in_bcount_opt(SizeOfContext) PVOID ConnectionContext, __in ULONG SizeOfContext, __deref_out_opt PVOID *ConnectionCookie ); VOID FQDRVPortDisconnect( __in_opt PVOID ConnectionCookie ); NTSTATUS FQDRVpScanFileInUserMode( __in PFLT_INSTANCE Instance, __in PFILE_OBJECT FileObject, __in PFLT_CALLBACK_DATA Data, __in ULONG Operation, __out PBOOLEAN SafeToOpen ); // // Assign text sections for each routine. // #ifdef ALLOC_PRAGMA #pragma alloc_text(INIT, DriverEntry) #pragma alloc_text(PAGE, FQDRVInstanceSetup) #pragma alloc_text(PAGE, FQDRVPreCreate) #pragma alloc_text(PAGE, FQDRVPostCreate) #pragma alloc_text(PAGE, FQDRVPortConnect) #pragma alloc_text(PAGE, FQDRVPortDisconnect) #pragma alloc_text(PAGE, FQDRVPreSetInforMation) #pragma alloc_text(PAGE, FQDRVPostSetInforMation) #endif // // Constant FLT_REGISTRATION structure for our filter. This // initializes the callback routines our filter wants to register // for. This is only used to register with the filter manager // const FLT_OPERATION_REGISTRATION Callbacks[] = { { IRP_MJ_CREATE, 0, FQDRVPreCreate, FQDRVPostCreate}, { IRP_MJ_CLEANUP, 0, FQDRVPreCleanup, NULL}, { IRP_MJ_WRITE, 0, FQDRVPreWrite, NULL}, { IRP_MJ_SET_INFORMATION, 0, FQDRVPreSetInforMation, FQDRVPostSetInforMation}, { IRP_MJ_OPERATION_END} }; const FLT_CONTEXT_REGISTRATION ContextRegistration[] = { { FLT_STREAMHANDLE_CONTEXT, 0, NULL, sizeof(FQDRV_STREAM_HANDLE_CONTEXT), 'chBS' }, { FLT_CONTEXT_END } }; const FLT_REGISTRATION FilterRegistration = { sizeof(FLT_REGISTRATION), // Size FLT_REGISTRATION_VERSION, // Version 0, // Flags ContextRegistration, // Context Registration. Callbacks, // Operation callbacks FQDRVUnload, // FilterUnload FQDRVInstanceSetup, // InstanceSetup FQDRVQueryTeardown, // InstanceQueryTeardown NULL, // InstanceTeardownStart NULL, // InstanceTeardownComplete NULL, // GenerateFileName NULL, // GenerateDestinationFileName NULL // NormalizeNameComponent }; //////////////////////////////////////////////////////////////////////////// // // Filter initialization and unload routines. // //////////////////////////////////////////////////////////////////////////// //协议代码转为名称 char* ProtocolIdToName(UINT16 id) { char *ProtocolName = kmalloc(16); switch (id) //http://www.ietf.org/rfc/rfc1700.txt { case 1: strcpy_s(ProtocolName, 4 + 1, "ICMP"); break; case 2: strcpy_s(ProtocolName, 4 + 1, "IGMP"); break; case 6: strcpy_s(ProtocolName, 3 + 1, "TCP"); break; case 17: strcpy_s(ProtocolName, 3 + 1, "UDP"); break; case 27: strcpy_s(ProtocolName, 3 + 1, "RDP"); break; default: strcpy_s(ProtocolName, 7 + 1, "UNKNOWN"); break; } return ProtocolName; } //最重要的过滤函数 //http://msdn.microsoft.com/en-us/library/windows/hardware/ff551238(v=vs.85).aspx void NTAPI WallALEConnectClassify ( IN const FWPS_INCOMING_VALUES0* inFixedValues, IN const FWPS_INCOMING_METADATA_VALUES0* inMetaValues, IN OUT void* layerData, IN const void* classifyContext, IN const FWPS_FILTER* filter, IN UINT64 flowContext, OUT FWPS_CLASSIFY_OUT* classifyOut ) { char *ProtocolName = NULL; DWORD LocalIp, RemoteIP; LocalIp = inFixedValues->incomingValue[FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_LOCAL_ADDRESS].value.uint32; RemoteIP = inFixedValues->incomingValue[FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_REMOTE_ADDRESS].value.uint32; ProtocolName = ProtocolIdToName(inFixedValues->incomingValue[FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_PROTOCOL].value.uint16); //DbgPrint("[WFP]IRQL=%d;PID=%ld;Path=%S;Local=%u.%u.%u.%u:%d;Remote=%u.%u.%u.%u:%d;Protocol=%s\n", // (USHORT)KeGetCurrentIrql(), // (DWORD)(inMetaValues->processId), // (PWCHAR)inMetaValues->processPath->data, //NULL,// // (LocalIp >> 24) & 0xFF, (LocalIp >> 16) & 0xFF, (LocalIp >> 8) & 0xFF, LocalIp & 0xFF, // inFixedValues->incomingValue[FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_LOCAL_PORT].value.uint16, // (RemoteIP >> 24) & 0xFF, (RemoteIP >> 16) & 0xFF, (RemoteIP >> 8) & 0xFF, RemoteIP & 0xFF, // inFixedValues->incomingValue[FWPS_FIELD_ALE_AUTH_CONNECT_V4_IP_REMOTE_PORT].value.uint16, // ProtocolName); kfree(ProtocolName); //classifyOut->actionType = FWP_ACTION_PERMIT;//允许连接 //禁止IE联网(设置“行动类型”为FWP_ACTION_BLOCK) if((isOpenNet==1)&&(searchModuleRule(inMetaValues->processPath->data,&m_pNetRejectNames))) { classifyOut->actionType = FWP_ACTION_BLOCK; classifyOut->rights &= ~FWPS_RIGHT_ACTION_WRITE; classifyOut->flags |= FWPS_CLASSIFY_OUT_FLAG_ABSORB; DbgPrint("%S静止连网",(PWCHAR)inMetaValues->processPath->data); } else { classifyOut->actionType = FWP_ACTION_PERMIT;//允许连接 } return; } NTSTATUS RegisterCalloutForLayer ( IN const GUID* layerKey, IN const GUID* calloutKey, IN FWPS_CALLOUT_CLASSIFY_FN classifyFn, IN FWPS_CALLOUT_NOTIFY_FN notifyFn, IN FWPS_CALLOUT_FLOW_DELETE_NOTIFY_FN flowDeleteNotifyFn, OUT UINT32* calloutId, OUT UINT64* filterId ) { NTSTATUS status = STATUS_SUCCESS; FWPS_CALLOUT sCallout = { 0 }; FWPM_FILTER mFilter = { 0 }; FWPM_FILTER_CONDITION mFilter_condition[1] = { 0 }; FWPM_CALLOUT mCallout = { 0 }; FWPM_DISPLAY_DATA mDispData = { 0 }; BOOLEAN bCalloutRegistered = FALSE; sCallout.calloutKey = *calloutKey; sCallout.classifyFn = classifyFn; sCallout.flowDeleteFn = flowDeleteNotifyFn; sCallout.notifyFn = notifyFn; //要使用哪个设备对象注册 status = FwpsCalloutRegister(gDevObj, &sCallout, calloutId); if (!NT_SUCCESS(status)) goto exit; bCalloutRegistered = TRUE; mDispData.name = L"WFP TEST"; mDispData.description = L"TESLA.ANGELA's WFP TEST"; //你感兴趣的内容 mCallout.applicableLayer = *layerKey; //你感兴趣的内容的GUID mCallout.calloutKey = *calloutKey; mCallout.displayData = mDispData; //添加回调函数 status = FwpmCalloutAdd(gEngineHandle, &mCallout, NULL, NULL); if (!NT_SUCCESS(status)) goto exit; mFilter.action.calloutKey = *calloutKey; //在callout里决定 mFilter.action.type = FWP_ACTION_CALLOUT_TERMINATING; mFilter.displayData.name = L"WFP TEST"; mFilter.displayData.description = L"TESLA.ANGELA's WFP TEST"; mFilter.layerKey = *layerKey; mFilter.numFilterConditions = 0; mFilter.filterCondition = mFilter_condition; mFilter.subLayerKey = FWPM_SUBLAYER_UNIVERSAL; mFilter.weight.type = FWP_EMPTY; //添加过滤器 status = FwpmFilterAdd(gEngineHandle, &mFilter, NULL, filterId); if (!NT_SUCCESS(status)) goto exit; exit: if (!NT_SUCCESS(status)) { if (bCalloutRegistered) { FwpsCalloutUnregisterById(*calloutId); } } return status; } NTSTATUS WallRegisterCallouts() { NTSTATUS status = STATUS_SUCCESS; BOOLEAN bInTransaction = FALSE; BOOLEAN bEngineOpened = FALSE; FWPM_SESSION session = { 0 }; session.flags = FWPM_SESSION_FLAG_DYNAMIC; //开启WFP引擎 status = FwpmEngineOpen(NULL, RPC_C_AUTHN_WINNT, NULL, &session, &gEngineHandle); if (!NT_SUCCESS(status)) goto exit; bEngineOpened = TRUE; //确认过滤权限 status = FwpmTransactionBegin(gEngineHandle, 0); if (!NT_SUCCESS(status)) goto exit; bInTransaction = TRUE; //注册回调函数 status = RegisterCalloutForLayer( &FWPM_LAYER_ALE_AUTH_CONNECT_V4, &GUID_ALE_AUTH_CONNECT_CALLOUT_V4, WallALEConnectClassify, WallNotifyFn, WallFlowDeleteFn, &gAleConnectCalloutId, &gAleConnectFilterId); if (!NT_SUCCESS(status)) { DbgPrint("RegisterCalloutForLayer-FWPM_LAYER_ALE_AUTH_CONNECT_V4 failed!\n"); goto exit; } //确认所有内容并提交,让回调函数正式发挥作用 status = FwpmTransactionCommit(gEngineHandle); if (!NT_SUCCESS(status)) goto exit; bInTransaction = FALSE; exit: if (!NT_SUCCESS(status)) { if (bInTransaction) { FwpmTransactionAbort(gEngineHandle); } if (bEngineOpened) { FwpmEngineClose(gEngineHandle); gEngineHandle = 0; } } return status; } NTSTATUS WallUnRegisterCallouts() { if (gEngineHandle != 0) { //删除FilterId FwpmFilterDeleteById(gEngineHandle, gAleConnectFilterId); //删除CalloutId FwpmCalloutDeleteById(gEngineHandle, gAleConnectCalloutId); //清空FilterId gAleConnectFilterId = 0; //反注册CalloutId FwpsCalloutUnregisterById(gAleConnectCalloutId); //清空CalloutId gAleConnectCalloutId = 0; //关闭引擎 FwpmEngineClose(gEngineHandle); gEngineHandle = 0; } return STATUS_SUCCESS; } VOID DriverUnload(PDRIVER_OBJECT driverObject) { NTSTATUS status; status = WallUnRegisterCallouts(); if (!NT_SUCCESS(status)) { DbgPrint("网络监控开启 SUCCESS\n"); return; } if (gDevObj) { IoDeleteDevice(gDevObj); gDevObj = NULL; } DbgPrint("网络监控开启 failed\n"); } NTSTATUS DriverEntry( __in PDRIVER_OBJECT DriverObject, __in PUNICODE_STRING RegistryPath ) { OBJECT_ATTRIBUTES oa; UNICODE_STRING uniString; PSECURITY_DESCRIPTOR sd; NTSTATUS status; //UNREFERENCED_PARAMETER(RegistryPath); //DriverObject->DriverUnload = DriverUnload; UNICODE_STRING deviceName = { 0 }; UNICODE_STRING deviceDosName = { 0 }; DriverObject->DriverUnload = DriverUnload; RtlInitUnicodeString(&deviceName, DEVICE_NAME); status = IoCreateDevice(DriverObject, 0, &deviceName, FILE_DEVICE_NETWORK, 0, FALSE, &gDevObj); if (!NT_SUCCESS(status)) { DbgPrint("WFP设备IoCreateDevice failed!\n"); return STATUS_UNSUCCESSFUL; } RtlInitUnicodeString(&deviceDosName, DEVICE_DOSNAME); status = IoCreateSymbolicLink(&deviceDosName, &deviceName); if (!NT_SUCCESS(status)) { DbgPrint("WFP设备Create Symbolink name failed!\n"); return STATUS_UNSUCCESSFUL; } status = WallRegisterCallouts(); if (!NT_SUCCESS(status)) { DbgPrint("WFP设备WallRegisterCallouts failed!\n"); return STATUS_UNSUCCESSFUL; } DbgPrint("WFP设备 loaded! WallRegisterCallouts() success!\n"); InitLock(&g_fileLock); InitLock(&g_processLock); InitLock(&g_moduleLock); g_LastDelFileName.Buffer = ExAllocatePool(NonPagedPool, MAX_PATH * 2); g_LastDelFileName.Length = g_LastDelFileName.MaximumLength = MAX_PATH * 2; memset(g_LastDelFileName.Buffer, '\0', MAX_PATH * 2); //注册表监控初始化 status = PtRegisterInit(); if (!NT_SUCCESS(status)) { PtRegisterUnInit(); } status = PtProcessInit(); if (!NT_SUCCESS(status)) { DbgPrint("初始化进程监控失败\n"); PtProcessUnInit(); } status = PtModuleInit(); if (!NT_SUCCESS(status)) { DbgPrint("初始化模块失败\n"); PtProcessUnInit(); } status = FltRegisterFilter(DriverObject, &FilterRegistration, &FQDRVData.Filter); //status = WallRegisterCallouts(); if (!NT_SUCCESS(status)) { DbgPrint("WFP设备WallRegisterCallouts failed!\n"); return STATUS_UNSUCCESSFUL; } DbgPrint("WFP设备 loaded! WallRegisterCallouts() success!\n"); if (!NT_SUCCESS(status)) { return status; } // // Create a communication port. // RtlInitUnicodeString(&uniString, FQDRVPortName); // // We secure the port so only ADMINs & SYSTEM can acecss it. // status = FltBuildDefaultSecurityDescriptor(&sd, FLT_PORT_ALL_ACCESS);//创建安全描述符,防止端口被非管理员用户打开 if (NT_SUCCESS(status)) { InitializeObjectAttributes(&oa, &uniString, OBJ_CASE_INSENSITIVE | OBJ_KERNEL_HANDLE, NULL, sd); status = FltCreateCommunicationPort(FQDRVData.Filter, &FQDRVData.ServerPort, &oa, NULL, FQDRVPortConnect, FQDRVPortDisconnect, MessageNotifyCallback, 1); // // Free the security descriptor in all cases. It is not needed once // the call to FltCreateCommunicationPort() is made. // FltFreeSecurityDescriptor(sd); if (NT_SUCCESS(status)) { // // Start filtering I/O. // status = FltStartFiltering(FQDRVData.Filter); if (NT_SUCCESS(status)) { return STATUS_SUCCESS; } FltCloseCommunicationPort(FQDRVData.ServerPort); } } FltUnregisterFilter(FQDRVData.Filter); return status; } NTSTATUS FQDRVPortConnect( __in PFLT_PORT ClientPort,//应用层端口 __in_opt PVOID ServerPortCookie, __in_bcount_opt(SizeOfContext) PVOID ConnectionContext, __in ULONG SizeOfContext, __deref_out_opt PVOID *ConnectionCookie ) { PAGED_CODE(); UNREFERENCED_PARAMETER(ServerPortCookie); UNREFERENCED_PARAMETER(ConnectionContext); UNREFERENCED_PARAMETER(SizeOfContext); UNREFERENCED_PARAMETER(ConnectionCookie); ASSERT(FQDRVData.ClientPort == NULL); ASSERT(FQDRVData.UserProcess == NULL); // // Set the user process and port. // FQDRVData.UserProcess = PsGetCurrentProcess();//应用层EPROCESS结构 FQDRVData.ClientPort = ClientPort; DbgPrint("!!! FQDRV.sys --- connected, port=0x%p\n", ClientPort); return STATUS_SUCCESS; } VOID FQDRVPortDisconnect( __in_opt PVOID ConnectionCookie ) { UNREFERENCED_PARAMETER(ConnectionCookie); PAGED_CODE(); DbgPrint("!!! FQDRV.sys --- disconnected, port=0x%p\n", FQDRVData.ClientPort); FltCloseClientPort(FQDRVData.Filter, &FQDRVData.ClientPort); FQDRVData.UserProcess = NULL; } NTSTATUS FQDRVUnload( __in FLT_FILTER_UNLOAD_FLAGS Flags ) { UNREFERENCED_PARAMETER(Flags); // // Close the server port. // if (g_LastDelFileName.Buffer) ExFreePool(g_LastDelFileName.Buffer); FltCloseCommunicationPort(FQDRVData.ServerPort); // // Unregister the filter // NTSTATUS status = STATUS_SUCCESS; FltUnregisterFilter(FQDRVData.Filter); PtRegisterUnInit(); PtProcessUnInit(); PtModuleUnInit(); DeleteLock(&g_fileLock); DeleteLock(&g_processLock); DeleteLock(&g_moduleLock); return STATUS_SUCCESS; } NTSTATUS FQDRVInstanceSetup( __in PCFLT_RELATED_OBJECTS FltObjects, __in FLT_INSTANCE_SETUP_FLAGS Flags, __in DEVICE_TYPE VolumeDeviceType, __in FLT_FILESYSTEM_TYPE VolumeFilesystemType ) { UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(Flags); UNREFERENCED_PARAMETER(VolumeFilesystemType); PAGED_CODE(); ASSERT(FltObjects->Filter == FQDRVData.Filter); // // Don't attach to network volumes. // if (VolumeDeviceType == FILE_DEVICE_NETWORK_FILE_SYSTEM) { return STATUS_FLT_DO_NOT_ATTACH; } return STATUS_SUCCESS; } NTSTATUS FQDRVQueryTeardown( __in PCFLT_RELATED_OBJECTS FltObjects, __in FLT_INSTANCE_QUERY_TEARDOWN_FLAGS Flags ) { UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(Flags); return STATUS_SUCCESS; } FLT_PREOP_CALLBACK_STATUS FQDRVPreCreate( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ) { UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(CompletionContext); PAGED_CODE(); // // See if this create is being done by our user process. // if (IoThreadToProcess(Data->Thread) == FQDRVData.UserProcess) {//拿到发送创建请求的Eprocess结构 DbgPrint("!!! FQDRV.sys -- allowing create for trusted process \n"); return FLT_PREOP_SUCCESS_NO_CALLBACK; } return FLT_PREOP_SUCCESS_WITH_CALLBACK; } FLT_POSTOP_CALLBACK_STATUS FQDRVPostCreate( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __in_opt PVOID CompletionContext, __in FLT_POST_OPERATION_FLAGS Flags ) { //PFQDRV_STREAM_HANDLE_CONTEXT FQDRVContext; FLT_POSTOP_CALLBACK_STATUS returnStatus = FLT_POSTOP_FINISHED_PROCESSING; PFLT_FILE_NAME_INFORMATION nameInfo; NTSTATUS status; BOOLEAN safeToOpen, scanFile; ULONG options; ULONG ulDisposition; BOOLEAN isPopWindow = FALSE; FILE_DISPOSITION_INFORMATION fdi; UNREFERENCED_PARAMETER(CompletionContext); UNREFERENCED_PARAMETER(Flags); // // If this create was failing anyway, don't bother scanning now. // if (isOpenFilter) { if (!NT_SUCCESS(Data->IoStatus.Status) ||//打开不成功 (STATUS_REPARSE == Data->IoStatus.Status)) {//文件是重定向的 return FLT_POSTOP_FINISHED_PROCESSING; } options = Data->Iopb->Parameters.Create.Options; //下面判断 if (FlagOn(options, FILE_DIRECTORY_FILE) ||//是目录 FlagOn(FltObjects->FileObject->Flags, FO_VOLUME_OPEN) || //文件对象表示卷打开请求。 FlagOn(Data->Flags, SL_OPEN_PAGING_FILE))//打开标识 { return FLT_POSTOP_FINISHED_PROCESSING; } ulDisposition = (Data->Iopb->Parameters.Create.Options >> 24) & 0xFF; if (ulDisposition == FILE_CREATE || ulDisposition == FILE_OVERWRITE || ulDisposition == FILE_OVERWRITE_IF) { isPopWindow = TRUE; } // // Check if we are interested in this file. // status = FltGetFileNameInformation(Data,//拿到文件名字 FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &nameInfo); if (!NT_SUCCESS(status)) { return FLT_POSTOP_FINISHED_PROCESSING; } FltParseFileNameInformation(nameInfo);//w文件路径解析,扩展名,路径,等 //scanFile = FQDRVpCheckExtension(&nameInfo->Extension);//看扩展名是不是需要的 WCHAR tmp[256] = { 0 }; wcsncpy_s(tmp, nameInfo->Name.Length, nameInfo->Name.Buffer, nameInfo->Name.Length); //DbgPrint(" tmp路径是%S\n", tmp); //scanFile = IsPatternMatch(L"\\*\\*\\WINDOWS\\SYSTEM32\\*\\*.*", tmp, TRUE); //LockRead(&g_fileLock); scanFile = searchRule(tmp,&m_pfilenames); //UnLockRead(&g_fileLock); FltReleaseFileNameInformation(nameInfo); if (!scanFile) { return FLT_POSTOP_FINISHED_PROCESSING; } if (isPopWindow) { FQDRVpScanFileInUserMode( FltObjects->Instance, FltObjects->FileObject, Data, 1,//1是创建 &safeToOpen ); if (!safeToOpen) { DbgPrint("拒绝创建操作\n"); //就算拒绝了 也会创建一个空文件 这里我们删除 fdi.DeleteFile = TRUE; FltSetInformationFile(FltObjects->Instance, FltObjects->FileObject, &fdi, sizeof(FILE_DISPOSITION_INFORMATION), FileDispositionInformation); FltCancelFileOpen(FltObjects->Instance, FltObjects->FileObject); Data->IoStatus.Status = STATUS_ACCESS_DENIED; Data->IoStatus.Information = 0; returnStatus = FLT_POSTOP_FINISHED_PROCESSING; } } } return returnStatus; } FLT_PREOP_CALLBACK_STATUS FQDRVPreCleanup( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ) { UNREFERENCED_PARAMETER(Data); UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(CompletionContext); return FLT_PREOP_SUCCESS_NO_CALLBACK; } FLT_PREOP_CALLBACK_STATUS FQDRVPreWrite( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ) { FLT_PREOP_CALLBACK_STATUS returnStatus = FLT_PREOP_SUCCESS_NO_CALLBACK; UNREFERENCED_PARAMETER(CompletionContext); UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(Data); // // If not client port just ignore this write. // if (FQDRVData.ClientPort == NULL) { return FLT_PREOP_SUCCESS_NO_CALLBACK; } return returnStatus; } BOOLEAN isNeedWatchFile(PFLT_CALLBACK_DATA Data) { BOOLEAN Ret = FALSE; //UNICODE_STRING ustrRule = { 0 }; PFLT_FILE_NAME_INFORMATION nameInfo = { 0 }; NTSTATUS status = STATUS_SUCCESS; status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &nameInfo); if (!NT_SUCCESS(status)) { return FALSE; } FltParseFileNameInformation(nameInfo); WCHAR tmp[256] = { 0 }; wcsncpy_s(tmp, nameInfo->Name.Length, nameInfo->Name.Buffer, nameInfo->Name.Length); //RtlInitUnicodeString(&ustrRule, L"\\*\\*\\WINDOWS\\SYSTEM32\\*\\*.SYS"); //Ret = IsPatternMatch(L"\\*\\*\\WINDOWS\\SYSTEM32\\*\\*.*", tmp, TRUE); //LockRead(&g_fileLock); Ret=searchRule(tmp,&m_pfilenames); //UnLockRead(&g_fileLock); FltReleaseFileNameInformation(nameInfo); return Ret; } BOOLEAN isRecycle(PFLT_CALLBACK_DATA Data, PCFLT_RELATED_OBJECTS FltObje) { BOOLEAN Ret = FALSE; PFLT_FILE_NAME_INFORMATION nameInfo = { 0 }; PFILE_RENAME_INFORMATION pRenameInfo = { 0 }; NTSTATUS status = STATUS_SUCCESS; char *temp = (char*)ExAllocatePool(NonPagedPool, MAX_PATH * 2); if (temp == NULL) return TRUE; memset(temp, '\0', MAX_PATH * 2); //特殊情况,当字符串中包含$Recycle.Bin时是普通删除,实际上删除只是更名而已 pRenameInfo = (PFILE_RENAME_INFORMATION)Data->Iopb->Parameters.SetFileInformation.InfoBuffer; status = FltGetDestinationFileNameInformation(FltObje->Instance, Data->Iopb->TargetFileObject, pRenameInfo->RootDirectory, pRenameInfo->FileName, pRenameInfo->FileNameLength, FLT_FILE_NAME_NORMALIZED, &nameInfo); if (!NT_SUCCESS(status)) { DbgPrint("FltGetDestinationFileNameInformation is faild! 0x%x", status); return TRUE; } UnicodeToChar(&nameInfo->Name, temp); if (strstr(temp, "Recycle.Bin")) Ret = TRUE; else Ret = FALSE; FltReleaseFileNameInformation(nameInfo); ExFreePool(temp); return Ret; } FLT_PREOP_CALLBACK_STATUS FQDRVPreSetInforMation( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __deref_out_opt PVOID *CompletionContext ) { FLT_PREOP_CALLBACK_STATUS status = FLT_PREOP_SUCCESS_NO_CALLBACK; ULONG Options = 0;//记录操作类型 1创建,2重命名,3删除 BOOLEAN isAllow = TRUE;//是否放行 UNREFERENCED_PARAMETER(Data); UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(CompletionContext); if (isOpenFilter) { //UNREFERENCED_PARAMETER(FltObjects); if (FQDRVData.ClientPort == NULL) { return FLT_PREOP_SUCCESS_NO_CALLBACK; } if (FQDRVData.UserProcess == PsGetCurrentProcess()) { return FLT_PREOP_SUCCESS_NO_CALLBACK; } /* lpIrpStack->Parameters.SetFile.FileInformationClass == FileRenameInformation ||//重命名 lpIrpStack->Parameters.SetFile.FileInformationClass == FileBasicInformation || //设置基础信息 lpIrpStack->Parameters.SetFile.FileInformationClass == FileAllocationInformation || lpIrpStack->Parameters.SetFile.FileInformationClass == FileEndOfFileInformation ||//设置大小 lpIrpStack->Parameters.SetFile.FileInformationClass == FileDispositionInformation)//删除 */ if (Data->Iopb->Parameters.SetFileInformation.FileInformationClass == FileRenameInformation || Data->Iopb->Parameters.SetFileInformation.FileInformationClass == FileDispositionInformation) { switch (Data->Iopb->Parameters.SetFileInformation.FileInformationClass) { case FileRenameInformation: Options = 2; break; case FileDispositionInformation: Options = 3; break; default: Options = 0;// break; } //判断是不是我们要监控的 if (!isNeedWatchFile(Data)) { return FLT_PREOP_SUCCESS_NO_CALLBACK; } if (Options == 2) { if (isRecycle(Data, FltObjects)) { return FLT_PREOP_SUCCESS_NO_CALLBACK; } } //进程路径,操作类型,原路径,重命名后路径 FQDRVpScanFileInUserMode(FltObjects->Instance, FltObjects->FileObject, Data, Options, &isAllow); if (!isAllow) { DbgPrint("ReName in PreSetInforMation被拒绝 !\n"); Data->IoStatus.Status = STATUS_ACCESS_DENIED; Data->IoStatus.Information = 0; status = FLT_PREOP_COMPLETE; } else { status = FLT_PREOP_SUCCESS_NO_CALLBACK; } } } return status; } FLT_POSTOP_CALLBACK_STATUS FQDRVPostSetInforMation( __inout PFLT_CALLBACK_DATA Data, __in PCFLT_RELATED_OBJECTS FltObjects, __in_opt PVOID CompletionContext, __in FLT_POST_OPERATION_FLAGS Flags ) { //FLT_POSTOP_CALLBACK_STATUS status = FLT_POSTOP_FINISHED_PROCESSING; //ULONG Options = 0;//记录操作类型 1创建,2重命名,3删除 //BOOLEAN isAllow = TRUE;//是否放行 UNREFERENCED_PARAMETER(Flags); UNREFERENCED_PARAMETER(Data); UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(CompletionContext); return FLT_POSTOP_FINISHED_PROCESSING; } ////////////////////////////////////////////////////////////////////////// // Local support routines. // ///////////////////////////////////////////////////////////////////////// //操作类型 1创建 2重命名 3 删除 NTSTATUS FQDRVpScanFileInUserMode( __in PFLT_INSTANCE Instance, __in PFILE_OBJECT FileObject, __in PFLT_CALLBACK_DATA Data, __in ULONG Operation, __out PBOOLEAN SafeToOpen ) { NTSTATUS status = STATUS_SUCCESS; PFQDRV_NOTIFICATION notification = NULL; ULONG replyLength = 0; PFLT_FILE_NAME_INFORMATION nameInfo; PFLT_FILE_NAME_INFORMATION pOutReNameinfo; PFILE_RENAME_INFORMATION pRenameInfo; UNREFERENCED_PARAMETER(FileObject); UNREFERENCED_PARAMETER(Instance); *SafeToOpen = TRUE; // // If not client port just return. // if (FQDRVData.ClientPort == NULL) { return STATUS_SUCCESS; } try { notification = ExAllocatePoolWithTag(NonPagedPool, sizeof(FQDRV_NOTIFICATION), 'nacS'); if (NULL == notification) { status = STATUS_INSUFFICIENT_RESOURCES; leave; } //在这里获取进程路径,操作类型,目标路径 //拷贝操作类型 notification->Operation = Operation; status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &nameInfo); //拷贝进程路径 //wcsncpy(notification->ProcessPath, uSProcessPath->Buffer, uSProcessPath->Length); if (!NT_SUCCESS(status)) { status = STATUS_INSUFFICIENT_RESOURCES; leave; } //拷贝目标路径 FltParseFileNameInformation(nameInfo); //wcsncpy(notification->ProcessPath, nameInfo->Name.Buffer, nameInfo->Name.Length); //12345 WCHAR tmp[MAX_PATH] = { 0 }; wcsncpy_s(tmp, nameInfo->Name.Length, nameInfo->Name.Buffer, nameInfo->Name.Length); GetNTLinkName(tmp,notification->ProcessPath); DbgPrint("notification->ProcessPath is %ls", notification->ProcessPath); FltReleaseFileNameInformation(nameInfo); //wcsncpy(¬ification->ProcessPath,L"test",wcslen(L"test")); status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_DEFAULT, &nameInfo); //FltGetDestinationFileNameInformation( if (!NT_SUCCESS(status)) { status = STATUS_INSUFFICIENT_RESOURCES; leave; } //拷贝目标路径 FltParseFileNameInformation(nameInfo); //这里应该注意下多线程的 if (Operation == 3) { //if (wcsncmp(g_LastDelFileName.Buffer, nameInfo->Name.Buffer, nameInfo->Name.MaximumLength) == 0) //{ // FltReleaseFileNameInformation(nameInfo); // memset(g_LastDelFileName.Buffer, '\0', MAX_PATH * 2); // *SafeToOpen = TRUE; // leave; //} wcsncpy(g_LastDelFileName.Buffer, nameInfo->Name.Buffer, nameInfo->Name.MaximumLength); } WCHAR tmp3[MAX_PATH] = { 0 }; wcsncpy_s(tmp3, nameInfo->Name.Length, nameInfo->Name.Buffer, nameInfo->Name.Length); GetNTLinkName(tmp3,notification->TargetPath); DbgPrint("notification->TargetPath is %ls", notification->TargetPath); FltReleaseFileNameInformation(nameInfo); if (Operation == 2)//重命名 { pRenameInfo = (PFILE_RENAME_INFORMATION)Data->Iopb->Parameters.SetFileInformation.InfoBuffer; status = FltGetDestinationFileNameInformation(Instance, Data->Iopb->TargetFileObject, pRenameInfo->RootDirectory, pRenameInfo->FileName, pRenameInfo->FileNameLength, FLT_FILE_NAME_NORMALIZED, &pOutReNameinfo); if (!NT_SUCCESS(status)) { DbgPrint("FltGetDestinationFileNameInformation is faild! 0x%x", status); leave; } //wcsncpy(notification->RePathName, pOutReNameinfo->Name.Buffer, pOutReNameinfo->Name.MaximumLength); //12345 WCHAR tmp1[MAX_PATH] = { 0 }; wcsncpy_s(tmp1, pOutReNameinfo->Name.Length, pOutReNameinfo->Name.Buffer, pOutReNameinfo->Name.Length); GetNTLinkName(tmp1,notification->RePathName); DbgPrint("notification->RePathName is %ls", notification->RePathName); DbgPrint("重命名:%wZ\n", &pOutReNameinfo->Name); FltReleaseFileNameInformation(pOutReNameinfo); } LARGE_INTEGER WaitTimeOut = { 0 }; replyLength = sizeof(FQDRV_REPLY); WaitTimeOut.QuadPart = -20 * 10000000; status = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, &WaitTimeOut); if (STATUS_SUCCESS == status) { *SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; } else { // // Couldn't send message // DbgPrint("!!! FQDRV.sys --- couldn't send message to user-mode to scan file, status 0x%X\n", status); } } finally{ if (NULL != notification) { ExFreePoolWithTag(notification, 'nacS'); } } return status; } NTSTATUS MessageNotifyCallback( IN PVOID PortCookie, IN PVOID InputBuffer OPTIONAL, IN ULONG InputBufferLength, OUT PVOID OutputBuffer OPTIONAL, IN ULONG OutputBufferLength,//用户可以接受的数据的最大长度. OUT PULONG ReturnOutputBufferLength) { NTSTATUS status = 0; WCHAR buffer[MAX_PATH] = { 0 }; PAGED_CODE(); ULONG level = KeGetCurrentIrql(); RuleResult uResult = 0; UNREFERENCED_PARAMETER(PortCookie); Data *data = (Data*)InputBuffer; WCHAR rulePath[MAX_PATH] = { 0 }; WCHAR filePath[MAX_PATH] = { 0 }; WCHAR filePathHead[MAX_PATH]=L"\\??\\"; if (data->command == DEFAULT_PATH || data->command == ADD_PATH || data->command == DELETE_PATH) { GetNtDeviceName(data->filename, rulePath); DbgPrint("用户发来的信息是:%ls,GetNtDeviceName之后是%ls\n", data->filename, rulePath); } else if(data->command == DELETE_FILE) { wcscat(filePathHead, data->filename); wcscpy_s(rulePath, MAX_PATH, filePathHead); } else { wcscpy_s(rulePath, MAX_PATH, data->filename); } IOMonitorCommand command; command = data->command; WCHAR* p = rulePath; //WCHAR* p = data->filename; WCHAR cachePathTemp[MAX_PATH] = { 0 }; ULONG i = 0; while (*p) { cachePathTemp[i] = *p; i++, p++; } KdPrint(("cachePathTemp是:%ls\n", cachePathTemp)); ////cachePathTemp[i] = 0; // //申请内存构造字符串 UNICODE_STRING cachePath = { 0 }; ULONG ulLength = (i) * sizeof(WCHAR); __try { cachePath.Buffer = ExAllocatePoolWithTag(PagedPool, MAX_PATH * sizeof(WCHAR), 'PMET'); RtlZeroMemory(cachePath.Buffer, MAX_PATH * sizeof(WCHAR)); cachePath.Length = ulLength; cachePath.MaximumLength = MAX_PATH*sizeof(WCHAR); wcscpy_s(cachePath.Buffer, ulLength, cachePathTemp); } __except (EXCEPTION_EXECUTE_HANDLER) { ExFreePool(cachePath.Buffer); cachePath.Buffer = NULL; cachePath.Length = cachePath.MaximumLength = 0; return status; } DbgPrint("构建好的是%wZ\n", cachePath); switch (command) { case DEFAULT_PATH: //LockWrite(&g_fileLock); uResult=AddPathList(&cachePath,&m_pfilenames); //LockWrite(&g_fileLock); break; case ADD_PATH: //LockWrite(&g_fileLock); uResult=AddPathList(&cachePath, &m_pfilenames); //LockWrite(&g_fileLock); break; case DELETE_PATH: //LockWrite(&g_fileLock); uResult = DeletePathList(&cachePath, &m_pfilenames); //LockWrite(&g_fileLock); break; case CLOSE_PATH: isOpenFilter = 0; uResult= PAUSE_FILEMON; break; case OPEN_PATH: isOpenFilter = 1; break; case PAUSE_REGMON: isOpenReg = 0; uResult = MPAUSE_REGMON; break; case RESTART_REGMON: isOpenReg = 1; uResult = MRESTART_REGMON; break; case DEFAULT_PROCESS: uResult = AddPathList(&cachePath, &m_pProcessNames); break; case ADD_PROCESS: uResult = AddPathList(&cachePath, &m_pProcessNames); break; case DELETE_PROCESS: uResult = DeletePathList(&cachePath, &m_pProcessNames); break; case PAUSE_PROCESS: isOpenProcess = 0; uResult = MPAUSE_PROCESS; break; case RESTART_PROCESS: isOpenProcess = 1; uResult = MRESTART_PROCESS; break; case ADD_MODULE: uResult = AddPathList(&cachePath, &m_pMoudleNames); break; case DELETE_MODULE: uResult = DeletePathList(&cachePath, &m_pMoudleNames); break; case PAUSE_MODULE: isOpenModule = 0; uResult = MPAUSE_MODULE; break; case RESTART_MODULE: isOpenModule = 1; uResult = MRESTART_MODULE; break; case DELETE_FILE: //uResult = MRESTART_MODULE; DbgPrint("filePathHead is %ls\n", filePathHead); status=myDelFileDir(filePathHead); if (NT_SUCCESS(status)) { uResult = DELETE_SUCCESS; } else { uResult = DELETE_FAITH; } break; case ADD_NETREJECT: //LockWrite(&g_fileLock); uResult = AddPathList(&cachePath, &m_pNetRejectNames); //LockWrite(&g_fileLock); break; case DELETE_NETREJECT: //LockWrite(&g_fileLock); uResult = DeletePathList(&cachePath, &m_pNetRejectNames); //LockWrite(&g_fileLock); break; case PAUSE_NETMON: isOpenNet = 0; uResult = MPAUSE_NETMON; break; case RESTART_NETMON: isOpenNet = 1; uResult = MRESTART_NETMON; break; default: break; } ////释放内存 ExFreePool(cachePath.Buffer); cachePath.Buffer = NULL; cachePath.Length = cachePath.MaximumLength = 0; //返回用户信息 switch (uResult) { case ADD_SUCCESS: wcscpy_s(buffer, wcslen(L"ADD_SUCCESS")+1,L"ADD_SUCCESS"); break; case ADD_PATH_ALREADY_EXISTS: wcscpy_s(buffer, wcslen(L"ADD_PATH_ALREADY_EXISTS") + 1, L"ADD_PATH_ALREADY_EXISTS"); break; case ADD_FAITH: wcscpy_s(buffer, wcslen(L"ADD_FAITH") + 1, L"ADD_FAITH"); break; case DELETE_SUCCESS: wcscpy_s(buffer, wcslen(L"DELETE_SUCCESS") + 1, L"DELETE_SUCCESS"); break; case DELETE_PATH_NOT_EXISTS: wcscpy_s(buffer, wcslen(L"DELETE_PATH_NOT_EXISTS") + 1, L"DELETE_PATH_NOT_EXISTS"); break; case DELETE_FAITH: wcscpy_s(buffer, wcslen(L"DELETE_FAITH") + 1, L"DELETE_FAITH"); case PAUSE_FILEMON: wcscpy_s(buffer, wcslen(L"PAUSE_FILEMON") + 1, L"PAUSE_FILEMON"); case RESTART_FILEMON: wcscpy_s(buffer, wcslen(L"RESTART_FILEMON") + 1, L"RESTART_FILEMON"); break; case MPAUSE_REGMON: wcscpy_s(buffer, wcslen(L"PAUSE_REGMON") + 1, L"PAUSE_REGMON"); break; case MRESTART_REGMON: wcscpy_s(buffer, wcslen(L"RESTART_REGMON") + 1, L"RESTART_REGMON"); break; case MPAUSE_PROCESS: wcscpy_s(buffer, wcslen(L"PAUSE_PROCESS") + 1, L"PAUSE_PROCESS"); break; case MRESTART_PROCESS: wcscpy_s(buffer, wcslen(L"RESTART_PROCESS") + 1, L"RESTART_PROCESS"); break; case MPAUSE_MODULE: wcscpy_s(buffer, wcslen(L"PAUSE_MODULE") + 1, L"PAUSE_MODULE"); break; case MRESTART_MODULE: wcscpy_s(buffer, wcslen(L"RESTART_MODULE") + 1, L"RESTART_MODULE"); break; case MPAUSE_NETMON: wcscpy_s(buffer, wcslen(L"PAUSE_NETMON") + 1, L"PAUSE_NETMON"); break; case MRESTART_NETMON: wcscpy_s(buffer, wcslen(L"RESTART_NETMON") + 1, L"RESTART_NETMON"); break; default: break; } ReturnOutputBufferLength = (wcslen(buffer) + 1) * sizeof(WCHAR); RtlCopyMemory(OutputBuffer, buffer, (wcslen(buffer) + 1) * sizeof(WCHAR)); return status; } ULONG AddPathList(PUNICODE_STRING filename, pFilenames *headFilenames) { filenames * new_filename, *current, *precurrent; new_filename = ExAllocatePool(NonPagedPool, sizeof(filenames)); new_filename->filename.Buffer = (PWSTR)ExAllocatePool(NonPagedPool, filename->MaximumLength); new_filename->filename.MaximumLength = filename->MaximumLength; __try { RtlCopyUnicodeString(&new_filename->filename, filename); new_filename->pNext = NULL; if (NULL == *headFilenames) //头是空的,路径添加到头 { *headFilenames = new_filename; DbgPrint("插入成功,头是空的,路径添加到头,插入的是%wZ\n", new_filename->filename); return ADD_SUCCESS; } current = *headFilenames; while (current != NULL) { if (RtlEqualUnicodeString(&new_filename->filename, &current->filename, TRUE)) //链表中含有这个路径,返回 { RtlFreeUnicodeString(&new_filename->filename); ExFreePool(new_filename); new_filename = NULL; return ADD_PATH_ALREADY_EXISTS; } precurrent = current; current = current->pNext; } //链表中没有这个路径,添加 current = *headFilenames; while (current->pNext != NULL) { current = current->pNext; } current->pNext = new_filename; DbgPrint("插入成功,插入的是%wZ\n", new_filename->filename); return ADD_SUCCESS; } __except (EXCEPTION_EXECUTE_HANDLER) { RtlFreeUnicodeString(&new_filename->filename); ExFreePool(new_filename); new_filename = NULL; return ADD_FAITH; } } ULONG DeletePathList(PUNICODE_STRING filename, pFilenames *headFilenames) { filenames *current, *precurrent; current = precurrent = *headFilenames; while (current != NULL) { __try { if (RtlEqualUnicodeString(filename, &current->filename, TRUE)) { //判断一下是否是头,如果是头,就让头指向第二个,删掉第一个 if (current == *headFilenames) { DbgPrint("删除成功,删除的是头结点是%wZ\n", current->filename); *headFilenames = current->pNext; RtlFreeUnicodeString(&current->filename); ExFreePool(current); return DELETE_SUCCESS; } //如果不是头,删掉当前的 DbgPrint("删除成功,删除的不是头结点%wZ\n", current->filename); precurrent->pNext = current->pNext; current->pNext = NULL; RtlFreeUnicodeString(&current->filename); ExFreePool(current); return DELETE_SUCCESS; } precurrent = current; current = current->pNext; } __except (EXCEPTION_EXECUTE_HANDLER) { return DELETE_FAITH; } } return DELETE_PATH_NOT_EXISTS; } BOOLEAN searchRule(WCHAR *path, pFilenames *headFilenames) { filenames *current; current = *headFilenames; WCHAR tmpPath[MAX_PATH]={0}; while (current != NULL) { __try { WCHAR tmp[MAX_PATH] = { 0 }; wcsncpy_s(tmp, current->filename.Length, current->filename.Buffer, current->filename.Length); ToUpperString(tmp); //DbgPrint("tmp is %ls,path is %ls", tmp, path); if (IsPatternMatch(tmp, path, TRUE)) { return TRUE; } current = current->pNext; } __except (EXCEPTION_EXECUTE_HANDLER) { return FALSE; } } return FALSE; } BOOLEAN searchProcessRule(WCHAR *path, pFilenames *headFilenames) { filenames *current; current = *headFilenames; WCHAR tmpPath[MAX_PATH] = { 0 }; while (current != NULL) { __try { WCHAR tmp[MAX_PATH] = { 0 }; wcsncpy_s(tmp, current->filename.Length, current->filename.Buffer, current->filename.Length); //ToUpperString(tmp); //DbgPrint("tmp is %ls,path is %ls", tmp, path); if (!wcscmp(tmp, path)) { return TRUE; } current = current->pNext; } __except (EXCEPTION_EXECUTE_HANDLER) { return FALSE; } } return FALSE; } NTSTATUS PtRegisterInit() { NTSTATUS status = STATUS_UNSUCCESSFUL; status = CmRegisterCallback(RegistryCallback, NULL, &CmHandle); if (NT_SUCCESS(status)) DbgPrint("CmRegisterCallback SUCCESS!"); else DbgPrint("CmRegisterCallback Failed!"); return status; } NTSTATUS PtRegisterUnInit() { NTSTATUS status = STATUS_UNSUCCESSFUL; status=CmUnRegisterCallback(CmHandle); if (NT_SUCCESS(status)) DbgPrint("CmUnRegisterCallback SUCCESS!"); else DbgPrint("CmUnRegisterCallback Failed!"); return status; } BOOLEAN IsProcessName(char *string, PEPROCESS eprocess) { char xx[260] = { 0 }; strcpy(xx, PsGetProcessImageFileName(eprocess)); if (!_stricmp(xx, string)) return TRUE; else return FALSE; } BOOLEAN GetRegistryObjectCompleteName(PUNICODE_STRING pRegistryPath, PUNICODE_STRING pPartialRegistryPath, PVOID pRegistryObject) { BOOLEAN foundCompleteName = FALSE; BOOLEAN partial = FALSE; if ((!MmIsAddressValid(pRegistryObject)) || (pRegistryObject == NULL)) return FALSE; /* Check to see if the partial name is really the complete name */ if (pPartialRegistryPath != NULL) { if ((((pPartialRegistryPath->Buffer[0] == '\\') || (pPartialRegistryPath->Buffer[0] == '%')) || ((pPartialRegistryPath->Buffer[0] == 'T') && (pPartialRegistryPath->Buffer[1] == 'R') && (pPartialRegistryPath->Buffer[2] == 'Y') && (pPartialRegistryPath->Buffer[3] == '\\')))) { RtlCopyUnicodeString(pRegistryPath, pPartialRegistryPath); partial = TRUE; foundCompleteName = TRUE; } } if (!foundCompleteName) { /* Query the object manager in the kernel for the complete name */ NTSTATUS status; ULONG returnedLength; PUNICODE_STRING pObjectName = NULL; status = ObQueryNameString(pRegistryObject, (POBJECT_NAME_INFORMATION)pObjectName, 0, &returnedLength); if (status == STATUS_INFO_LENGTH_MISMATCH) { pObjectName = ExAllocatePoolWithTag(NonPagedPool, returnedLength, REGISTRY_POOL_TAG); status = ObQueryNameString(pRegistryObject, (POBJECT_NAME_INFORMATION)pObjectName, returnedLength, &returnedLength); if (NT_SUCCESS(status)) { RtlCopyUnicodeString(pRegistryPath, pObjectName); foundCompleteName = TRUE; } ExFreePoolWithTag(pObjectName, REGISTRY_POOL_TAG); } } return foundCompleteName; } NTSTATUS RegistryCallback ( IN PVOID CallbackContext, IN PVOID Argument1,//操作类型, IN PVOID Argument2//操作的结构体指针 ) { if (!isOpenReg) { return STATUS_SUCCESS; } ULONG Options = 0;//记录操作类型 4创建,5删除,6设置键值,7删除键值,8重命名键 BOOLEAN isAllow = TRUE;//是否放行 PFQDRV_NOTIFICATION notification = NULL; ULONG replyLength = 0; BOOLEAN SafeToOpen; SafeToOpen = TRUE; NTSTATUS status = STATUS_SUCCESS; long type; NTSTATUS CallbackStatus = STATUS_SUCCESS; UNICODE_STRING registryPath; registryPath.Length = 0; registryPath.MaximumLength = 2048 * sizeof(WCHAR); registryPath.Buffer = ExAllocatePoolWithTag(NonPagedPool, registryPath.MaximumLength, REGISTRY_POOL_TAG); notification = ExAllocatePoolWithTag(NonPagedPool, sizeof(FQDRV_NOTIFICATION), 'nacS'); if (NULL == notification) { CallbackStatus = STATUS_INSUFFICIENT_RESOURCES; return CallbackStatus; } if (registryPath.Buffer == NULL) return STATUS_SUCCESS; type = (REG_NOTIFY_CLASS)Argument1; switch (type) { case RegNtPreCreateKeyEx: //出现两次是因为一次是OpenKey,一次是createKey { if (IsProcessName("regedit.exe", PsGetCurrentProcess())) { GetRegistryObjectCompleteName(&registryPath, NULL, ((PREG_CREATE_KEY_INFORMATION)Argument2)->RootObject); DbgPrint("[RegNtPreCreateKeyEx]KeyPath: %wZ", &registryPath); //新键的路径 DbgPrint("[RegNtPreCreateKeyEx]KeyName: %wZ", ((PREG_CREATE_KEY_INFORMATION)Argument2)->CompleteName);//新键的名称 notification->Operation = 4; char newPath[MAX_PATH] = { 0 }; WCHAR newPath1[MAX_PATH] = { 0 }; UnicodeToChar(&registryPath, newPath); CharToWchar(newPath, newPath1); wcscpy_s(notification->ProcessPath, MAX_PATH, newPath1); char newName[MAX_PATH] = { 0 }; WCHAR newName1[MAX_PATH] = { 0 }; UnicodeToChar(((PREG_CREATE_KEY_INFORMATION)Argument2)->CompleteName, newName); CharToWchar(newName, newName1); wcscpy_s(notification->TargetPath, MAX_PATH, newName1); replyLength = sizeof(FQDRV_REPLY); status = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, NULL); if (STATUS_SUCCESS == status) { SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; if (SafeToOpen) { CallbackStatus = STATUS_SUCCESS; } else { CallbackStatus = STATUS_ACCESS_DENIED; } } //CallbackStatus = STATUS_ACCESS_DENIED; } break; } case RegNtPreDeleteKey: { if (IsProcessName("regedit.exe", PsGetCurrentProcess())) { GetRegistryObjectCompleteName(&registryPath, NULL, ((PREG_DELETE_KEY_INFORMATION)Argument2)->Object); DbgPrint("[RegNtPreDeleteKey]%wZ", &registryPath); //新键的路径 notification->Operation = 5; char newPath[MAX_PATH] = { 0 }; WCHAR newPath1[MAX_PATH] = { 0 }; UnicodeToChar(&registryPath, newPath); CharToWchar(newPath, newPath1); wcscpy_s(notification->ProcessPath, MAX_PATH, newPath1); replyLength = sizeof(FQDRV_REPLY); status = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, NULL); if (STATUS_SUCCESS == status) { SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; if (SafeToOpen) { CallbackStatus = STATUS_SUCCESS; } else { CallbackStatus = STATUS_ACCESS_DENIED; } } //CallbackStatus = STATUS_ACCESS_DENIED; } break; } case RegNtPreSetValueKey: { if (IsProcessName("regedit.exe", PsGetCurrentProcess())) { GetRegistryObjectCompleteName(&registryPath, NULL, ((PREG_SET_VALUE_KEY_INFORMATION)Argument2)->Object); DbgPrint("[RegNtPreSetValueKey]KeyPath: %wZ", &registryPath); DbgPrint("[RegNtPreSetValueKey]ValName: %wZ", ((PREG_SET_VALUE_KEY_INFORMATION)Argument2)->ValueName); notification->Operation = 6; char newPath[MAX_PATH] = { 0 }; WCHAR newPath1[MAX_PATH] = { 0 }; UnicodeToChar(&registryPath, newPath); CharToWchar(newPath, newPath1); wcscpy_s(notification->ProcessPath, MAX_PATH, newPath1); char newName[MAX_PATH] = { 0 }; WCHAR newName1[MAX_PATH] = { 0 }; UnicodeToChar(((PREG_SET_VALUE_KEY_INFORMATION)Argument2)->ValueName, newName); CharToWchar(newName, newName1); wcscpy_s(notification->TargetPath, MAX_PATH, newName1); replyLength = sizeof(FQDRV_REPLY); status = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, NULL); if (STATUS_SUCCESS == status) { SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; if (SafeToOpen) { CallbackStatus = STATUS_SUCCESS; } else { CallbackStatus = STATUS_ACCESS_DENIED; } } //CallbackStatus = STATUS_ACCESS_DENIED; } break; } case RegNtPreDeleteValueKey: { if (IsProcessName("regedit.exe", PsGetCurrentProcess())) { GetRegistryObjectCompleteName(&registryPath, NULL, ((PREG_DELETE_VALUE_KEY_INFORMATION)Argument2)->Object); DbgPrint("[RegNtPreDeleteValueKey]KeyPath: %wZ", &registryPath); DbgPrint("[RegNtPreDeleteValueKey]ValName: %wZ", ((PREG_DELETE_VALUE_KEY_INFORMATION)Argument2)->ValueName); notification->Operation = 7; char newPath[MAX_PATH] = { 0 }; WCHAR newPath1[MAX_PATH] = { 0 }; UnicodeToChar(&registryPath, newPath); CharToWchar(newPath, newPath1); wcscpy_s(notification->ProcessPath, MAX_PATH, newPath1); char newName[MAX_PATH] = { 0 }; WCHAR newName1[MAX_PATH] = { 0 }; UnicodeToChar(((PREG_DELETE_VALUE_KEY_INFORMATION)Argument2)->ValueName, newName); CharToWchar(newName, newName1); wcscpy_s(notification->TargetPath, MAX_PATH, newName1); replyLength = sizeof(FQDRV_REPLY); status = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, NULL); if (STATUS_SUCCESS == status) { SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; if (SafeToOpen) { CallbackStatus = STATUS_SUCCESS; } else { CallbackStatus = STATUS_ACCESS_DENIED; } } //CallbackStatus = STATUS_ACCESS_DENIED; } break; } case RegNtPreRenameKey: { if (IsProcessName("regedit.exe", PsGetCurrentProcess())) { GetRegistryObjectCompleteName(&registryPath, NULL, ((PREG_RENAME_KEY_INFORMATION)Argument2)->Object); DbgPrint("[RegNtPreRenameKey]KeyPath: %wZ", &registryPath); DbgPrint("[RegNtPreRenameKey]NewName: %wZ", ((PREG_RENAME_KEY_INFORMATION)Argument2)->NewName); notification->Operation = 8; char newPath[MAX_PATH] = { 0 }; WCHAR newPath1[MAX_PATH] = { 0 }; UnicodeToChar(&registryPath, newPath); CharToWchar(newPath, newPath1); wcscpy_s(notification->ProcessPath, MAX_PATH, newPath1); char newName[MAX_PATH] = { 0 }; WCHAR newName1[MAX_PATH] = { 0 }; UnicodeToChar(((PREG_RENAME_KEY_INFORMATION)Argument2)->NewName, newName); CharToWchar(newName, newName1); wcscpy_s(notification->TargetPath, MAX_PATH, newName1); replyLength = sizeof(FQDRV_REPLY); status = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, NULL); if (STATUS_SUCCESS == status) { SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; if (SafeToOpen) { CallbackStatus = STATUS_SUCCESS; } else { CallbackStatus = STATUS_ACCESS_DENIED; } } //CallbackStatus = STATUS_ACCESS_DENIED; } break; } //『注册表编辑器』里的“重命名键值”是没有直接函数的,是先SetValueKey再DeleteValueKey default: break; } if (NULL != notification) { ExFreePoolWithTag(notification, 'nacS'); } if (registryPath.Buffer != NULL) ExFreePoolWithTag(registryPath.Buffer, REGISTRY_POOL_TAG); return CallbackStatus; } PWCHAR GetProcessNameByProcessId(HANDLE ProcessId) { NTSTATUS st = STATUS_UNSUCCESSFUL; PEPROCESS ProcessObj = NULL; PWCHAR string = NULL; st = PsLookupProcessByProcessId(ProcessId, &ProcessObj); if (NT_SUCCESS(st)) { string = PsGetProcessImageFileName(ProcessObj); ObfDereferenceObject(ProcessObj); } return string; } VOID MyCreateProcessNotifyEx ( __inout PEPROCESS Process, __in HANDLE ProcessId, __in_opt PPS_CREATE_NOTIFY_INFO CreateInfo ) { if (isOpenProcess) { NTSTATUS st = 0; HANDLE hProcess = NULL; OBJECT_ATTRIBUTES oa = { 0 }; CLIENT_ID ClientId = { 0 }; char xxx[16] = { 0 }; ULONG Options = 0;//9进程创建 BOOLEAN isAllow = TRUE;//是否放行 PFQDRV_NOTIFICATION notification = NULL; BOOLEAN SafeToOpen; SafeToOpen = TRUE; BOOLEAN scanFile; scanFile = TRUE; ULONG replyLength = 0; notification = ExAllocatePoolWithTag(NonPagedPool, sizeof(FQDRV_NOTIFICATION), 'nacS'); if (NULL == notification) { st = STATUS_INSUFFICIENT_RESOURCES; return st; } if (CreateInfo != NULL) //进程创建事件 { DbgPrint("进程监控[%ld]%s创建进程: %wZ", CreateInfo->ParentProcessId, GetProcessNameByProcessId(CreateInfo->ParentProcessId), CreateInfo->ImageFileName); strcpy(xxx, PsGetProcessImageFileName(Process)); WCHAR tmp[256] = { 0 }; CharToWchar(PsGetProcessImageFileName(Process), tmp); scanFile = searchProcessRule(tmp, &m_pProcessNames); if (scanFile) { notification->Operation = 9; CHAR parentProcessName[MAX_PATH] = { 0 }; WCHAR wparentProcessName[MAX_PATH] = { 0 }; strcpy_s(parentProcessName, MAX_PATH, GetProcessNameByProcessId(CreateInfo->ParentProcessId)); CharToWchar(parentProcessName, wparentProcessName); wcscpy_s(notification->ProcessPath, MAX_PATH, wparentProcessName); char processName[MAX_PATH] = { 0 }; WCHAR wProcessName[MAX_PATH] = { 0 }; UnicodeToChar(CreateInfo->ImageFileName, processName); CharToWchar(processName, wProcessName); wcscpy_s(notification->TargetPath, MAX_PATH, wProcessName); replyLength = sizeof(FQDRV_REPLY); st = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, NULL); if (STATUS_SUCCESS == st) { SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; if (SafeToOpen) { CreateInfo->CreationStatus = STATUS_SUCCESS; } else { CreateInfo->CreationStatus = STATUS_UNSUCCESSFUL; } } } } else { DbgPrint("进程监控:进程退出: %s", PsGetProcessImageFileName(Process)); } if (NULL != notification) { ExFreePoolWithTag(notification, 'nacS'); } } } NTSTATUS PtProcessInit() { NTSTATUS status = 0; status=PsSetCreateProcessNotifyRoutineEx((PCREATE_PROCESS_NOTIFY_ROUTINE_EX)MyCreateProcessNotifyEx, FALSE); if (NT_SUCCESS(status)) DbgPrint("进程监控开启 SUCCESS!"); else DbgPrint("进程监控开启 Failed!"); return status; } NTSTATUS PtProcessUnInit() { NTSTATUS status = 0; status = PsSetCreateProcessNotifyRoutineEx((PCREATE_PROCESS_NOTIFY_ROUTINE_EX)MyCreateProcessNotifyEx, TRUE); if (NT_SUCCESS(status)) DbgPrint("进程监控关闭 SUCCESS!"); else DbgPrint("进程监控关闭 Failed!"); return status; } //模块加载相关 NTSTATUS RtlSuperCopyMemory(IN VOID UNALIGNED *Dst, IN CONST VOID UNALIGNED *Src, IN ULONG Length) { //MDL是一个对物理内存的描述,负责把虚拟内存映射到物理内存 PMDL pmdl = IoAllocateMdl(Dst, Length, 0, 0, NULL);//分配mdl if (pmdl == NULL) return STATUS_UNSUCCESSFUL; MmBuildMdlForNonPagedPool(pmdl);//build mdl unsigned int *Mapped = (unsigned int *)MmMapLockedPages(pmdl, KernelMode);//锁住内存 if (!Mapped) { IoFreeMdl(pmdl); return STATUS_UNSUCCESSFUL; } KIRQL kirql = KeRaiseIrqlToDpcLevel(); RtlCopyMemory(Mapped, Src, Length); KeLowerIrql(kirql); MmUnmapLockedPages((PVOID)Mapped, pmdl); IoFreeMdl(pmdl); return STATUS_SUCCESS; } void DenyLoadDriver(PVOID DriverEntry) { UCHAR fuck[] = "\xB8\x22\x00\x00\xC0\xC3"; RtlSuperCopyMemory(DriverEntry, fuck, sizeof(fuck)); } PVOID GetDriverEntryByImageBase(PVOID ImageBase) { PIMAGE_DOS_HEADER pDOSHeader; PIMAGE_NT_HEADERS64 pNTHeader; PVOID pEntryPoint; pDOSHeader = (PIMAGE_DOS_HEADER)ImageBase; pNTHeader = (PIMAGE_NT_HEADERS64)((ULONG64)ImageBase + pDOSHeader->e_lfanew); pEntryPoint = (PVOID)((ULONG64)ImageBase + pNTHeader->OptionalHeader.AddressOfEntryPoint); return pEntryPoint; } VOID LoadImageNotifyRoutine ( __in_opt PUNICODE_STRING FullImageName, __in HANDLE ProcessId, __in PIMAGE_INFO ImageInfo ) { if (isOpenModule) { PVOID pDrvEntry; char szFullImageName[260] = { 0 }; ULONG Options = 0;//10模块加载 BOOLEAN isAllow = TRUE;//是否放行 PFQDRV_NOTIFICATION notification = NULL; BOOLEAN SafeToOpen; SafeToOpen = TRUE; BOOLEAN scanFile; ULONG replyLength = 0; NTSTATUS st = 0; if (FullImageName != NULL && MmIsAddressValid(FullImageName)) { if (ProcessId == 0) { notification = ExAllocatePoolWithTag(NonPagedPool, sizeof(FQDRV_NOTIFICATION), 'nacS'); DbgPrint("模块加载监控%wZ\n", FullImageName); pDrvEntry = GetDriverEntryByImageBase(ImageInfo->ImageBase); DbgPrint("模块加载监控 模块的DriverEntry: %p\n", pDrvEntry); UnicodeToChar(FullImageName, szFullImageName); WCHAR newPath1[MAX_PATH] = { 0 }; CharToWchar(szFullImageName, newPath1); //searchModuleRule(WCHAR *path, pFilenames *headFilenames); //if (strstr(szFullImageName, "myTestDriver.sys")) if (searchModuleRule(newPath1, &m_pMoudleNames)) { //DbgPrint("Deny load [DelDir.sys]"); //禁止加载win64ast.sys notification->Operation = 10; wcscpy_s(notification->ProcessPath, MAX_PATH, newPath1); replyLength = sizeof(FQDRV_REPLY); st = FltSendMessage(FQDRVData.Filter, &FQDRVData.ClientPort, notification, sizeof(FQDRV_NOTIFICATION), notification, &replyLength, NULL); if (STATUS_SUCCESS == st) { SafeToOpen = ((PFQDRV_REPLY)notification)->SafeToOpen; if (SafeToOpen) { DbgPrint("同意模块加载\n"); } else { DenyLoadDriver(pDrvEntry); } } } else { DbgPrint("没匹配上"); } if (NULL != notification) { ExFreePoolWithTag(notification, 'nacS'); } } } } } NTSTATUS PtModuleInit() { NTSTATUS status = 0; status = PsSetLoadImageNotifyRoutine((PLOAD_IMAGE_NOTIFY_ROUTINE)LoadImageNotifyRoutine); if (NT_SUCCESS(status)) DbgPrint("模块监控开启 SUCCESS!"); else DbgPrint("模块监控开启 Failed!"); return status; } NTSTATUS PtModuleUnInit() { NTSTATUS status = 0; status = PsRemoveLoadImageNotifyRoutine((PLOAD_IMAGE_NOTIFY_ROUTINE)LoadImageNotifyRoutine); if (NT_SUCCESS(status)) DbgPrint("模块监控关闭 SUCCESS!"); else DbgPrint("模块监控关闭 Failed!"); return status; } BOOLEAN searchModuleRule(WCHAR *path, pFilenames *headFilenames) { filenames *current; current = *headFilenames; WCHAR tmpPath[MAX_PATH] = { 0 }; while (current != NULL) { __try { WCHAR tmp[MAX_PATH] = { 0 }; wcsncpy_s(tmp, current->filename.Length, current->filename.Buffer, current->filename.Length); //ToUpperString(tmp); //DbgPrint("tmp is %ls,path is %ls", tmp, path); //if (strstr(szFullImageName, "myTestDriver.sys")) if (wcsstr(path, tmp)) { return TRUE; } current = current->pNext; } __except (EXCEPTION_EXECUTE_HANDLER) { return FALSE; } } return FALSE; } //删除文件相关 NTSTATUS myDelFile(const WCHAR* fileName) { NTSTATUS status = STATUS_SUCCESS; UNICODE_STRING uFileName = { 0 }; OBJECT_ATTRIBUTES objAttributes = { 0 }; HANDLE handle = NULL; IO_STATUS_BLOCK iosb = { 0 };//io完成情况,成功true,失败false FILE_DISPOSITION_INFORMATION disInfo = { 0 }; RtlInitUnicodeString(&uFileName, fileName); //初始化属性 InitializeObjectAttributes( &objAttributes, &uFileName, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL ); status = ZwCreateFile( &handle, SYNCHRONIZE | FILE_WRITE_ACCESS | DELETE, &objAttributes, &iosb, NULL, FILE_ATTRIBUTE_NORMAL,//普通文件,非文件夹 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT | FILE_DELETE_ON_CLOSE, NULL, 0); if (!NT_SUCCESS(status)) { if (status == STATUS_ACCESS_DENIED) { //如果访问拒绝,可能是只读的,就以没delete去打开,然后进去把属性设置成narmal在删除打开 status = ZwCreateFile( &handle, SYNCHRONIZE | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES, &objAttributes, &iosb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN, FILE_SYNCHRONOUS_IO_NONALERT, NULL, 0 ); if (NT_SUCCESS(status)) { FILE_BASIC_INFORMATION basicInfo = { 0 };//因为要修改文件属性所以床FileBasicInformation status = ZwQueryInformationFile( handle, &iosb, &basicInfo, sizeof(basicInfo),//要查什么这里就是跟其相关的结构体 FileBasicInformation ); if (!NT_SUCCESS(status)) { DbgPrint("ZwQueryInformationFile %wZ is failed %x\n", &uFileName, status); } //然后修改文件属性 basicInfo.FileAttributes = FILE_ATTRIBUTE_NORMAL; status = ZwSetInformationFile(handle, &iosb, &basicInfo, sizeof(basicInfo), FileBasicInformation); if (!NT_SUCCESS(status)) { DbgPrint("ZwSetInformationFile (%wZ) failed (%x)\n", &uFileName, status); } ZwClose(handle); status = ZwCreateFile( &handle, SYNCHRONIZE | FILE_WRITE_DATA | FILE_SHARE_DELETE, &objAttributes, &iosb, NULL, FILE_ATTRIBUTE_NORMAL, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_OPEN, FILE_SYNCHRONOUS_IO_ALERT | FILE_DELETE_ON_CLOSE, NULL, 0 ); } } if (!NT_SUCCESS(status)) { KdPrint(("ZwCreateFile(%wZ) failed(%x)\n", &uFileName, status)); return status; } } disInfo.DeleteFile = TRUE; status = ZwSetInformationFile(handle, &iosb, &disInfo, sizeof(disInfo), FileDispositionInformation); if (!NT_SUCCESS(status)) { KdPrint(("ZwSetInformationFile(%wZ) failed(%x)\n", &uFileName, status)); } ZwClose(handle); return status; } NTSTATUS myDelFileDir(const WCHAR * directory) { UNICODE_STRING uDirName = { 0 }; PWSTR nameBuffer = NULL; //记录文件夹 PFILE_LIST_ENTRY tmpEntry = NULL; //链表结点 LIST_ENTRY listHead = { 0 }; //链表,用来存放删除过程中的目录 NTSTATUS status = 0; PFILE_LIST_ENTRY preEntry = NULL; OBJECT_ATTRIBUTES objAttributes = { 0 }; HANDLE handle = NULL; IO_STATUS_BLOCK iosb = { 0 }; BOOLEAN restartScan = FALSE; PVOID buffer = NULL; ULONG bufferLength = 0; PFILE_DIRECTORY_INFORMATION dirInfo = NULL; UNICODE_STRING nameString = { 0 }; FILE_DISPOSITION_INFORMATION disInfo = { 0 }; RtlInitUnicodeString(&uDirName, directory); nameBuffer = (PWSTR)ExAllocatePoolWithTag(PagedPool, uDirName.Length + sizeof(WCHAR), 'DRID');//为了防'\0'加sizeofwchar if (!nameBuffer) { return STATUS_INSUFFICIENT_RESOURCES; } tmpEntry = (PFILE_LIST_ENTRY)ExAllocatePoolWithTag(PagedPool, sizeof(FILE_LIST_ENTRY), 'DRID'); if (!tmpEntry) { ExFreePool(nameBuffer); return STATUS_INSUFFICIENT_RESOURCES; } RtlCopyMemory(nameBuffer, uDirName.Buffer, uDirName.Length); nameBuffer[uDirName.Length / sizeof(WCHAR)] = L'\0'; InitializeListHead(&listHead);//初始化链表 tmpEntry->NameBuffer = nameBuffer; InsertHeadList(&listHead, &tmpEntry->ENTRY);//将要删除的文件夹首先插入链表 // listHead里初始化为要删除的文件夹。 //之后遍历文件夹下的文件和目录,判断是文件,则立即删除;判断是目录,则放进listHead里面 //每次都从listHead里拿出一个目录来处理 while (!IsListEmpty(&listHead)) { //先将要删除的文件夹和之前打算删除的文件夹比较一下,如果从链表里取下来的还是之前的Entry,表明没有删除成功,说明里面非空 //否则,已经成功删除,不可能是它自身;或者还有子文件夹,在前面,也不可能是它自身。 tmpEntry = (PFILE_LIST_ENTRY)RemoveHeadList(&listHead); if (preEntry == tmpEntry) { status = STATUS_DIRECTORY_NOT_EMPTY; break; } preEntry = tmpEntry; InsertHeadList(&listHead, &tmpEntry->ENTRY); //放进去,等删除了里面的内容,再移除。如果移除失败,则说明还有子文件夹或者目录非空 RtlInitUnicodeString(&nameString, tmpEntry->NameBuffer); //初始化内核对象 InitializeObjectAttributes(&objAttributes, &nameString, OBJ_CASE_INSENSITIVE, NULL, NULL); //打开文件,查询 status = ZwCreateFile( &handle, FILE_ALL_ACCESS, &objAttributes, &iosb, NULL, 0, FILE_SHARE_VALID_FLAGS, FILE_OPEN, FILE_SYNCHRONOUS_IO_ALERT, NULL, 0 ); if (!NT_SUCCESS(status)) { DbgPrint("ZwCreateFile(%ws) failed(%x)\n", tmpEntry->NameBuffer, status); break; } //从第一个扫描 restartScan = TRUE;//这是里面一个属性里面要改false不然ZwQueryDirectoryFile每次从第一个开始 while (TRUE) //遍历从栈上摘除的文件夹 { buffer = NULL; bufferLength = 64;//后面指数扩大 status = STATUS_BUFFER_OVERFLOW; while ((status == STATUS_BUFFER_OVERFLOW) || (status == STATUS_INFO_LENGTH_MISMATCH))//不断分配内存,直到够大 { if (buffer) { ExFreePool(buffer); } bufferLength *= 2; buffer = ExAllocatePoolWithTag(PagedPool, bufferLength, 'DRID'); if (!buffer) { KdPrint(("ExAllocatePool failed\n")); status = STATUS_INSUFFICIENT_RESOURCES; break; } status = ZwQueryDirectoryFile(handle, NULL, NULL, NULL, &iosb, buffer, bufferLength, FileDirectoryInformation, FALSE, NULL, restartScan);//False代表一次只遍历每次只返回一个文件夹,restartScan设置为true代表顺序查,如果不改成false每次都是第一个文件夹 } //上面查询完了,下面进行判断。查询结果在buffer里 //如果是空说明遍历完了 if (status == STATUS_NO_MORE_FILES) { ExFreePool(buffer); status = STATUS_SUCCESS; break; } restartScan = FALSE; if (!NT_SUCCESS(status)) { KdPrint(("ZwQueryDirectoryFile(%ws) failed(%x)\n", tmpEntry->NameBuffer, status)); if (buffer) { ExFreePool(buffer); } break; } dirInfo = (PFILE_DIRECTORY_INFORMATION)buffer; //申请一块内存保存当前文件夹路径和查询到子目录拼接在一起的完整目录 nameBuffer = (PWSTR)ExAllocatePoolWithTag(PagedPool, wcslen(tmpEntry->NameBuffer) * sizeof(WCHAR) + dirInfo->FileNameLength + 4, 'DRID'); if (!nameBuffer) { KdPrint(("ExAllocatePool failed\n")); ExFreePool(buffer); status = STATUS_INSUFFICIENT_RESOURCES; break; } //tmpEntry->NameBuffer是当前文件夹路径 //下面的操作在拼接文件夹下面的文件路径 RtlZeroMemory(nameBuffer, wcslen(tmpEntry->NameBuffer) * sizeof(WCHAR) + dirInfo->FileNameLength + 4); wcscpy(nameBuffer, tmpEntry->NameBuffer); wcscat(nameBuffer, L"\\"); RtlCopyMemory(&nameBuffer[wcslen(nameBuffer)], dirInfo->FileName, dirInfo->FileNameLength); RtlInitUnicodeString(&nameString, nameBuffer); if (dirInfo->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) { //如果是非'.'和'..'两个特殊的目录,则将目录放入listHead if ((dirInfo->FileNameLength == sizeof(WCHAR)) && (dirInfo->FileName[0] == L'.')) { } else if ((dirInfo->FileNameLength == sizeof(WCHAR) * 2) && (dirInfo->FileName[0] == L'.') && (dirInfo->FileName[1] == L'.')) { } else { //将文件夹插入listHead中 PFILE_LIST_ENTRY localEntry; localEntry = (PFILE_LIST_ENTRY)ExAllocatePoolWithTag(PagedPool, sizeof(FILE_LIST_ENTRY), 'DRID'); if (!localEntry) { KdPrint(("ExAllocatePool failed\n")); ExFreePool(buffer); ExFreePool(nameBuffer); status = STATUS_INSUFFICIENT_RESOURCES; break; } localEntry->NameBuffer = nameBuffer; nameBuffer = NULL; InsertHeadList(&listHead, &localEntry->ENTRY); //插入头部,先把子文件夹里的删除 } } else//如果是文件,直接删除 { status = myDelFile(nameBuffer); if (!NT_SUCCESS(status)) { KdPrint(("dfDeleteFile(%wZ) failed(%x)\n", &nameString, status)); ExFreePool(buffer); ExFreePool(nameBuffer); break; } } ExFreePool(buffer); if (nameBuffer) { ExFreePool(nameBuffer); }//继续在循环里处理下一个子文件或者子文件夹 }// while (TRUE) ,一直弄目录里的文件和文件夹 if (NT_SUCCESS(status)) { //处理完目录里的文件文件夹,再处理目录文件夹 disInfo.DeleteFile = TRUE; status = ZwSetInformationFile(handle, &iosb, &disInfo, sizeof(disInfo), FileDispositionInformation); if (!NT_SUCCESS(status)) { KdPrint(("ZwSetInformationFile(%ws) failed(%x)\n", tmpEntry->NameBuffer, status)); } } ZwClose(handle); if (NT_SUCCESS(status)) { //删除成功,从链表里移出该目录 RemoveEntryList(&tmpEntry->ENTRY); ExFreePool(tmpEntry->NameBuffer); ExFreePool(tmpEntry); } //如果失败,则表明在文件夹还有子文件夹,继续先删除子文件夹 }// while (!IsListEmpty(&listHead)) while (!IsListEmpty(&listHead)) { tmpEntry = (PFILE_LIST_ENTRY)RemoveHeadList(&listHead); ExFreePool(tmpEntry->NameBuffer); ExFreePool(tmpEntry); } return status; } <file_sep>/CHipsManager.cpp // CHipsManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "CHipsManager.h" #include "afxdialogex.h" #include "CFileManager.h" // CHipsManager 对话框 extern pFileRule g_ModuleRule; IMPLEMENT_DYNAMIC(CHipsManager, CDialogEx) CHipsManager::CHipsManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_HIPS_MANAGER, pParent) , m_ModuleRule(_T("")) , m_ruleState(_T("")) { } CHipsManager::~CHipsManager() { } void CHipsManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT1, m_ModuleRule); DDX_Text(pDX, IDC_EDIT2, m_ruleState); DDX_Control(pDX, IDC_LIST1, m_listCtrl); } BEGIN_MESSAGE_MAP(CHipsManager, CDialogEx) ON_BN_CLICKED(IDC_BUTTON_ADDRULE, &CHipsManager::OnBnClickedButtonAddrule) ON_BN_CLICKED(IDC_BUTTON_DELRULE, &CHipsManager::OnBnClickedButtonDelrule) ON_BN_CLICKED(IDC_BUTTON_PAUSEMOUDLE, &CHipsManager::OnBnClickedButtonPausemoudle) ON_BN_CLICKED(IDC_BUTTON_RESTARTMOUDLE, &CHipsManager::OnBnClickedButtonRestartmoudle) END_MESSAGE_MAP() // CHipsManager 消息处理程序 void CHipsManager::OnBnClickedButtonAddrule() { // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_ModuleRule.GetBuffer(); AddToDriver(p, ADD_MODULE); int ret = AddPathList(p, &g_ModuleRule); int iLine = 0; if (ret) { iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, p); } switch (ret) { case 1: m_ruleState = L"添加监控模块成功"; break; case 2: m_ruleState = L"添加监控模块失败,已经存在"; break; case 3: default: m_ruleState = L"添加监控模块失败"; break; } UpdateData(FALSE); writeToMoudleMonFile(); } void CHipsManager::OnBnClickedButtonDelrule() { // TODO: Add your control notification handler code here // TODO: Add your control notification handler code here UpdateData(TRUE); WCHAR * p = m_ModuleRule.GetBuffer(); DeleteFromDriver(p, DELETE_MODULE); int ret = DeletePathList(p, &g_ModuleRule); int iLine = 0; if (ret == 1) { while (m_listCtrl.DeleteItem(0)); pFileRule new_filename, current, precurrent; current = precurrent = g_ModuleRule; while (current != NULL) { int iLine = m_listCtrl.GetItemCount(); m_listCtrl.InsertItem(iLine, current->filePath); current = current->pNext; } UpdateData(FALSE); } switch (ret) { case 1: m_ruleState = L"删除监控模块成功"; break; case 2: m_ruleState = L"删除监控模块失败,不存在"; break; case 3: default: m_ruleState = L"删除监控模块失败"; break; } UpdateData(FALSE); writeToMoudleMonFile(); } bool writeToMoudleMonFile() { FILE *fp; _wfopen_s(&fp, L".\\MODULERULE.txt", L"w+"); if (fp == NULL) return FALSE; pFileRule new_filename, current, precurrent; current = precurrent = g_ModuleRule; while (current != NULL) { fputws(current->filePath, fp); if (current->pNext != NULL) { fputwc('\n', fp); } current = current->pNext; } fclose(fp); return true; } void CHipsManager::OnBnClickedButtonPausemoudle() { // TODO: Add your control notification handler code here Data data; void *pData = NULL; data.command = PAUSE_MODULE; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } void CHipsManager::OnBnClickedButtonRestartmoudle() { // TODO: Add your control notification handler code here Data data; void *pData = NULL; data.command = RESTART_MODULE; pData = &data.command; HRESULT hResult = SendToDriver(pData, sizeof(data)); if (IS_ERROR(hResult)) { OutputDebugString(L"FilterSendMessage fail!\n"); } else { OutputDebugString(L"FilterSendMessage is ok!\n"); } } BOOL CHipsManager::OnInitDialog() { CDialogEx::OnInitDialog(); m_listCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT); m_listCtrl.InsertColumn(0, _T("模块监控"), LVCFMT_LEFT, 240); FILE *fp; int iLine = 0; _wfopen_s(&fp, L".\\MODULERULE.txt", L"a+"); if (fp == NULL) return FALSE; while (!feof(fp)) { int ret = 0; WCHAR p[MAX_PATH] = { 0 }; WCHAR *p1; fgetws(p, MAX_PATH, fp); p1 = NopEnter(p); m_listCtrl.InsertItem(iLine, p1); } fclose(fp); // TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } <file_sep>/CRegeditManager.cpp // CRegeditManager.cpp: 实现文件 // #include "stdafx.h" #include "FQHIPS.h" #include "CRegeditManager.h" #include "afxdialogex.h" #include "CFileManager.h" // CRegeditManager 对话框 IMPLEMENT_DYNAMIC(CRegeditManager, CDialogEx) CRegeditManager::CRegeditManager(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_DIALOG_REGEDIT_MANAGER, pParent) , m_szUNC(_T("")) , m_szLocal(_T("")) { } CRegeditManager::~CRegeditManager() { } void CRegeditManager::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Text(pDX, IDC_EDIT_UNC, m_szUNC); DDX_Text(pDX, IDC_EDIT_LOCAL, m_szLocal); } BEGIN_MESSAGE_MAP(CRegeditManager, CDialogEx) ON_BN_CLICKED(IDC_BUTTON_U2L, &CRegeditManager::OnBnClickedButtonU2l) ON_BN_CLICKED(IDC_BUTTON_STARTREG, &CRegeditManager::OnBnClickedButtonStartreg) ON_BN_CLICKED(IDC_BUTTON_STOPREG, &CRegeditManager::OnBnClickedButtonStopreg) END_MESSAGE_MAP() // CRegeditManager 消息处理程序 void CRegeditManager::OnBnClickedButtonU2l() { // TODO: 在此添加控件通知处理程序代码 UpdateData(TRUE); } void CRegeditManager::OnBnClickedButtonStartreg() { // TODO: Add your control notification handler code here RenewRegMon(); } void CRegeditManager::OnBnClickedButtonStopreg() { // TODO: Add your control notification handler code here PauseRegMon(); }
43db39a5dfacc61d26c5d62dde92076bb8a2fe5a
[ "C", "C++" ]
25
C
iamasbcx/myHips
5a29e7d8e8ca713a9b22eefcd1b2858b795ed194
04c458deb584d17571da64103be1150c9b07daa2
refs/heads/master
<file_sep>package nju.androidchat.client.component; import android.app.AlertDialog; import android.content.Context; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ImageSpan; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.StyleableRes; import java.io.IOException; import java.util.UUID; import lombok.Setter; import nju.androidchat.client.R; public class ItemTextSend extends LinearLayout implements View.OnLongClickListener { @StyleableRes int index0 = 0; private TextView textView; private Context context; private UUID messageId; @Setter private OnRecallMessageRequested onRecallMessageRequested; private final static String img_pattern = "!\\[.+\\]\\(.+\\)"; public ItemTextSend(Context context, String text, UUID messageId, OnRecallMessageRequested onRecallMessageRequested) { super(context); this.context = context; inflate(context, R.layout.item_text_send, this); this.textView = findViewById(R.id.chat_item_content_text); this.messageId = messageId; this.onRecallMessageRequested = onRecallMessageRequested; this.setOnLongClickListener(this); setText(text); } public String getText() { return textView.getText().toString(); } public void setText(String text) { if (text.matches(img_pattern)) { Runnable runnable = () -> { SpannableString spannableString = new SpannableString(" "); String url = text.substring(text.indexOf("(") + 1, text.length() - 1); System.out.println(url); try { Drawable drawable = Drawable.createFromStream(new java.net.URL(url).openStream(), null); drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 5, drawable.getIntrinsicHeight() * 5); spannableString.setSpan(new ImageSpan(drawable), 1, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } catch (IOException e) { e.printStackTrace(); } Message msg = new Message(); msg.obj = spannableString; handler.sendMessage(msg); }; String str = text.substring(text.indexOf("[") + 1, text.indexOf("]")); textView.setText(str); new Thread(runnable).start(); } else { textView.setText(text); } } private Handler handler = new Handler(msg -> { SpannableString spannableString = (SpannableString) msg.obj; textView.setText(spannableString); return true; }); @Override public boolean onLongClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("确定要撤回这条消息吗?") .setPositiveButton("是", (dialog, which) -> { if (onRecallMessageRequested != null) { onRecallMessageRequested.onRecallMessageRequested(this.messageId); } }) .setNegativeButton("否", ((dialog, which) -> { })) .create() .show(); return true; } } <file_sep>package nju.androidchat.client.component; import android.app.AlertDialog; import android.content.Context; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ImageSpan; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import androidx.annotation.StyleableRes; import java.io.IOException; import java.util.UUID; import nju.androidchat.client.R; public class ItemTextReceive extends LinearLayout { @StyleableRes int index0 = 0; private TextView textView; private Context context; private UUID messageId; private OnRecallMessageRequested onRecallMessageRequested; private final static String img_pattern = "!\\[.+\\]\\(.+\\)"; public ItemTextReceive(Context context, String text, UUID messageId) { super(context); this.context = context; inflate(context, R.layout.item_text_receive, this); this.textView = findViewById(R.id.chat_item_content_text); this.messageId = messageId; setText(text); } public void init(Context context) { } public String getText() { return textView.getText().toString(); } public void setText(String text) { if (text.matches(img_pattern)) { Runnable runnable = () -> { SpannableString spannableString = new SpannableString(" "); String url = text.substring(text.indexOf("(") + 1, text.length() - 1); System.out.println(url); try { Drawable drawable = Drawable.createFromStream(new java.net.URL(url).openStream(), null); drawable.setBounds(0, 0, drawable.getIntrinsicWidth() * 5, drawable.getIntrinsicHeight() * 5); spannableString.setSpan(new ImageSpan(drawable), 1, 2, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); } catch (IOException e) { e.printStackTrace(); } Message msg = new Message(); msg.obj = spannableString; handler.sendMessage(msg); }; String str = text.substring(text.indexOf("[") + 1, text.indexOf("]")); textView.setText(str); new Thread(runnable).start(); } else { textView.setText(text); } } private Handler handler = new Handler(msg -> { SpannableString spannableString = (SpannableString) msg.obj; textView.setText(spannableString); return true; }); }
d52e07534664d8a856941f5c2f924a96558cfd77
[ "Java" ]
2
Java
Skoze/android-chat-in-4-patterns
124a9883bcf737190a190818fd9ac0ad8f5e1e72
be284e1f068925c1f593c9d8537603120e3dedae
refs/heads/master
<repo_name>striverLiu/douyuMsg<file_sep>/routes/users.js var express = require('express'); var router = express.Router(); const nodemailer = require('nodemailer') const { getDouyuRoomInfoByRoomId,getTelArr,sendMail } = require('../uti/util.js') const config = require('../config/config.js') var fs = require('fs'); var path = require('path') var svgCaptcha = require('svg-captcha') let num = Math.random().toString().slice(-6) var response = { Code: '', Msg: '', Data: '' } /* GET users listing. */ router.post('/getdata', function(req, res, next) { var list_data = fs.readFileSync(path.join(__dirname, "../listData.json")) list_data = JSON.parse(list_data) var obj = { phone: req.body.tel, roomId: req.body.roomId, }; var zbRoom = req.body.zbRoom // 判断是否超出订阅上限 var isMost = getTelArr() var isDy = false for(var i in isMost.telList){ if(req.body.tel == isMost.telList[i].el){ if(isMost.telList[i].room.length == 6){ isDy = true break; } } } if(isDy){ response.Code = '502' response.Msg = '订阅超出上限,一个手机号只允许订阅六个主播' response.Data = '' res.end(JSON.stringify(response)) return; } var tem = false if(list_data.list.length >= 1){ for(var i in list_data.list){ if(obj.phone == list_data.list[i].phone && obj.roomId == list_data.list[i].roomId){ tem = true break; } } if(tem){ response.Code = '501' response.Msg = '此手机号已订阅过相同主播,请勿重复订阅' response.Data = '' res.end(JSON.stringify(response)) return; } } list_data.list.push(obj) fs.writeFileSync('listData.json', JSON.stringify(list_data, null, '\t')); response.Code = '200' response.Msg = '处理成功' response.Data = getTelArr() res.end(JSON.stringify(response)) // 邮件提醒设置 nodemailer.createTestAccount((err, account) => { // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport(config.transporter) // 开启循环监听 getSMS(transporter) }) function getSMS(transporter){ // 配置发送邮件信息 const mailOptions = Object.assign(config.emailDetail, { subject: `新用户关注提醒`, // 邮箱标题 text: `手机号${obj.phone}斗鱼用户关注了-${zbRoom}-房间号为${obj.roomId}` // 邮箱内容 }) // 发送邮件 sendMail(transporter, mailOptions) } }); router.post('/search', function(req, res, next) { let roomID = req.body.roomID getDouyuRoomInfoByRoomId(roomID).then((reslut)=>{ response.Code = '200' response.Msg = '处理成功' response.Data = reslut.data res.end(JSON.stringify(response)) }).catch((err)=>{ response.Code = '500' response.Msg = '系统错误' response.Data = err res.end(JSON.stringify(response)) }) }); // 发送图形验证码 router.get('/imgCode', function (req, res) { var codeConfig = { size: 4,// 验证码长度 ignoreChars: '0o1i', // 验证码字符中排除 0o1i noise: 5, // 干扰线条的数量 height: 35, width:102 } var captcha = svgCaptcha.create(codeConfig) response.Code = '200' response.Msg = '处理成功' response.Data = captcha res.type('svg'); res.status(200).end(JSON.stringify(response)) }) // 发送验证码 router.post('/send', function (req, res) { /** * 云通信基础能力业务短信发送、查询详情以及消费消息示例,供参考。 * Created on 2017-07-31 */ const SMSClient = require('@alicloud/sms-sdk') // ACCESS_KEY_ID/ACCESS_KEY_SECRET 根据实际申请的账号信息进行替换 const accessKeyId = '<KEY>' const secretAccessKey = 'yY4C69LFHRoeL281oief4qorEbUgPg' // 初始化sms_client let smsClient = new SMSClient({accessKeyId, secretAccessKey}) // 发送短信 // console.log(req.body.phone) var phone = req.body.tel smsClient.sendSMS({ PhoneNumbers: req.body.tel, SignName: '柳建聪', TemplateCode: 'SMS_139435277', TemplateParam: '{"code": ' + num + ' }' }).then(function (respon) { let {Code} = respon if (Code === 'OK') { response.Code = '200' response.Msg = '发送成功' response.Data = { 'phone':phone, 'num':num } res.end(JSON.stringify(response)) }else{ res.end(JSON.stringify(respon)) } }, function (err) { res.end(JSON.stringify(err)) }) }) module.exports = router; <file_sep>/index.js const nodemailer = require('nodemailer') const { sleep, getAllDouyuRoomInfoPromise, sendMail,sendMsg } = require('./uti/util.js') const config = require('./config/config.js') var fs = require('fs'); var path = require('path') // var listArr = [] var listObj = {} function getArr(){ // 立即执行函数,获取所有的房间号并判断是否开播状态 var listData = fs.readFileSync(path.join(__dirname, "./listData.json")) listData = JSON.parse(listData) var temArr = []; if(listData.list.length > 0){ for(var i in listData.list){ temArr.push(listData.list[i].roomId) } } function unique(arr){ var newArr = []; arr.forEach(function(item){ if(newArr.indexOf(item) === -1){ newArr.push(item); } }); return newArr; } listObj = { 'listArr':unique(temArr), 'allData':listData } }; let preStreamState = {} // 主播之前的开播状态 nodemailer.createTestAccount((err, account) => { // create reusable transporter object using the default SMTP transport let transporter = nodemailer.createTransport(config.transporter) // 开启循环监听 monitor(transporter) }) // 监听房间状态 async function monitor(transporter) { getArr(); // console.log(listObj.allData.list) try { console.log(listObj.listArr) const resultArray = await getAllDouyuRoomInfoPromise(listObj.listArr) for (let value of resultArray) { const { data: { data: roomInfo, error: errorCode } } = value // 判断状态 if (errorCode !== 0 ) { throw new Error(roomInfo) } // 判断是否开播 // "1" - 开播 , "2" - 未开播 if (roomInfo.room_status === '1') { var temTelArr = [] var getTel = listObj.allData.list for(var i in getTel){ if(roomInfo.room_id == getTel[i].roomId){ temTelArr.push(getTel[i].phone) } } console.log(`${roomInfo.owner_name} ---- 已经开播 ---- ${roomInfo.start_time}`) if (!preStreamState[roomInfo.room_id]) { // 配置发送邮件信息 // const mailOptions = Object.assign(config.emailDetail, { // subject: roomInfo.owner_name, // 邮箱标题 // text: roomInfo.room_name + roomInfo.start_time // 邮箱内容 // }) // 发送邮件 // sendMail(transporter, mailOptions) // 获取订阅的手机号 sendMsg(`${roomInfo.owner_name}`,temTelArr) preStreamState[roomInfo.room_id] = true } } else { console.log(`${roomInfo.owner_name} ---- 未开播 ---- 上次开播时间 ---- ${roomInfo.start_time}`) preStreamState[roomInfo.room_id] = false } } } catch (error) { console.log(error) } finally { // 隔一段时间再请求 await sleep(config.delayTime) return monitor(transporter) } } // 后台的路由模板引擎 var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var index = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); // app.use(express.static(path.join(__dirname, 'public'))); app.use('/', index); app.use('/users', users); app.listen(5050, function () { console.log('应用实例,访问地址为 http://localhost:5050') }) <file_sep>/README.md # douyuMsg 斗鱼主播开播短信提醒订阅服务 ## 先进行npm install ## 然后npm start
9f5d9cab986071d7ed597d30ec744dbdcb886102
[ "JavaScript", "Markdown" ]
3
JavaScript
striverLiu/douyuMsg
c1516b0d04b6cd0201a6d5c95af7fc824d30662f
3bed1d267301f04247975ccb881e94381d035113
refs/heads/master
<repo_name>Shitij-Khanna/ReactRedux<file_sep>/myapp/src/Ninjas.js import React from 'react'; const Ninjas = (props) => { const {ninjas, deleteNinja} = props; // const ninjaList = ninjas.map(ninja => { // if(ninja.age > 27){ // return ( // <div className = "ninja" key={ninja.id}> // <div>Name : {ninja.name}</div> // <div>Age : {ninja.age}</div> // <div>Belt : {ninja.belt}</div> // </div> // ) // }else{ // return null // } // }) const ninjaList = ninjas.map(ninja => { return ninja.age > 10 ? ( <div className = "ninja" key={ninja.id}> <div>Name : {ninja.name}</div> <div>Age : {ninja.age}</div> <div>Belt : {ninja.belt}</div> <button onClick={() => {deleteNinja(ninja.id)}}>Delete</button> </div> ) : null; }) return( <div className = "ninja-list"> { ninjaList } </div> ) } export default Ninjas;<file_sep>/myapp/src/App.js import React, { Component } from 'react'; import Ninjas from './Ninjas'; import AddNinja from './AddNinja' class App extends Component { state = { ninjas :[ { name : 'Shitij', age : 30, belt : 'black', id:1}, { name : 'Neha', age : 30, belt : 'white', id:2}, { name : 'Akshit', age : 27, belt : 'yellow', id:3} ] } addNinja = (ninja) => { ninja.id = Math.random(); let ninjas = [...this.state.ninjas, ninja]; this.setState({ ninjas : ninjas }) console.log("helllo", ninja); } deleteNinja = (id) => { console.log("ID: ", id); let ninjas = this.state.ninjas.filter(ninja => { return ninja.id !== id; }) this.setState({ ninjas : ninjas }) } componentDidMount(){ console.log("Component Mounted"); } componentDidUpdate(prevProps, prevState){ console.log("Component Updated"); console.log(prevProps, prevState); } render() { return ( <div className="App"> <h1>My first React App !</h1> <Ninjas ninjas = {this.state.ninjas} deleteNinja = {this.deleteNinja}/> <AddNinja addNinja={this.addNinja} /> </div> ); } } export default App;
2aea40dd36a1bca6aef8145bdfcb6ea68799067e
[ "JavaScript" ]
2
JavaScript
Shitij-Khanna/ReactRedux
a969e669bd00e8e126b745eac12aa038c5b3d285
576ac4d38601e3323c9a04ac6c3b147a4af40574
refs/heads/master
<repo_name>simonkberg/shebang<file_sep>/src/pages/404.js import * as React from 'react' import PropTypes from 'prop-types' import styled from '@emotion/styled' import Layout from '../components/layout' const Title = styled('h2')` font-size: 1rem; font-weight: bold; ` const SubTitle = styled('span')` font-weight: normal; ` const NotFoundPage = ({ location }) => ( <Layout location={location}> <Title> /dev/null <SubTitle> - 404 Not Found</SubTitle> </Title> </Layout> ) NotFoundPage.propTypes = { location: PropTypes.shape({ pathname: PropTypes.string.isRequired, }).isRequired, } export default NotFoundPage <file_sep>/gatsby-ssr.js 'use strict' /** * Implement Gatsby's SSR (Server Side Rendering) APIs in this file. * * See: https://www.gatsbyjs.org/docs/ssr-apis/ */ exports.onPreRenderHTML = ({ getHeadComponents, replaceHeadComponents }) => { replaceHeadComponents( getHeadComponents().filter( el => el.key !== 'gatsby-plugin-manifest-icon-link' ) ) } <file_sep>/gatsby-config.js 'use strict' module.exports = { siteMetadata: { siteUrl: 'https://shebang.consulting', title: 'Shebang Consulting', description: 'Fullstack web consulting, specialized in React, Node.js, and GraphQL, with a strong focus on building scalable frontend architecture.', }, plugins: [ 'gatsby-plugin-emotion', 'gatsby-plugin-react-helmet', 'gatsby-plugin-sitemap', 'gatsby-plugin-offline', 'gatsby-plugin-netlify', { resolve: 'gatsby-plugin-manifest', options: { name: 'Shebang Consulting', short_name: 'Shebang', start_url: '/', background_color: '#151515', theme_color: '#151515', display: 'minimal-ui', icon: 'src/assets/icon.png', }, }, ], } <file_sep>/readme.md # shebang.consulting ```js // TODO ``` <file_sep>/src/components/header.js import * as React from 'react' import PropTypes from 'prop-types' import { Link } from 'gatsby' import styled from '@emotion/styled' const Wrapper = styled('header')` color: #fff; background: #151515; margin-bottom: '1.45rem'; ` const Container = styled('div')` margin: 0 auto; max-width: 48rem; padding: 1.45rem 1.0875rem; ` const Title = styled('h1')` font-size: 1rem; font-weight: bold; margin: 0; text-transform: lowercase; ` const StyledLink = styled(Link)` color: #fff; text-decoration: none; ` const Header = ({ siteTitle }) => ( <Wrapper> <Container> <Title> <StyledLink to="/">#!/{siteTitle}</StyledLink> </Title> </Container> </Wrapper> ) Header.propTypes = { siteTitle: PropTypes.string.isRequired, } export default Header <file_sep>/src/pages/index.js import * as React from 'react' import PropTypes from 'prop-types' import styled from '@emotion/styled' import { graphql } from 'gatsby' import Layout from '../components/layout' const Link = styled('a')` color: inherit; ` const email = '<EMAIL>' const website = 'simon.dev' const IndexPage = ({ data, location }) => ( <Layout location={location}> <p>{data.site.siteMetadata.description}</p> <p>Located in Stockholm, Sweden.</p> <p> For inquires contact <Link href={`mailto:${email}`}>{email}</Link> or visit <Link href={`https://${website}`}>{website}</Link>. </p> </Layout> ) IndexPage.propTypes = { data: PropTypes.shape({ site: PropTypes.shape({ siteMetadata: PropTypes.shape({ description: PropTypes.string.isRequired, }).isRequired, }).isRequired, }).isRequired, location: PropTypes.shape({ pathname: PropTypes.string.isRequired, }).isRequired, } export default IndexPage export const query = graphql` query IndexPageQuery { site { siteMetadata { description } } } `
58734126cebdd0a3311fb2d9d8d87ff5aa9dfcb8
[ "JavaScript", "Markdown" ]
6
JavaScript
simonkberg/shebang
7c29db2c087e91784e61bcd7e4c10cfd37c77c86
c3ab1dcc3bcc266894df03429900c33cb92da38f
refs/heads/master
<repo_name>metrocoder/SoftwareMethodology<file_sep>/SongLib/SongLib/src/view/Controller.java package view; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.stage.Stage; import org.w3c.dom.*; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.util.Comparator; import java.util.Optional; public class Controller { private final ObservableList<Songs> songsArray = FXCollections.observableArrayList(); @FXML ListView<Songs> songListView; @FXML Button addButton, delButton, editButton; @FXML TextField inputArtist, inputSong, inputAlbum, inputYear, displayArtist, displayAlbum, displaySong,displayYear; @FXML public void start(Stage mainStage) { getXML(); songListView.setItems(songsArray); songListView.getSelectionModel().select(0); songListView.getSelectionModel() .selectedIndexProperty() .addListener( (obs, oldVal, newVal) -> showItemInputDialog(mainStage)); Stage window = mainStage; window.setOnCloseRequest(event -> createXML(songsArray)); } public void createSong(ActionEvent event) { if (inputArtist.getText().isEmpty() || inputSong.getText().isEmpty()) { Alert inputError = new Alert(Alert.AlertType.ERROR); inputError.setTitle("Try again."); inputError.setContentText("Artist and Song fields must not be empty"); inputError.showAndWait(); } else { addSong(inputSong.getText(),inputAlbum.getText(),inputYear.getText(),inputArtist.getText()); sortSongs(); } } public void deleteSong(ActionEvent event) { } private void showItemInputDialog(Stage mainStage) { Songs item = songListView.getSelectionModel().getSelectedItem(); int index = songListView.getSelectionModel().getSelectedIndex(); displayAlbum.setText(item.getAlbum()); displayArtist.setText(item.getArtist()); displaySong.setText(item.getName()); displayYear.setText(item.getYear()); // // Optional<String> result = dialog.showAndWait(); // if (result.isPresent()) { obsList.set(index, result.get()); } } /* * This method is to add the song to the SongList * * !!!!!!!!! We need to find a way to get the: * NAME, ALBUM, YEAR, ARTIST from the TEXTFIELDS * ONLY IFF they click on add * * */ public void addSong(String name, String Album, String Year, String Artist) { Songs temp = new Songs(name,Album,Year, Artist); if(songsArray.indexOf(temp)>=0) { //Means that there is a duplicate so populate ERROR popup } else { songsArray.add(temp); } } public void removeSong(String name, String Album, String Year, String Artist) { Songs temp = new Songs(name,Album,Year, Artist); if(songsArray.indexOf(temp)>=0) { songsArray.remove(songsArray.indexOf(temp));//Check if this works!!! } else { //Means that there isn't a song like that in the list so populate ERROR popup } } public void editSong(Songs old, Songs replacement) { if(songsArray.indexOf(old)>=0) { removeSong(old.getName(),old.getAlbum(),old.getYear(),old.getArtist()); addSong(replacement.getName(),replacement.getAlbum(),replacement.getYear(),replacement.getArtist()); } else { //Means that there isn't a song like that in the list so populate ERROR popup } } /* * This method is going to be used after any modifications are made to the SONGS * and BEFORE we save the LIST. * * VERY IMPORTANT PART OF THE ASSIGNMENT * */ public void sortSongs() { if (songsArray.size()==0) return; /* * Lets see if soring first by artist then by song name does the trick * * */ songsArray.sort(Comparator.comparing(Songs::getArtist)); songsArray.sort(Comparator.comparing(Songs::getName)); //Need to Loop through this sorted array list and see if there are any //name duplicates and if so sort the songs with duplicate song names by artist and swap there //respective indices in the ArrayList. /*for (int i=1;i<song.size();i++) { if (song.get(i).name.compareTo(song.get(i+1))) }*/ } /* * This method is what will be used to store the ObservableList into an XML * This needs to be called on before the EXIT of the program to store the data * to long term Memory.!!!!!!!!!!!!!!!!!!! * * ----------Accepts a ArrayList of Song objects-------------- * */ public void createXML(ObservableList<Songs> songs) { System.out.println("Saving to XML"); try { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); // root elements Document doc = docBuilder.newDocument(); Element rootElement = doc.createElement("songList"); doc.appendChild(rootElement); for(int i = 0; i<songs.size();i++) { String nameIn = songs.get(i).getName(); String artistIn = songs.get(i).getArtist(); String albumIn = songs.get(i).getAlbum(); String yearIn = songs.get(i).getYear(); // staff elements Element song = doc.createElement("Song"); rootElement.appendChild(song); // set attribute to staff element Attr attr = doc.createAttribute("id"); //attr.setValue("1"); attr.setValue(Integer.toString(i)); song.setAttributeNode(attr); // shorten way // staff.setAttribute("id", "1"); // firstname elements Element songname = doc.createElement("name"); songname.appendChild(doc.createTextNode(nameIn)); song.appendChild(songname); // lastname elements Element artist = doc.createElement("artist"); artist.appendChild(doc.createTextNode(artistIn)); song.appendChild(artist); // nickname elements Element album = doc.createElement("album"); album.appendChild(doc.createTextNode(albumIn)); song.appendChild(album); // salary elements Element year = doc.createElement("year"); year.appendChild(doc.createTextNode(yearIn)); song.appendChild(year); } // write the content into xml file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); DOMSource source = new DOMSource(doc); StreamResult result = new StreamResult(new File("file.xml")); // Output to console for testing // StreamResult result = new StreamResult(System.out); transformer.transform(source, result); System.out.println("File saved!"); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (TransformerException tfe) { tfe.printStackTrace(); } } /* * You need to call this method when program starts to populate the * LISTVIEW with the saved data. * */ public void getXML() { try { File fXmlFile = new File("file.xml"); DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document doc = dBuilder.parse(fXmlFile); //optional, but recommended //read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work doc.getDocumentElement().normalize(); // System.out.println("Root element :" + doc.getDocumentElement().getNodeName()); NodeList nList = doc.getElementsByTagName("Song"); // System.out.println("----------------------------"); String name, artist, album, year; for (int temp = 0; temp < nList.getLength(); temp++) { Node nNode = nList.item(temp); //System.out.println("\nCurrent Element :" + nNode.getNodeName()); if (nNode.getNodeType() == Node.ELEMENT_NODE) { Element eElement = (Element) nNode; //^^^^^^^^^^^^^^^^^^^^ This is for debug ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^// /*System.out.println("Song id : " + eElement.getAttribute("id")); System.out.println("Name : " + eElement.getElementsByTagName("name").item(0).getTextContent()); System.out.println("Artist : " + eElement.getElementsByTagName("artist").item(0).getTextContent()); System.out.println("Album : " + eElement.getElementsByTagName("album").item(0).getTextContent()); System.out.println("Year : " + eElement.getElementsByTagName("year").item(0).getTextContent()); */ //^^^^^^^^^^^^^^^^^^^^ This is for debug ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^// name = eElement.getElementsByTagName("name").item(0).getTextContent(); artist = eElement.getElementsByTagName("artist").item(0).getTextContent(); album = eElement.getElementsByTagName("album").item(0).getTextContent(); year = eElement.getElementsByTagName("year").item(0).getTextContent(); addSong(name,album,year,artist); } } } catch (Exception e) { e.printStackTrace(); } } } <file_sep>/README.md # SoftwareMethodology These are the assignments that were given in Software Methodology @ Rutgers University New Brunswick
f413479ce58f639680de0d221bc2be86d20d12e8
[ "Markdown", "Java" ]
2
Java
metrocoder/SoftwareMethodology
4cf607ae09c7ada0405fd2750b7ae08ad87ade6b
dcf2e3f244d8e45db21d7a06835c08ddde0ca6cf
refs/heads/master
<file_sep>/** * Created by Mine on 6/9/2016. */ 'use strict'; const Backtory = require("../../provider/LibsProvider").backtory(); var BookingDetails = Backtory.Object.extend('BookingDetails',{ getId(){return this.get(BookingDetails.Col.id)}, getUserName(){return this.get(BookingDetails.Col.userName)}, getUserId(){return this.get(BookingDetails.Col.userId)}, getPurpose(){return this.get(BookingDetails.Col.purpose)}, getPickupArea(){return this.get(BookingDetails.Col.pickupArea)}, getdropArea(){return this.get(BookingDetails.Col.dropArea)}, getPickupDateTime(){return this.get(BookingDetails.Col.pickupDateTime)}, getTaxiType(){return this.get(BookingDetails.Col.taxiType)}, getTaxiId(){return this.get(BookingDetails.Col.taxiId)}, getDepartureDateTime(){return this.get(BookingDetails.Col.departureDateTime)}, getPackage() {return this.get(BookingDetails.Col.package)}, getStatus(){return this.get(BookingDetails.Col.status)}, getStatusCode(){return this.get(BookingDetails.Col.statusCode)}, getPromoCode(){return this.get(BookingDetails.Col.promoCode)}, getBookCreateDateTime() {return this.get(BookingDetails.Col.bookCreateDateTime)}, getIsDevice() {return this.get(BookingDetails.Col.isDevice)}, getApproxTime() {return this.get(BookingDetails.Col.approxTime)}, getAmount() {return this.get(BookingDetails.Col.amount)}, getFinalAmount() {return this.get(BookingDetails.Col.finalAmount)}, getPickupAddress() {return this.get(BookingDetails.Col.pickupAddress)}, getAssignedFor() {return this.get(BookingDetails.Col.assignedFor)}, getPerson() {return this.get(BookingDetails.Col.person)}, getPaymentType() {return this.get(BookingDetails.Col.paymentType)}, getTransactionId() {return this.get(BookingDetails.Col.transactionId)}, getKm() {return this.get(BookingDetails.Col.km)}, getTimeType() {return this.get(BookingDetails.Col.timeType)}, getComment() {return this.get(BookingDetails.Col.comment)}, getDriverStatus() {return this.get(BookingDetails.Col.driverStatus)}, getPickupLat() {return this.get(BookingDetails.Col.pickupLat)}, getPickupLong() {return this.get(BookingDetails.Col.pickupLong)}, getDropLat() {return this.get(BookingDetails.Col.dropLat)}, getDropLong() {return this.get(BookingDetails.Col.dropLong)}, getFlag() {return this.get(BookingDetails.Col.flag)}, getReason() {return this.get(BookingDetails.Col.reason)}, setId(value){this.set(BookingDetails.Col.id,value)}, setUserName(value){this.set(BookingDetails.Col.userName,value)}, setUserId(value){this.set(BookingDetails.Col.userId,value)}, setPurpose(value){this.set(BookingDetails.Col.purpose,value)}, setPickupArea(value){this.set(BookingDetails.Col.pickupArea,value)}, setdropArea(value){this.set(BookingDetails.Col.dropArea,value)}, setPickupDateTime(value){this.set(BookingDetails.Col.pickupDateTime,value)}, setTaxiType(value){this.set(BookingDetails.Col.taxiType,value)}, setTaxiId(value){this.set(BookingDetails.Col.taxiId,value)}, setDepartureDateTime(value){this.set(BookingDetails.Col.departureDateTime,value)}, setPackage(value) {this.set(BookingDetails.Col.package,value)}, setStatus(value){this.set(BookingDetails.Col.status,value)}, setStatusCode(value){this.set(BookingDetails.Col.statusCode,value)}, setPromoCode(value){this.set(BookingDetails.Col.promoCode,value)}, setBookCreateDateTime(value) {this.set(BookingDetails.Col.bookCreateDateTime,value)}, setIsDevice(value) {this.set(BookingDetails.Col.isDevice,value)}, setApproxTime(value) {this.set(BookingDetails.Col.approxTime,value)}, setAmount(value) {this.set(BookingDetails.Col.amount,value)}, setFinalAmount(value) {this.set(BookingDetails.Col.finalAmount,value)}, setPickupAddress(value) {this.set(BookingDetails.Col.pickupAddress,value)}, setAssignedFor(value) {this.set(BookingDetails.Col.assignedFor,value)}, setPerson(value) {this.set(BookingDetails.Col.person,value)}, setPaymentType(value) {this.set(BookingDetails.Col.paymentType,value)}, setTransactionId(value) {this.set(BookingDetails.Col.transactionId,value)}, setKm(value) {this.set(BookingDetails.Col.km,value)}, setTimeType(value) {this.set(BookingDetails.Col.timeType,value)}, setComment(value) {this.set(BookingDetails.Col.comment,value)}, setDriverStatus(value) {this.set(BookingDetails.Col.driverStatus,value)}, setPickupLat(value) {this.set(BookingDetails.Col.pickupLat,value)}, setPickupLong(value) {this.set(BookingDetails.Col.pickupLong,value)}, setDropLat(value) {this.set(BookingDetails.Col.dropLat,value)}, setDropLong(value) {this.set(BookingDetails.Col.dropLong,value)}, setFlag(value) {this.set(BookingDetails.Col.flag,value)}, setReason(value) {this.set(BookingDetails.Col.reason,value)}, },{ get Name(){return 'BookingDetails'}, }); BookingDetails.Col = { get id(){return '_id'}, get userName(){return 'userName'}, get userId(){return 'userId'}, get purpose(){return 'purpose'}, get pickupArea(){return 'pickupArea'}, get dropArea(){return 'dropArea'}, get pickupDateTime(){return 'pickupDateTime'}, get taxiType(){return 'taxiType'}, get taxiId(){return 'taxiId'}, get departureDateTime(){return 'departureDateTime'}, get package() {return 'package'}, get status(){return 'status'}, get statusCode(){return 'statusCode'}, get promoCode(){return 'promoCode'}, get bookCreateDateTime() {return 'bookCreateDateTime'}, get isDevice() {return "isDevice"}, get approxTime() {return "approxTime"}, get amount() {return "amount"}, get finalAmount() {return "finalAmount"}, get pickupAddress() {return "pickupAddress"}, get assignedFor() {return "assignedFor"}, get person() {return "person"}, get paymentType() {return "paymentType"}, get transactionId() {return "transactionId"}, get km() {return "km"}, get timeType() {return "timeType"}, get comment() {return "comment"}, get driverStatus() {return "driverStatus"}, get pickupLat() {return "pickupLat"}, get pickupLong() {return "pickupLong"}, get dropLat() {return "dropLat"}, get dropLong() {return "dropLong"}, get flag() {return "flag"}, get reason() {return "reason"}, }; Backtory.Object.registerSubclass(BookingDetails.Name, BookingDetails); module.exports = BookingDetails;<file_sep> var runBefore = require ('../moduleGenerator/RunBeforeAspectRunner.js') var runAfter = require ('../moduleGenerator/RunAfterAspectRunner.js') var runAround = require ('../moduleGenerator/RunAroundAspectRunner.js') var originalModule = require ('../db/repo/CarTypeRepo.js') module.exports.getCarTypes = function ( skip , limit ) { var original = originalModule.getCarTypes; return original. apply( null, arguments); }; /* module.exports.getCarTypeById = function ( carTypeId ) { var original = originalModule.getCarTypeById; return original. apply( null, arguments); }; module.exports.getCarTypesByListOfId = function ( carTypeIds ) { var original = originalModule.getCarTypesByListOfId; return original. apply( null, arguments); }; module.exports.updateCarTypeRating = function ( carType , starInc , countInc ) { var original = originalModule.updateCarTypeRating; return original. apply( null, arguments); }; module.exports.saveCarType = function ( name , releaseDate , poster , director , writer , production , actors , genre , plot , runtime , country , boxOffice ) { var original = originalModule.saveCarType; return original. apply( null, arguments); }; module.exports.addAllCarTypesToDbIfNeeded = function () { var original = originalModule.addAllCarTypesToDbIfNeeded; original = runAround( original, originalModule, __dirname, "../annotationRuntimeModules/AutoWired_AspectItem_75053.js", "aspect", "{\"originalArguments\":[\"UserFavoriteRepo\",\"UserRatingRepo\"],\"autoWiredModules\":{\"UserFavoriteRepo\":{\"moduleName\":\"UserFavoriteRepo\",\"moduleAddress\":\"../generated/UserFavoriteRepo.js\"},\"UserRatingRepo\":{\"moduleName\":\"UserRatingRepo\",\"moduleAddress\":\"../generated/UserRatingRepo.js\"}}}"); return original. apply( null, arguments); }; module.exports.addAllCarTypesToDb = function () { var original = originalModule.addAllCarTypesToDb; return original. apply( null, arguments); };*/ <file_sep> 'use strict'; const Backtory = require("../../provider/LibsProvider").backtory(); var Wallet = Backtory.Object.extend('Wallet',{ getId(){return this.get(Wallet.Col.id)}, getUserName(){return this.get(Wallet.Col.userName)}, getItemNo(){return this.get(Wallet.Col.itemNo)}, getAmount(){return this.get(Wallet.Col.Amount)}, getStatus(){return this.get(Wallet.Col.status)}, setId(value){this.set(Wallet.Col.id, value)}, setUserName(value){this.set(Wallet.Col.userName, value)}, setItemNo(value){this.set(Wallet.Col.itemNo, value)}, setAmount(value){this.set(Wallet.Col.amount, value)}, setStatus(value){this.set(Wallet.Col.status, value)}, },{ get Name(){return 'Wallet'}, }); Wallet.Col = { get id(){return 'id'}, get userName(){return 'userName'}, get itemNo(){return 'itemNo'}, get amount(){return 'amount'}, get status(){return 'status'}, }; Backtory.Object.registerSubclass(Wallet.Name, Wallet); module.exports = Wallet;<file_sep> 'use strict'; const Backtory = require("../../provider/LibsProvider").backtory(); var DriverDetails = Backtory.Object.extend('DriverDetails',{ getId(){return this.get(DriverDetails.Col._id)}, getName(){return this.get(DriverDetails.Col.name)}, getUserName(){return this.get(DriverDetails.Col.userName)}, getPassword(){return this.get(DriverDetails.Col.password)}, getPhone(){return this.get(DriverDetails.Col.phone)}, getAddress(){return this.get(DriverDetails.Col.address)}, getEmail(){return this.get(DriverDetails.Col.email)}, getLicenseNo(){return this.get(DriverDetails.Col.licenseNo)}, getCarType(){return this.get(DriverDetails.Col.carType)}, getCarNo(){return this.get(DriverDetails.Col.carNo)}, getGender(){return this.get(DriverDetails.Col.gender)}, getDob(){return this.get(DriverDetails.Col.dob)}, getWalletAmount(){return this.get(DriverDetails.Col.walletAmount)}, getUserStatus() {return this.get(DriverDetails.Col.userStatus)}, getType() {return this.get(DriverDetails.Col.type)}, getRating() {return this.get(DriverDetails.Col.rating)}, getLicenseExpiryDate() {return this.get(DriverDetails.Col.licenseExpiryDate)}, getLicensePlate() {return this.get(DriverDetails.Col.licensePlate)}, getInsurance() {return this.get(DriverDetails.Col.insurance)}, getSeatingCapacity() {return this.get(DriverDetails.Col.seatingCapacity)}, getCarModel() {return this.get(DriverDetails.Col.carModel)}, getCarMake() {return this.get(DriverDetails.Col.carMake)}, getImage() {return this.get(DriverDetails.Col.image)}, getStatus() {return this.get(DriverDetails.Col.status)}, getSocketStatus() {return this.get(DriverDetails.Col.socketStatus)}, getFlag() {return this.get(DriverDetails.Col.flag)}, setId(value){this.set(DriverDetails.Col._id,value)}, setName(value){this.set(DriverDetails.Col.name,value)}, setUserName(value){this.set(DriverDetails.Col.userName,value)}, setPassword(value){this.set(DriverDetails.Col.password,value)}, setPhone(value){this.set(DriverDetails.Col.phone,value)}, setAddress(value){this.set(DriverDetails.Col.address,value)}, setEmail(value){this.set(DriverDetails.Col.email,value)}, setLicenseNo(value){this.set(DriverDetails.Col.licenseNo,value)}, setCarType(value){this.set(DriverDetails.Col.carType,value)}, setCarNo(value){this.set(DriverDetails.Col.carNo,value)}, setGender(value){this.set(DriverDetails.Col.gender,value)}, setDob(value){this.set(DriverDetails.Col.dob,value)}, setWalletAmount(value){this.set(DriverDetails.Col.walletAmount,value)}, setUserStatus(value) {this.set(DriverDetails.Col.userStatus,value)}, setType(value) {this.set(DriverDetails.Col.type,value)}, setRating(value) {this.set(DriverDetails.Col.rating,value)}, setLicenseExpiryDate(value) {this.set(DriverDetails.Col.licenseExpiryDate,value)}, setLicensePlate(value) {this.set(DriverDetails.Col.licensePlate,value)}, setInsurance(value) {this.set(DriverDetails.Col.insurance,value)}, setSeatingCapacity(value) {this.set(DriverDetails.Col.seatingCapacity,value)}, setCarModel(value) {this.set(DriverDetails.Col.carModel,value)}, setCarMake(value) {this.set(DriverDetails.Col.carMake,value)}, setImage(value) {this.set(DriverDetails.Col.image,value)}, setStatus(value) {this.set(DriverDetails.Col.status,value)}, setSocketStatus(value) {this.set(DriverDetails.Col.socketStatus,value)}, setFlag(value) {this.set(DriverDetails.Col.flag,value)}, },{ get Name(){return 'DriverDetails'}, }); DriverDetails.Col = { get _id(){return '_id'}, get name(){return 'name'}, get userName(){return 'userName'}, get password(){return '<PASSWORD>'}, get phone(){return 'phone'}, get address(){return 'address'}, get email(){return 'email'}, get licenseNo(){return 'licenseNo'}, get carType(){return 'carType'}, get carNo(){return 'carNo'}, get gender(){return 'gender'}, get dob(){return 'dob'}, get walletAmount(){return 'walletAmount'}, get userStatus(){return 'userStatus'}, get type(){return 'type'}, get rating(){return 'rating'}, get licenseExpiryDate(){return 'licenseExpiryDate'}, get licensePlate(){return 'licensePlate'}, get insurance(){return 'insurance'}, get seatingCapacity(){return 'seatingCapacity'}, get carModel(){return 'carModel'}, get carMake(){return 'carMake'}, get image(){return 'image'}, get status(){return 'status'}, get socketStatus(){return 'socketStatus'}, get flag(){return 'flag'}, }; Backtory.Object.registerSubclass(DriverDetails.Name, DriverDetails); module.exports = DriverDetails;<file_sep> 'use strict'; const Backtory = require("../../provider/LibsProvider").backtory(); var AdminLogin = Backtory.Object.extend('AdminLogin',{ getId(){return this.get(AdminLogin.Col.id)}, getName(){return this.get(AdminLogin.Col.name)}, getUserName(){return this.get(AdminLogin.Col.userName)}, getPassword(){return this.get(AdminLogin.Col.password)}, getRole(){return this.get(AdminLogin.Col.role)}, getEmail(){return this.get(AdminLogin.Col.email)}, getMobile(){return this.get(AdminLogin.Col.mobile)}, getGender(){return this.get(AdminLogin.Col.gender)}, getImage(){return this.get(AdminLogin.Col.image)}, setId(value){this.set(AdminLogin.Col.id, value)}, setName(value){this.set(AdminLogin.Col.name, value)}, setUserName(value){this.set(AdminLogin.Col.userName, value)}, setPassword(value){this.set(AdminLogin.Col.password, value)}, setRole(value){this.set(AdminLogin.Col.role, value)}, setEmail(value){this.set(AdminLogin.Col.email, value)}, setMobile(value){this.set(AdminLogin.Col.mobile, value)}, setGender(value){this.set(AdminLogin.Col.gender, value)}, setImage(value){this.set(AdminLogin.Col.image, value)}, },{ get Name(){return 'AdminLogin'}, }); AdminLogin.Col = { get id(){return '_id'}, get name(){return 'name'}, get userName(){return 'username'}, get password(){return '<PASSWORD>'}, get role(){return 'role'}, get email(){return 'email'}, get mobile(){return 'mobile'}, get gender(){return 'gender'}, get image(){return 'image'}, }; Backtory.Object.registerSubclass(AdminLogin.Name, AdminLogin); module.exports = AdminLogin;<file_sep>/** * Created by hamid on 8/12/16. */ 'use strict'; const StringField = require("../../../requestDataHandler/dataTypes/StringField"); const IntegerField = require("../../../requestDataHandler/dataTypes/IntegerField"); const ValidatableObject = require("../../../requestDataHandler/ValidatableObject"); function RegisterDriverRequest(){ this.init.apply(this, arguments); } RegisterDriverRequest.prototype = Object.create(ValidatableObject.prototype); RegisterDriverRequest.prototype.init = function(){ this.name = new StringField(true); this.userName = new StringField(true); this.phone = new StringField(true); this.email = new StringField(true); this.password = new StringField(true); this.dob = new StringField(true); this.gender = new StringField(true); this.address = new StringField(true); this.car_make = new StringField(true); this.car_model = new StringField(true); this.car_type = new IntegerField(true); this.car_no = new StringField(true); this.seating_capacity = new StringField(true); this.license_no = new StringField(true); this.license_expiry_date = new StringField(true); this.license_plate = new StringField(true); this.insurance = new StringField(true); // this.isdevice = new StringField(true); ValidatableObject.prototype.init.apply(this, arguments); }; RegisterDriverRequest.prototype._name = function(){ return "RegisterDriverRequest"; }; /** * @Request("RegisterDriverRequest") */ module.exports = RegisterDriverRequest;<file_sep>/** * Created by hamid on 8/12/16. */ 'use strict'; const StringField = require("../../../requestDataHandler/dataTypes/StringField"); const BooleanField = require("../../../requestDataHandler/dataTypes/BooleanField"); const IdField = require("../../../requestDataHandler/dataTypes/IdField"); const IntegerField = require("../../../requestDataHandler/dataTypes/IntegerField"); const LoginUserResponse = require("../user/LoginUserResponse"); function RegisterDriverResponse(){ this.init.apply(this, arguments); } RegisterDriverResponse.prototype = Object.create(LoginUserResponse.prototype); RegisterDriverResponse.prototype.init = function(){ this.id = new IdField(true); this.email = new StringField(false); LoginUserResponse.prototype.init.apply(this, arguments); return this; }; RegisterDriverResponse.prototype._name = function(){ return "RegisterDriverResponse"; }; /** * @Response("RegisterDriverResponse") * @Component() */ module.exports = RegisterDriverResponse;<file_sep>/** * Created by hamid on 1/27/17. */ 'use strict'; const StringField = require("../../requestDataHandler/dataTypes/StringField"); const BooleanField = require("../../requestDataHandler/dataTypes/BooleanField"); const NumberField = require("../../requestDataHandler/dataTypes/NumberField"); const IntegerField = require("../../requestDataHandler/dataTypes/IntegerField"); const UserInfoResponse = require("./user/UserInfoResponse"); const BaseObject = require("../../requestDataHandler/BaseObject"); function CarTypeListItemResponse(){ this.init.apply(this, arguments); } CarTypeListItemResponse.prototype = Object.create(BaseObject.prototype); CarTypeListItemResponse.prototype.init = function(){ this.id = new StringField(); this.carType = new StringField(); this.carIcon = new StringField(); BaseObject.prototype.init.apply(this, arguments); }; CarTypeListItemResponse.prototype.initFromData = function(carType){ if(!carType){ return; } let data = { id: carType.getId(), carType: carType.getCarType(), carIcon: carType.getCarIcon(), }; this.init(data); }; CarTypeListItemResponse.prototype._name = function(){ return "CarTypeListItemResponse"; }; /** * @Response("MovieListItemResponse") * @Component() */ module.exports = CarTypeListItemResponse;<file_sep>'use strict'; const Backtory = require("../../provider/LibsProvider").backtory(); var CarTypes = Backtory.Object.extend('CarTypes',{ getId(){return this.get(CarTypes.Col.id)}, getCarType(){return this.get(CarTypes.Col.carType)}, getCarIcon(){return this.get(CarTypes.Col.carIcon)}, setId(value){this.set(CarTypes.Col.id, value)}, setUserName(value){this.set(CarTypes.Col.carType, value)}, setItemNo(value){this.set(CarTypes.Col.carIcon, value)}, },{ get Name(){return 'CarTypes'}, }); CarTypes.Col = { get id(){return '_id'}, get carType(){return 'car_type'}, get carIcon(){return 'car_icon'}, get CreationDate(){return 'createdAt'}, }; Backtory.Object.registerSubclass(CarTypes.Name, CarTypes); module.exports = CarTypes;<file_sep> 'use strict'; const Backtory = require("../../provider/LibsProvider").backtory(); var DriverRating = Backtory.Object.extend('DriverRating',{ getId(){return this.get(DriverRating.Col.id)}, getDriverId(){return this.get(DriverRating.Col.driverId)}, getBookingId(){return this.get(DriverRating.Col.bookingId)}, getStartTime(){return this.get(DriverRating.Col.startTime)}, getEndTime(){return this.get(DriverRating.Col.endTime)}, getDriverFlag(){return this.get(DriverRating.Col.driverFlag)}, setId(value){this.set(DriverRating.Col.id, value)}, setDriverId(value){this.set(DriverRating.Col.driverId, value)}, setBookingId(value){this.set(DriverRating.Col.bookingId, value)}, setStartTime(value){this.set(DriverRating.Col.startTime, value)}, setEndTime(value){this.set(DriverRating.Col.endTime, value)}, setDriverFlag(value){this.set(DriverRating.Col.driverFlag, value)}, },{ get Name(){return 'DriverRating'}, }); DriverRating.Col = { get id(){return 'id'}, get driverId(){return 'driverId'}, get bookingId(){return 'bookingId'}, get startTime(){return 'startTime'}, get endTime(){return 'endTime'}, get driverFlag(){return 'driverFlag'}, }; Backtory.Object.registerSubclass(DriverRating.Name, DriverRating); module.exports = DriverRating;<file_sep> 'use strict'; const Backtory = require("../../provider/LibsProvider").backtory(); var CabDetails = Backtory.Object.extend('CabDetails',{ getCabId(){return this.get(CabDetails.Col.cabId)}, getCarType(){return this.get(CabDetails.Col.carType)}, getCarRate(){return this.get(CabDetails.Col.carRate)}, getTransferType(){return this.get(CabDetails.Col.transferType)}, getIntialKm(){return this.get(CabDetails.Col.intialKm)}, getIntailRate(){return this.get(CabDetails.Col.intailRate)}, getStandardRate(){return this.get(CabDetails.Col.standardRate)}, getFromintialKm(){return this.get(CabDetails.Col.fromintialKm)}, getFromIntailRate(){return this.get(CabDetails.Col.fromIntailRate)}, getFromStandardRate(){return this.get(CabDetails.Col.fromStandardRate)}, getNightFromIntialKm(){return this.get(CabDetails.Col.nighFromIntailKm)}, getNighFromIntailRate(){return this.get(CabDetails.Col.nighFromIntailRate)}, getExtraHour(){return this.get(CabDetails.Col.extraHour)}, getExtraKm(){return this.get(CabDetails.Col.extraKm)}, getTimeType(){return this.get(CabDetails.Col.timeType)}, getPackage(){return this.get(CabDetails.Col.package)}, getNightPackage(){return this.get(CabDetails.Col.nightPackage)}, getIcon(){return this.get(CabDetails.Col.icon)}, getDescription(){return this.get(CabDetails.Col.description)}, getRideTimeRate(){return this.get(CabDetails.Col.rideTimeRate)}, getNightRideTimeRate(){return this.get(CabDetails.Col.nightRideTimeRate)}, getDayStartTime(){return this.get(CabDetails.Col.dayStartTime)}, getDayEndTime(){return this.get(CabDetails.Col.dayEndTime)}, getNightStartTime(){return this.get(CabDetails.Col.nightStartTime)}, getNightEndTime(){return this.get(CabDetails.Col.nightEndTime)}, getNightIntailRate(){return this.get(CabDetails.Col.nightIntailRate)}, getNightStandardRate(){return this.get(CabDetails.Col.nightStandardRate)}, getSeatCapacity(){return this.get(CabDetails.Col.seatCapacity)}, setCabId(){this.set(CabDetails.Col.cabId,value)}, setCarType(){this.set(CabDetails.Col.carType,value)}, setCarRate(){this.set(CabDetails.Col.carRate,value)}, setTransferType(){this.set(CabDetails.Col.transferType,value)}, setIntialKm(){this.set(CabDetails.Col.intialKm,value)}, setIntailRate(){this.set(CabDetails.Col.intailRate,value)}, setStandardRate(){this.set(CabDetails.Col.standardRate,value)}, setFromintialKm(){this.set(CabDetails.Col.fromintialKm,value)}, setFromIntailRate(){this.set(CabDetails.Col.fromIntailRate,value)}, setFromStandardRate(){this.set(CabDetails.Col.fromStandardRate,value)}, setNightFromIntialKm(){this.set(CabDetails.Col.nighFromIntailKm,value)}, setNighFromIntailRate(){this.set(CabDetails.Col.nighFromIntailRate,value)}, setExtraHour(){this.set(CabDetails.Col.extraHour,value)}, setExtraKm(){this.set(CabDetails.Col.extraKm,value)}, setTimeType(){this.set(CabDetails.Col.timeType,value)}, setPackage(){this.set(CabDetails.Col.package,value)}, setNightPackage(){this.set(CabDetails.Col.nightPackage,value)}, setIcon(){this.set(CabDetails.Col.icon,value)}, setDescription(){this.set(CabDetails.Col.description,value)}, setRideTimeRate(){this.set(CabDetails.Col.rideTimeRate,value)}, setNightRideTimeRate(){this.set(CabDetails.Col.nightRideTimeRate,value)}, setDayStartTime(){this.set(CabDetails.Col.dayStartTime,value)}, setDayEndTime(){this.set(CabDetails.Col.dayEndTime,value)}, setNightStartTime(){this.set(CabDetails.Col.nightStartTime,value)}, setNightEndTime(){this.set(CabDetails.Col.nightEndTime,value)}, setNightIntailRate(){this.set(CabDetails.Col.nightIntailRate,value)}, setNightStandardRate(){this.set(CabDetails.Col.nightStandardRate,value)}, setSeatCapacity(){this.set(CabDetails.Col.seatCapacity,value)}, },{ get Name(){return 'CabDetails'}, }); CabDetails.Col = { get cabId() {return 'cabId'}, get carType(){return 'carType'}, get carRate(){return 'carRate'}, get transferType(){return 'transferType'}, get intialKm() {return 'intialKm'}, get intailRate(){return 'intailRate'}, get standardRate(){return 'standardRate'}, get fromintialKm(){return 'fromintialKm'}, get fromIntailRate(){return 'fromIntailRate'}, get fromStandardRate(){return 'fromStandardRate'}, get nightFromIntialKm(){return 'nightFromIntialKm'}, get nighFromIntailRate(){return 'nighFromIntailRate'}, get extraHour(){return 'extraHour'}, get extraKm(){return 'extraKm'}, get timeType(){return 'timeType'}, get package(){return 'package'}, get nightPackage(){return 'nightPackage'}, get icon(){return 'icon'}, get description(){return 'description'}, get rideTimeRate(){return 'rideTimeRate'}, get nightRideTimeRate(){return 'nightRideTimeRate'}, get dayStartTime(){return 'dayStartTime'}, get dayEndTime(){return 'dayEndTime'}, get nightStartTime(){return 'nightStartTime'}, get nightEndTime(){return 'nightEndTime'}, get nightIntailRate(){return 'nightIntailRate'}, get nightStandardRate(){return 'nightStandardRate'}, get seatCapacity(){return 'seatCapacity'}, }; Backtory.Object.registerSubclass(CabDetails.Name, CabDetails); module.exports = CabDetails;
19f368c098d19f5df00e25998bbaa33297c83aa6
[ "JavaScript" ]
11
JavaScript
aminzaheri/Snap
2dc91ae47f7ba8bfab76998456b89490db1200ff
6df4b7dd3e64f939dd3aa16d4188eb5a9b1bd58b
refs/heads/master
<repo_name>pavva94/JackTheGiant<file_sep>/Assets/Scripts/Cloud/CloudSpawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CloudSpawner : MonoBehaviour { [SerializeField] private GameObject[] clouds; private float distanceBetweenCloud = 3.0f; // min e max dove possono spawnare le nuvole, i bordi della telecamera private float minX, maxX; // la posizione in Y della nuvola più in bassom, dobbiamo saperla per spawnare nuvole sotto questa private float lastCloudPositionY; private float controlX; [SerializeField] private GameObject[] collectables; private GameObject player; // Use this for initialization void Awake () { controlX = 0f; SetMinAndMaxX (); CreateClouds (); player = GameObject.Find ("Player"); for (int i = 0; i < collectables.Length; i++) { collectables [i].SetActive (false); } } void Start () { PositionThePlayer (); } void SetMinAndMaxX () { // converte la risolizione dello schermo in coordinate di Unity Vector3 bounds = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width, Screen.height, 0f)); // prendo il max X in cui istanziare le nuvole, tolgo 0.5 perchè senno metà nuvola potrebbe andare fuori dallo schermo dato che Unity prende il centro del GameObject maxX = bounds.x - 0.5f; minX = - bounds.x + 0.5f; } void Shuffle (GameObject[] arrayToShuffle) { for (int i = 0; i < arrayToShuffle.Length; i++) { GameObject temp = arrayToShuffle [i]; int random = Random.Range (i, arrayToShuffle.Length); arrayToShuffle [i] = arrayToShuffle [random]; arrayToShuffle [random] = temp; } } void CreateClouds () { Shuffle (clouds); float posistionY = 0f; for (int i = 0; i < clouds.Length; i++) { Vector3 temp = clouds [i].transform.position; temp.y = posistionY; // controllo la logica di spawn della nuvola sulle x per non metterle una sotto l'altra // controlX sono più o meno gli step di spawn delle nuvole controllando così lo zig zag delle nuvole if (controlX == 0) { temp.x = Random.Range (0.0f, maxX); controlX = 1; } else if (controlX == 1) { temp.x = Random.Range (0.0f, minX); controlX = 2; } else if (controlX == 2) { temp.x = Random.Range (1.0f, maxX); controlX = 3; } else if (controlX == 3) { temp.x = Random.Range (-1.0f, minX); controlX = 0; } // mi salvo la posizione Y della nuvola lastCloudPositionY = posistionY; clouds [i].transform.position = temp; posistionY -= distanceBetweenCloud; } } void PositionThePlayer () { GameObject[] darkClouds = GameObject.FindGameObjectsWithTag ("Deadly"); GameObject[] cloudsInGame = GameObject.FindGameObjectsWithTag ("Cloud"); for (int i = 0; i < darkClouds.Length; i++) { // se la prima nuvola è una darkCloud allora la scambio con la prima nuvola chiara if (darkClouds [i].transform.position.y == 0f) { Vector3 t = darkClouds [i].transform.position; darkClouds [i].transform.position = new Vector3 ( cloudsInGame [0].transform.position.x, cloudsInGame [0].transform.position.x, cloudsInGame [0].transform.position.y ); cloudsInGame [0].transform.position = t; } } // riposiziono il player alla prima nuvola Vector3 temp = cloudsInGame[0].transform.position; // trovo la prima nuvola for (int i = 1; i < cloudsInGame.Length; i++) { if (temp.y < cloudsInGame [i].transform.position.y) { temp = cloudsInGame [i].transform.position; } } // metto il player sopra la nuvola temp.y += 0.6f; player.transform.position = temp; } void OnTriggerEnter2D (Collider2D target) { if (target.tag == "Cloud" || target.tag == "Deadly") { // se il target è l'ultima nuvola allora devo ricreare le nuvole if (target.transform.position.y == lastCloudPositionY) { Shuffle (clouds); Shuffle (collectables); Vector3 temp = target.transform.position; for (int i = 0; i < clouds.Length; i++) { // solo se la nuvola non è attiva allora la riposiziono if (!clouds [i].activeInHierarchy) { // controllo la logica di spawn della nuvola sulle x per non metterle una sotto l'altra // controlX sono più o meno gli step di spawn delle nuvole controllando così lo zig zag delle nuvole if (controlX == 0) { temp.x = Random.Range (0.0f, maxX); controlX = 1; } else if (controlX == 1) { temp.x = Random.Range (0.0f, minX); controlX = 2; } else if (controlX == 2) { temp.x = Random.Range (1.0f, maxX); controlX = 3; } else if (controlX == 3) { temp.x = Random.Range (-1.0f, minX); controlX = 0; } temp.y -= distanceBetweenCloud; // mi salvo l'ultima posizione Y della nuvola istanziata lastCloudPositionY = temp.y; clouds [i].transform.position = temp; clouds [i].SetActive (true); int random = Random.Range (0, collectables.Length); // spawn dei bonus sopra le nuvole non nere if (clouds [i].tag != "Deadly") { // se il bonus è già attivo lo lascio dov'è if (!collectables [random].activeInHierarchy) { Vector3 temp2 = clouds [i].transform.position; temp2.y += 0.7f; // spawn della vita solo se il giocatore ha meno di due vite if (collectables [random].tag == "Life") { if (PlayerScore.lifeCount < 2) { collectables [random].transform.position = temp2; collectables [random].SetActive (true); } } else { // metto il bonus sopra la nuvola collectables [random].transform.position = temp2; collectables [random].SetActive (true); } } } } } // controllo la logica di spawn della nuvola sulle x per non metterle una sotto l'altra // controlX sono più o meno gli step di spawn delle nuvole controllando così lo zig zag delle nuvole if (controlX == 0) { temp.x = Random.Range (0.0f, maxX); controlX = 1; } else if (controlX == 1) { temp.x = Random.Range (0.0f, minX); controlX = 2; } else if (controlX == 2) { temp.x = Random.Range (1.0f, maxX); controlX = 3; } else if (controlX == 3) { temp.x = Random.Range (-1.0f, minX); controlX = 0; } } } } } <file_sep>/Assets/Scripts/Collectables/CollectablesScript.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollectablesScript : MonoBehaviour { // funzione chiamata quando viene attivato il componente void OnEnable() { // distruggo il componente dopo x secondi Invoke ("DestroyCollectable", 8f); } void DestroyCollectable() { gameObject.SetActive (false); } } <file_sep>/Assets/Scripts/Game Controllers/GameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManager : MonoBehaviour { public static GameManager instance; [HideInInspector] public bool gameStartedFromMainMenu, gameRestartedAfterPlayerDied; [HideInInspector] public int score, coinScore, lifeScore; // Use this for initialization void Awake () { MakeSingleton (); } void Start() { InitializeVariables (); } // utilizzo OnEnable e OnDisable per delegare alla fine del loading della scena la funzione // in questo modo quando la scena e caricata eseguo la funzione OnSceneLoaded() void OnEnable() { //Tell our 'OnSceneLoaded' function to start listening for a scene change as soon as this script is enabled. SceneManager.sceneLoaded += OnSceneLoaded; } void OnDisable() { //Tell our 'OnSceneLoaded' function to stop listening for a scene change as soon as this script is disabled. Remember to always have an unsubscription for every delegate you subscribe to! SceneManager.sceneLoaded -= OnSceneLoaded; } void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (SceneManager.GetActiveScene ().name == "Gameplay") { if (gameRestartedAfterPlayerDied) { GameplayController.instance.SetScore (score); GameplayController.instance.SetCoinScore (coinScore); GameplayController.instance.SetLifeScore (lifeScore); PlayerScore.scoreCount = score; PlayerScore.coinCount = coinScore; PlayerScore.lifeCount = lifeScore; } else if (gameStartedFromMainMenu) { GameplayController.instance.SetScore (0); GameplayController.instance.SetCoinScore (0); GameplayController.instance.SetLifeScore (2); PlayerScore.scoreCount = 0; PlayerScore.coinCount = 0; PlayerScore.lifeCount = 2; } } } void InitializeVariables() { // se è la prima volta che apriamo il gioco // PlayerPref non ha nessuna chiave if (!PlayerPrefs.HasKey("Game Initialized")) { GamePreferences.SetEasyDifficulty(0); GamePreferences.SetEasyDifficultyHighScore (0); GamePreferences.SetEasyDifficultyCoinScore (0); GamePreferences.SetMediumDifficulty(1); // difficoltà base GamePreferences.SetMediumDifficultyHighScore (0); GamePreferences.SetMediumDifficultyCoinScore (0); GamePreferences.SetHardDifficulty(0); GamePreferences.SetHardDifficultyHighScore (0); GamePreferences.SetHardDifficultyCoinScore (0); GamePreferences.SetMusicState (0); // salvo questa chiave così non ci torno più qui PlayerPrefs.SetInt ("Game Initialized", 123); } } void MakeSingleton () { // così si crea un SINGLETON // questo gameObject viene chiamato ogni volta che si carica questa scne // quindi creerebbe ogni volta un nuovo gamemanager // la prima volta va bene e lo crea mettendolo anche come DontDestroy // la seconda volta crea un nuovo gameObject ma noi abbiamo già il primo // quindi questo secondo oggetto viene distrutto // e così ogni volta che si carica la scena. // in questo modo abbiamo sempre e solo il primo creato if (instance != null) { Destroy (gameObject); } else { instance = this; // viene passato ovunque nelle varie scene DontDestroyOnLoad (gameObject); } } public void CheckGameStatus(int score, int coinScore, int lifeScore) { // controlliamo se non ho più vite, allora gameover if (lifeScore < 0) { if (GamePreferences.GetEasyDifficulty () == 1) { int highScore = GamePreferences.GetEasyDifficultyHighScore (); int coinHighScore = GamePreferences.GetEasyDifficultyCoinScore (); if (highScore < score) GamePreferences.SetEasyDifficultyHighScore (score); if (coinHighScore < coinScore) { GamePreferences.SetEasyDifficultyCoinScore (coinScore); } } if (GamePreferences.GetMediumDifficulty () == 1) { int highScore = GamePreferences.GetMediumDifficultyHighScore (); int coinHighScore = GamePreferences.GetMediumDifficultyCoinScore (); if (highScore < score) GamePreferences.SetMediumDifficultyHighScore (score); if (coinHighScore < coinScore) { GamePreferences.SetMediumDifficultyCoinScore (coinScore); } } if (GamePreferences.GetHardDifficulty () == 1) { int highScore = GamePreferences.GetHardDifficultyHighScore (); int coinHighScore = GamePreferences.GetHardDifficultyCoinScore (); if (highScore < score) GamePreferences.SetHardDifficultyHighScore (score); if (coinHighScore < coinScore) { GamePreferences.SetHardDifficultyCoinScore (coinScore); } } gameStartedFromMainMenu = false; gameRestartedAfterPlayerDied = false; GameplayController.instance.GameOverShowPanel (score, coinScore); } else { // se ho ancora delle vite allora mi salvo il punteggio perchè devo ricominciare! this.score = score; this.coinScore = coinScore; this.lifeScore = lifeScore; gameRestartedAfterPlayerDied = true; gameStartedFromMainMenu = false; GameplayController.instance.PlayerDiedRestartTheGame (); } } } <file_sep>/Assets/Scripts/Game Controllers/HighscoreController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class HighscoreController : MonoBehaviour { [SerializeField] private Text scoreText, coinText; // Use this for initialization void Start () { // faccio vedere lo score corretto in base alla difficoltà SetTheScoreBasedOnDifficulty (); } void SetScore(int score, int coinScore) { scoreText.text = score.ToString (); coinText.text = coinScore.ToString (); } void SetTheScoreBasedOnDifficulty() { if (GamePreferences.GetEasyDifficulty () == 1) { SetScore (GamePreferences.GetEasyDifficultyHighScore (), GamePreferences.GetEasyDifficultyCoinScore ()); } if (GamePreferences.GetMediumDifficulty () == 1) { SetScore (GamePreferences.GetMediumDifficultyHighScore (), GamePreferences.GetMediumDifficultyCoinScore ()); } if (GamePreferences.GetHardDifficulty () == 1) { SetScore (GamePreferences.GetHardDifficultyHighScore (), GamePreferences.GetHardDifficultyCoinScore ()); } } public void GoBackToMenu() { SceneManager.LoadScene ("MainMenu"); } } <file_sep>/Assets/Scripts/Player/PlayerBounds.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerBounds : MonoBehaviour { // min e max dove possono spawnare le nuvole, i bordi della telecamera private float minX, maxX; // Use this for initialization void Start () { SetMinAndMaxX (); } // Update is called once per frame void Update () { if (transform.position.x < minX) { Vector3 temp = transform.position; temp.x = minX; transform.position = temp; } if (transform.position.x > maxX) { Vector3 temp = transform.position; temp.x = maxX; transform.position = temp; } } void SetMinAndMaxX () { // converte la risolizione dello schermo in coordinate di Unity Vector3 bounds = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width, Screen.height, 0f)); // prendo il max X in cui istanziare le nuvole, tolgo 0.5 perchè senno metà nuvola potrebbe andare fuori dallo schermo dato che Unity prende il centro del GameObject maxX = bounds.x - 0.2f; minX = - bounds.x + 0.2f; } }
adf34018f888577348717d7349e2e903190ff105
[ "C#" ]
5
C#
pavva94/JackTheGiant
a40365f95a1939796f7785ad20e310348da3324f
eea6edf160e7f91172d665a769ae879459b33bbe